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 command-line abbreviations. */
58 static config_abbrev_t _option_abbrevs
[] = {
63 PLURAL(LongLivedPort
),
64 PLURAL(HiddenServiceNode
),
65 PLURAL(HiddenServiceExcludeNode
),
68 PLURAL(RendExcludeNode
),
69 PLURAL(StrictEntryNode
),
70 PLURAL(StrictExitNode
),
72 { "AllowUnverifiedNodes", "AllowInvalidNodes", 0, 0},
73 { "AutomapHostSuffixes", "AutomapHostsSuffixes", 0, 0},
74 { "AutomapHostOnResolve", "AutomapHostsOnResolve", 0, 0},
75 { "BandwidthRateBytes", "BandwidthRate", 0, 0},
76 { "BandwidthBurstBytes", "BandwidthBurst", 0, 0},
77 { "DirFetchPostPeriod", "StatusFetchPeriod", 0, 0},
78 { "MaxConn", "ConnLimit", 0, 1},
79 { "ORBindAddress", "ORListenAddress", 0, 0},
80 { "DirBindAddress", "DirListenAddress", 0, 0},
81 { "SocksBindAddress", "SocksListenAddress", 0, 0},
82 { "UseHelperNodes", "UseEntryGuards", 0, 0},
83 { "NumHelperNodes", "NumEntryGuards", 0, 0},
84 { "UseEntryNodes", "UseEntryGuards", 0, 0},
85 { "NumEntryNodes", "NumEntryGuards", 0, 0},
86 { "ResolvConf", "ServerDNSResolvConfFile", 0, 1},
87 { "SearchDomains", "ServerDNSSearchDomains", 0, 1},
88 { "ServerDNSAllowBrokenResolvConf", "ServerDNSAllowBrokenConfig", 0, 0 },
89 { "PreferTunnelledDirConns", "PreferTunneledDirConns", 0, 0},
90 { "BridgeAuthoritativeDirectory", "BridgeAuthoritativeDir", 0, 0},
91 { "HashedControlPassword", "__HashedControlSessionPassword", 1, 0},
94 /* A list of state-file abbreviations, for compatibility. */
95 static config_abbrev_t _state_abbrevs
[] = {
96 { "AccountingBytesReadInterval", "AccountingBytesReadInInterval", 0, 0 },
97 { "HelperNode", "EntryGuard", 0, 0 },
98 { "HelperNodeDownSince", "EntryGuardDownSince", 0, 0 },
99 { "HelperNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
100 { "EntryNode", "EntryGuard", 0, 0 },
101 { "EntryNodeDownSince", "EntryGuardDownSince", 0, 0 },
102 { "EntryNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
107 /** A variable allowed in the configuration file or on the command line. */
108 typedef struct config_var_t
{
109 const char *name
; /**< The full keyword (case insensitive). */
110 config_type_t type
; /**< How to interpret the type and turn it into a
112 off_t var_offset
; /**< Offset of the corresponding member of or_options_t. */
113 const char *initvalue
; /**< String (or null) describing initial value. */
116 /** An entry for config_vars: "The option <b>name</b> has type
117 * CONFIG_TYPE_<b>conftype</b>, and corresponds to
118 * or_options_t.<b>member</b>"
120 #define VAR(name,conftype,member,initvalue) \
121 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_options_t, member), \
123 /** As VAR, but the option name and member name are the same. */
124 #define V(member,conftype,initvalue) \
125 VAR(#member, conftype, member, initvalue)
126 /** An entry for config_vars: "The option <b>name</b> is obsolete." */
127 #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL }
129 /** Array of configuration options. Until we disallow nonstandard
130 * abbreviations, order is significant, since the first matching option will
133 static config_var_t _option_vars
[] = {
134 OBSOLETE("AccountingMaxKB"),
135 V(AccountingMax
, MEMUNIT
, "0 bytes"),
136 V(AccountingStart
, STRING
, NULL
),
137 V(Address
, STRING
, NULL
),
138 V(AllowInvalidNodes
, CSV
, "middle,rendezvous"),
139 V(AllowNonRFC953Hostnames
, BOOL
, "0"),
140 V(AllowSingleHopCircuits
, BOOL
, "0"),
141 V(AllowSingleHopExits
, BOOL
, "0"),
142 V(AlternateBridgeAuthority
, LINELIST
, NULL
),
143 V(AlternateDirAuthority
, LINELIST
, NULL
),
144 V(AlternateHSAuthority
, LINELIST
, NULL
),
145 V(AssumeReachable
, BOOL
, "0"),
146 V(AuthDirBadDir
, LINELIST
, NULL
),
147 V(AuthDirBadExit
, LINELIST
, NULL
),
148 V(AuthDirInvalid
, LINELIST
, NULL
),
149 V(AuthDirReject
, LINELIST
, NULL
),
150 V(AuthDirRejectUnlisted
, BOOL
, "0"),
151 V(AuthDirListBadDirs
, BOOL
, "0"),
152 V(AuthDirListBadExits
, BOOL
, "0"),
153 V(AuthDirMaxServersPerAddr
, UINT
, "2"),
154 V(AuthDirMaxServersPerAuthAddr
,UINT
, "5"),
155 VAR("AuthoritativeDirectory", BOOL
, AuthoritativeDir
, "0"),
156 V(AutomapHostsOnResolve
, BOOL
, "0"),
157 V(AutomapHostsSuffixes
, CSV
, ".onion,.exit"),
158 V(AvoidDiskWrites
, BOOL
, "0"),
159 V(BandwidthBurst
, MEMUNIT
, "10 MB"),
160 V(BandwidthRate
, MEMUNIT
, "5 MB"),
161 V(BridgeAuthoritativeDir
, BOOL
, "0"),
162 VAR("Bridge", LINELIST
, Bridges
, NULL
),
163 V(BridgePassword
, STRING
, NULL
),
164 V(BridgeRecordUsageByCountry
, BOOL
, "1"),
165 V(BridgeRelay
, BOOL
, "0"),
166 V(CircuitBuildTimeout
, INTERVAL
, "1 minute"),
167 V(CircuitIdleTimeout
, INTERVAL
, "1 hour"),
168 V(ClientDNSRejectInternalAddresses
, BOOL
,"1"),
169 V(ClientOnly
, BOOL
, "0"),
170 V(ConnLimit
, UINT
, "1000"),
171 V(ConstrainedSockets
, BOOL
, "0"),
172 V(ConstrainedSockSize
, MEMUNIT
, "8192"),
173 V(ContactInfo
, STRING
, NULL
),
174 V(ControlListenAddress
, LINELIST
, NULL
),
175 V(ControlPort
, UINT
, "0"),
176 V(ControlSocket
, LINELIST
, NULL
),
177 V(CookieAuthentication
, BOOL
, "0"),
178 V(CookieAuthFileGroupReadable
, BOOL
, "0"),
179 V(CookieAuthFile
, STRING
, NULL
),
180 V(DataDirectory
, FILENAME
, NULL
),
181 OBSOLETE("DebugLogFile"),
182 V(DirAllowPrivateAddresses
, BOOL
, NULL
),
183 V(TestingAuthDirTimeToLearnReachability
, INTERVAL
, "30 minutes"),
184 V(DirListenAddress
, LINELIST
, NULL
),
185 OBSOLETE("DirFetchPeriod"),
186 V(DirPolicy
, LINELIST
, NULL
),
187 V(DirPort
, UINT
, "0"),
188 V(DirPortFrontPage
, FILENAME
, NULL
),
189 OBSOLETE("DirPostPeriod"),
190 #ifdef ENABLE_GEOIP_STATS
191 V(DirRecordUsageByCountry
, BOOL
, "0"),
192 V(DirRecordUsageGranularity
, UINT
, "4"),
193 V(DirRecordUsageRetainIPs
, INTERVAL
, "14 days"),
194 V(DirRecordUsageSaveInterval
, INTERVAL
, "6 hours"),
196 VAR("DirServer", LINELIST
, DirServers
, NULL
),
197 V(DNSPort
, UINT
, "0"),
198 V(DNSListenAddress
, LINELIST
, NULL
),
199 V(DownloadExtraInfo
, BOOL
, "0"),
200 V(EnforceDistinctSubnets
, BOOL
, "1"),
201 V(EntryNodes
, ROUTERSET
, NULL
),
202 V(TestingEstimatedDescriptorPropagationTime
, INTERVAL
, "10 minutes"),
203 V(ExcludeNodes
, ROUTERSET
, NULL
),
204 V(ExcludeExitNodes
, ROUTERSET
, NULL
),
205 V(ExcludeSingleHopRelays
, BOOL
, "1"),
206 V(ExitNodes
, ROUTERSET
, NULL
),
207 V(ExitPolicy
, LINELIST
, NULL
),
208 V(ExitPolicyRejectPrivate
, BOOL
, "1"),
209 V(FallbackNetworkstatusFile
, FILENAME
,
210 SHARE_DATADIR PATH_SEPARATOR
"tor" PATH_SEPARATOR
"fallback-consensus"),
211 V(FascistFirewall
, BOOL
, "0"),
212 V(FirewallPorts
, CSV
, ""),
213 V(FastFirstHopPK
, BOOL
, "1"),
214 V(FetchDirInfoEarly
, BOOL
, "0"),
215 V(FetchServerDescriptors
, BOOL
, "1"),
216 V(FetchHidServDescriptors
, BOOL
, "1"),
217 V(FetchUselessDescriptors
, BOOL
, "0"),
219 V(GeoIPFile
, FILENAME
, "<default>"),
221 V(GeoIPFile
, FILENAME
,
222 SHARE_DATADIR PATH_SEPARATOR
"tor" PATH_SEPARATOR
"geoip"),
225 V(HardwareAccel
, BOOL
, "0"),
226 V(HashedControlPassword
, LINELIST
, NULL
),
227 V(HidServDirectoryV2
, BOOL
, "1"),
228 VAR("HiddenServiceDir", LINELIST_S
, RendConfigLines
, NULL
),
229 OBSOLETE("HiddenServiceExcludeNodes"),
230 OBSOLETE("HiddenServiceNodes"),
231 VAR("HiddenServiceOptions",LINELIST_V
, RendConfigLines
, NULL
),
232 VAR("HiddenServicePort", LINELIST_S
, RendConfigLines
, NULL
),
233 VAR("HiddenServiceVersion",LINELIST_S
, RendConfigLines
, NULL
),
234 VAR("HiddenServiceAuthorizeClient",LINELIST_S
,RendConfigLines
, NULL
),
235 V(HidServAuth
, LINELIST
, NULL
),
236 V(HSAuthoritativeDir
, BOOL
, "0"),
237 V(HSAuthorityRecordStats
, BOOL
, "0"),
238 V(HttpProxy
, STRING
, NULL
),
239 V(HttpProxyAuthenticator
, STRING
, NULL
),
240 V(HttpsProxy
, STRING
, NULL
),
241 V(HttpsProxyAuthenticator
, STRING
, NULL
),
242 OBSOLETE("IgnoreVersion"),
243 V(KeepalivePeriod
, INTERVAL
, "5 minutes"),
244 VAR("Log", LINELIST
, Logs
, NULL
),
245 OBSOLETE("LinkPadding"),
246 OBSOLETE("LogLevel"),
248 V(LongLivedPorts
, CSV
,
249 "21,22,706,1863,5050,5190,5222,5223,6667,6697,8300"),
250 VAR("MapAddress", LINELIST
, AddressMap
, NULL
),
251 V(MaxAdvertisedBandwidth
, MEMUNIT
, "1 GB"),
252 V(MaxCircuitDirtiness
, INTERVAL
, "10 minutes"),
253 V(MaxOnionsPending
, UINT
, "100"),
254 OBSOLETE("MonthlyAccountingStart"),
255 V(MyFamily
, STRING
, NULL
),
256 V(NewCircuitPeriod
, INTERVAL
, "30 seconds"),
257 VAR("NamingAuthoritativeDirectory",BOOL
, NamingAuthoritativeDir
, "0"),
258 V(NatdListenAddress
, LINELIST
, NULL
),
259 V(NatdPort
, UINT
, "0"),
260 V(Nickname
, STRING
, NULL
),
261 V(NoPublish
, BOOL
, "0"),
262 VAR("NodeFamily", LINELIST
, NodeFamilies
, NULL
),
263 V(NumCpus
, UINT
, "1"),
264 V(NumEntryGuards
, UINT
, "3"),
265 V(ORListenAddress
, LINELIST
, NULL
),
266 V(ORPort
, UINT
, "0"),
267 V(OutboundBindAddress
, STRING
, NULL
),
268 OBSOLETE("PathlenCoinWeight"),
269 V(PidFile
, STRING
, NULL
),
270 V(TestingTorNetwork
, BOOL
, "0"),
271 V(PreferTunneledDirConns
, BOOL
, "1"),
272 V(ProtocolWarnings
, BOOL
, "0"),
273 V(PublishServerDescriptor
, CSV
, "1"),
274 V(PublishHidServDescriptors
, BOOL
, "1"),
275 V(ReachableAddresses
, LINELIST
, NULL
),
276 V(ReachableDirAddresses
, LINELIST
, NULL
),
277 V(ReachableORAddresses
, LINELIST
, NULL
),
278 V(RecommendedVersions
, LINELIST
, NULL
),
279 V(RecommendedClientVersions
, LINELIST
, NULL
),
280 V(RecommendedServerVersions
, LINELIST
, NULL
),
281 OBSOLETE("RedirectExit"),
282 V(RejectPlaintextPorts
, CSV
, ""),
283 V(RelayBandwidthBurst
, MEMUNIT
, "0"),
284 V(RelayBandwidthRate
, MEMUNIT
, "0"),
285 OBSOLETE("RendExcludeNodes"),
286 OBSOLETE("RendNodes"),
287 V(RendPostPeriod
, INTERVAL
, "1 hour"),
288 V(RephistTrackTime
, INTERVAL
, "24 hours"),
289 OBSOLETE("RouterFile"),
290 V(RunAsDaemon
, BOOL
, "0"),
291 V(RunTesting
, BOOL
, "0"),
292 V(SafeLogging
, BOOL
, "1"),
293 V(SafeSocks
, BOOL
, "0"),
294 V(ServerDNSAllowBrokenConfig
, BOOL
, "1"),
295 V(ServerDNSAllowNonRFC953Hostnames
, BOOL
,"0"),
296 V(ServerDNSDetectHijacking
, BOOL
, "1"),
297 V(ServerDNSRandomizeCase
, BOOL
, "1"),
298 V(ServerDNSResolvConfFile
, STRING
, NULL
),
299 V(ServerDNSSearchDomains
, BOOL
, "0"),
300 V(ServerDNSTestAddresses
, CSV
,
301 "www.google.com,www.mit.edu,www.yahoo.com,www.slashdot.org"),
302 V(ShutdownWaitLength
, INTERVAL
, "30 seconds"),
303 V(SocksListenAddress
, LINELIST
, NULL
),
304 V(SocksPolicy
, LINELIST
, NULL
),
305 V(SocksPort
, UINT
, "9050"),
306 V(SocksTimeout
, INTERVAL
, "2 minutes"),
307 OBSOLETE("StatusFetchPeriod"),
308 V(StrictEntryNodes
, BOOL
, "0"),
309 V(StrictExitNodes
, BOOL
, "0"),
311 V(TestSocks
, BOOL
, "0"),
313 V(TrackHostExits
, CSV
, NULL
),
314 V(TrackHostExitsExpire
, INTERVAL
, "30 minutes"),
315 OBSOLETE("TrafficShaping"),
316 V(TransListenAddress
, LINELIST
, NULL
),
317 V(TransPort
, UINT
, "0"),
318 V(TunnelDirConns
, BOOL
, "1"),
319 V(UpdateBridgesFromAuthority
, BOOL
, "0"),
320 V(UseBridges
, BOOL
, "0"),
321 V(UseEntryGuards
, BOOL
, "1"),
322 V(User
, STRING
, NULL
),
323 VAR("V1AuthoritativeDirectory",BOOL
, V1AuthoritativeDir
, "0"),
324 VAR("V2AuthoritativeDirectory",BOOL
, V2AuthoritativeDir
, "0"),
325 VAR("V3AuthoritativeDirectory",BOOL
, V3AuthoritativeDir
, "0"),
326 V(TestingV3AuthInitialVotingInterval
, INTERVAL
, "30 minutes"),
327 V(TestingV3AuthInitialVoteDelay
, INTERVAL
, "5 minutes"),
328 V(TestingV3AuthInitialDistDelay
, INTERVAL
, "5 minutes"),
329 V(V3AuthVotingInterval
, INTERVAL
, "1 hour"),
330 V(V3AuthVoteDelay
, INTERVAL
, "5 minutes"),
331 V(V3AuthDistDelay
, INTERVAL
, "5 minutes"),
332 V(V3AuthNIntervalsValid
, UINT
, "3"),
333 V(V3AuthUseLegacyKey
, BOOL
, "0"),
334 VAR("VersioningAuthoritativeDirectory",BOOL
,VersioningAuthoritativeDir
, "0"),
335 V(VirtualAddrNetwork
, STRING
, "127.192.0.0/10"),
336 V(WarnPlaintextPorts
, CSV
, "23,109,110,143"),
337 VAR("__ReloadTorrcOnSIGHUP", BOOL
, ReloadTorrcOnSIGHUP
, "1"),
338 VAR("__AllDirActionsPrivate", BOOL
, AllDirActionsPrivate
, "0"),
339 VAR("__DisablePredictedCircuits",BOOL
,DisablePredictedCircuits
, "0"),
340 VAR("__LeaveStreamsUnattached",BOOL
, LeaveStreamsUnattached
, "0"),
341 VAR("__HashedControlSessionPassword", LINELIST
, HashedControlSessionPassword
,
343 V(MinUptimeHidServDirectoryV2
, INTERVAL
, "24 hours"),
344 { NULL
, CONFIG_TYPE_OBSOLETE
, 0, NULL
}
347 /* Keep defaults synchronous with man page and config value check. */
348 static config_var_t testing_tor_network_defaults
[] = {
349 V(ServerDNSAllowBrokenConfig
, BOOL
, "1"),
350 V(DirAllowPrivateAddresses
, BOOL
, "1"),
351 V(EnforceDistinctSubnets
, BOOL
, "0"),
352 V(AssumeReachable
, BOOL
, "1"),
353 V(AuthDirMaxServersPerAddr
, UINT
, "0"),
354 V(AuthDirMaxServersPerAuthAddr
,UINT
, "0"),
355 V(ClientDNSRejectInternalAddresses
, BOOL
,"0"),
356 V(ExitPolicyRejectPrivate
, BOOL
, "0"),
357 V(V3AuthVotingInterval
, INTERVAL
, "5 minutes"),
358 V(V3AuthVoteDelay
, INTERVAL
, "20 seconds"),
359 V(V3AuthDistDelay
, INTERVAL
, "20 seconds"),
360 V(TestingV3AuthInitialVotingInterval
, INTERVAL
, "5 minutes"),
361 V(TestingV3AuthInitialVoteDelay
, INTERVAL
, "20 seconds"),
362 V(TestingV3AuthInitialDistDelay
, INTERVAL
, "20 seconds"),
363 V(TestingAuthDirTimeToLearnReachability
, INTERVAL
, "0 minutes"),
364 V(TestingEstimatedDescriptorPropagationTime
, INTERVAL
, "0 minutes"),
365 { NULL
, CONFIG_TYPE_OBSOLETE
, 0, NULL
}
369 #define VAR(name,conftype,member,initvalue) \
370 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_state_t, member), \
372 static config_var_t _state_vars
[] = {
373 V(AccountingBytesReadInInterval
, MEMUNIT
, NULL
),
374 V(AccountingBytesWrittenInInterval
, MEMUNIT
, NULL
),
375 V(AccountingExpectedUsage
, MEMUNIT
, NULL
),
376 V(AccountingIntervalStart
, ISOTIME
, NULL
),
377 V(AccountingSecondsActive
, INTERVAL
, NULL
),
379 VAR("EntryGuard", LINELIST_S
, EntryGuards
, NULL
),
380 VAR("EntryGuardDownSince", LINELIST_S
, EntryGuards
, NULL
),
381 VAR("EntryGuardUnlistedSince", LINELIST_S
, EntryGuards
, NULL
),
382 VAR("EntryGuardAddedBy", LINELIST_S
, EntryGuards
, NULL
),
383 V(EntryGuards
, LINELIST_V
, NULL
),
385 V(BWHistoryReadEnds
, ISOTIME
, NULL
),
386 V(BWHistoryReadInterval
, UINT
, "900"),
387 V(BWHistoryReadValues
, CSV
, ""),
388 V(BWHistoryWriteEnds
, ISOTIME
, NULL
),
389 V(BWHistoryWriteInterval
, UINT
, "900"),
390 V(BWHistoryWriteValues
, CSV
, ""),
392 V(TorVersion
, STRING
, NULL
),
394 V(LastRotatedOnionKey
, ISOTIME
, NULL
),
395 V(LastWritten
, ISOTIME
, NULL
),
397 { NULL
, CONFIG_TYPE_OBSOLETE
, 0, NULL
}
404 /** Represents an English description of a configuration variable; used when
405 * generating configuration file comments. */
406 typedef struct config_var_description_t
{
408 const char *description
;
409 } config_var_description_t
;
411 static config_var_description_t options_description
[] = {
412 /* ==== general options */
413 { "AvoidDiskWrites", "If non-zero, try to write to disk less frequently than"
414 " we would otherwise." },
415 { "BandwidthRate", "A token bucket limits the average incoming bandwidth on "
416 "this node to the specified number of bytes per second." },
417 { "BandwidthBurst", "Limit the maximum token buffer size (also known as "
418 "burst) to the given number of bytes." },
419 { "ConnLimit", "Minimum number of simultaneous sockets we must have." },
420 { "ConstrainedSockets", "Shrink tx and rx buffers for sockets to avoid "
421 "system limits on vservers and related environments. See man page for "
422 "more information regarding this option." },
423 { "ConstrainedSockSize", "Limit socket buffers to this size when "
424 "ConstrainedSockets is enabled." },
425 /* ControlListenAddress */
426 { "ControlPort", "If set, Tor will accept connections from the same machine "
427 "(localhost only) on this port, and allow those connections to control "
428 "the Tor process using the Tor Control Protocol (described in "
429 "control-spec.txt).", },
430 { "CookieAuthentication", "If this option is set to 1, don't allow any "
431 "connections to the control port except when the connecting process "
432 "can read a file that Tor creates in its data directory." },
433 { "DataDirectory", "Store working data, state, keys, and caches here." },
434 { "DirServer", "Tor only trusts directories signed with one of these "
435 "servers' keys. Used to override the standard list of directory "
437 /* { "FastFirstHopPK", "" }, */
438 /* FetchServerDescriptors, FetchHidServDescriptors,
439 * FetchUselessDescriptors */
440 { "HardwareAccel", "If set, Tor tries to use hardware crypto accelerators "
442 /* HashedControlPassword */
443 { "HTTPProxy", "Force Tor to make all HTTP directory requests through this "
444 "host:port (or host:80 if port is not set)." },
445 { "HTTPProxyAuthenticator", "A username:password pair to be used with "
447 { "HTTPSProxy", "Force Tor to make all TLS (SSL) connectinos through this "
448 "host:port (or host:80 if port is not set)." },
449 { "HTTPSProxyAuthenticator", "A username:password pair to be used with "
451 { "KeepalivePeriod", "Send a padding cell every N seconds to keep firewalls "
452 "from closing our connections while Tor is not in use." },
453 { "Log", "Where to send logging messages. Format is "
454 "minSeverity[-maxSeverity] (stderr|stdout|syslog|file FILENAME)." },
455 { "OutboundBindAddress", "Make all outbound connections originate from the "
456 "provided IP address (only useful for multiple network interfaces)." },
457 { "PIDFile", "On startup, write our PID to this file. On clean shutdown, "
458 "remove the file." },
459 { "PreferTunneledDirConns", "If non-zero, avoid directory servers that "
460 "don't support tunneled connections." },
461 /* PreferTunneledDirConns */
462 /* ProtocolWarnings */
463 /* RephistTrackTime */
464 { "RunAsDaemon", "If set, Tor forks and daemonizes to the background when "
465 "started. Unix only." },
466 { "SafeLogging", "If set to 0, Tor logs potentially sensitive strings "
467 "rather than replacing them with the string [scrubbed]." },
468 { "TunnelDirConns", "If non-zero, when a directory server we contact "
469 "supports it, we will build a one-hop circuit and make an encrypted "
470 "connection via its ORPort." },
471 { "User", "On startup, setuid to this user." },
473 /* ==== client options */
474 { "AllowInvalidNodes", "Where on our circuits should Tor allow servers "
475 "that the directory authorities haven't called \"valid\"?" },
476 { "AllowNonRFC953Hostnames", "If set to 1, we don't automatically reject "
477 "hostnames for having invalid characters." },
478 /* CircuitBuildTimeout, CircuitIdleTimeout */
479 { "ClientOnly", "If set to 1, Tor will under no circumstances run as a "
480 "server, even if ORPort is enabled." },
481 { "EntryNodes", "A list of preferred entry nodes to use for the first hop "
482 "in circuits, when possible." },
483 /* { "EnforceDistinctSubnets" , "" }, */
484 { "ExitNodes", "A list of preferred nodes to use for the last hop in "
485 "circuits, when possible." },
486 { "ExcludeNodes", "A list of nodes never to use when building a circuit." },
487 { "FascistFirewall", "If set, Tor will only create outgoing connections to "
488 "servers running on the ports listed in FirewallPorts." },
489 { "FirewallPorts", "A list of ports that we can connect to. Only used "
490 "when FascistFirewall is set." },
491 { "LongLivedPorts", "A list of ports for services that tend to require "
492 "high-uptime connections." },
493 { "MapAddress", "Force Tor to treat all requests for one address as if "
494 "they were for another." },
495 { "NewCircuitPeriod", "Force Tor to consider whether to build a new circuit "
496 "every NUM seconds." },
497 { "MaxCircuitDirtiness", "Do not attach new streams to a circuit that has "
498 "been used more than this many seconds ago." },
499 /* NatdPort, NatdListenAddress */
500 { "NodeFamily", "A list of servers that constitute a 'family' and should "
501 "never be used in the same circuit." },
502 { "NumEntryGuards", "How many entry guards should we keep at a time?" },
503 /* PathlenCoinWeight */
504 { "ReachableAddresses", "Addresses we can connect to, as IP/bits:port-port. "
505 "By default, we assume all addresses are reachable." },
506 /* reachablediraddresses, reachableoraddresses. */
508 { "SOCKSPort", "The port where we listen for SOCKS connections from "
510 { "SOCKSListenAddress", "Bind to this address to listen to connections from "
511 "SOCKS-speaking applications." },
512 { "SOCKSPolicy", "Set an entry policy to limit which addresses can connect "
513 "to the SOCKSPort." },
515 { "StrictExitNodes", "If set, Tor will fail to operate when none of the "
516 "configured ExitNodes can be used." },
517 { "StrictEntryNodes", "If set, Tor will fail to operate when none of the "
518 "configured EntryNodes can be used." },
520 { "TrackHostsExit", "Hosts and domains which should, if possible, be "
521 "accessed from the same exit node each time we connect to them." },
522 { "TrackHostsExitExpire", "Time after which we forget which exit we were "
523 "using to connect to hosts in TrackHostsExit." },
524 /* "TransPort", "TransListenAddress */
525 { "UseEntryGuards", "Set to 0 if we want to pick from the whole set of "
526 "servers for the first position in each circuit, rather than picking a "
527 "set of 'Guards' to prevent profiling attacks." },
529 /* === server options */
530 { "Address", "The advertised (external) address we should use." },
531 /* Accounting* options. */
532 /* AssumeReachable */
533 { "ContactInfo", "Administrative contact information to advertise for this "
535 { "ExitPolicy", "Address/port ranges for which to accept or reject outgoing "
536 "connections on behalf of Tor users." },
537 /* { "ExitPolicyRejectPrivate, "" }, */
538 { "MaxAdvertisedBandwidth", "If set, we will not advertise more than this "
539 "amount of bandwidth for our bandwidth rate, regardless of how much "
540 "bandwidth we actually detect." },
541 { "MaxOnionsPending", "Reject new attempts to extend circuits when we "
542 "already have this many pending." },
543 { "MyFamily", "Declare a list of other servers as belonging to the same "
544 "family as this one, so that clients will not use two from the same "
545 "family in the same circuit." },
546 { "Nickname", "Set the server nickname." },
547 { "NoPublish", "{DEPRECATED}" },
548 { "NumCPUs", "How many processes to use at once for public-key crypto." },
549 { "ORPort", "Advertise this port to listen for connections from Tor clients "
551 { "ORListenAddress", "Bind to this address to listen for connections from "
552 "clients and servers, instead of the default 0.0.0.0:ORPort." },
553 { "PublishServerDescriptor", "Set to 0 to keep the server from "
554 "uploading info to the directory authorities." },
555 /* ServerDNS: DetectHijacking, ResolvConfFile, SearchDomains */
556 { "ShutdownWaitLength", "Wait this long for clients to finish when "
557 "shutting down because of a SIGINT." },
559 /* === directory cache options */
560 { "DirPort", "Serve directory information from this port, and act as a "
561 "directory cache." },
562 { "DirPortFrontPage", "Serve a static html disclaimer on DirPort." },
563 { "DirListenAddress", "Bind to this address to listen for connections from "
564 "clients and servers, instead of the default 0.0.0.0:DirPort." },
565 { "DirPolicy", "Set a policy to limit who can connect to the directory "
568 /* Authority options: AuthDirBadExit, AuthDirInvalid, AuthDirReject,
569 * AuthDirRejectUnlisted, AuthDirListBadExits, AuthoritativeDirectory,
570 * DirAllowPrivateAddresses, HSAuthoritativeDir,
571 * NamingAuthoritativeDirectory, RecommendedVersions,
572 * RecommendedClientVersions, RecommendedServerVersions, RendPostPeriod,
573 * RunTesting, V1AuthoritativeDirectory, VersioningAuthoritativeDirectory, */
575 /* Hidden service options: HiddenService: dir,excludenodes, nodes,
576 * options, port. PublishHidServDescriptor */
578 /* Nonpersistent options: __LeaveStreamsUnattached, __AllDirActionsPrivate */
582 static config_var_description_t state_description
[] = {
583 { "AccountingBytesReadInInterval",
584 "How many bytes have we read in this accounting period?" },
585 { "AccountingBytesWrittenInInterval",
586 "How many bytes have we written in this accounting period?" },
587 { "AccountingExpectedUsage",
588 "How many bytes did we expect to use per minute? (0 for no estimate.)" },
589 { "AccountingIntervalStart", "When did this accounting period begin?" },
590 { "AccountingSecondsActive", "How long have we been awake in this period?" },
592 { "BWHistoryReadEnds", "When does the last-recorded read-interval end?" },
593 { "BWHistoryReadInterval", "How long is each read-interval (in seconds)?" },
594 { "BWHistoryReadValues", "Number of bytes read in each interval." },
595 { "BWHistoryWriteEnds", "When does the last-recorded write-interval end?" },
596 { "BWHistoryWriteInterval", "How long is each write-interval (in seconds)?"},
597 { "BWHistoryWriteValues", "Number of bytes written in each interval." },
599 { "EntryGuard", "One of the nodes we have chosen as a fixed entry" },
600 { "EntryGuardDownSince",
601 "The last entry guard has been unreachable since this time." },
602 { "EntryGuardUnlistedSince",
603 "The last entry guard has been unusable since this time." },
605 { "LastRotatedOnionKey",
606 "The last time at which we changed the medium-term private key used for "
607 "building circuits." },
608 { "LastWritten", "When was this state file last regenerated?" },
610 { "TorVersion", "Which version of Tor generated this state file?" },
614 /** Type of a callback to validate whether a given configuration is
615 * well-formed and consistent. See options_trial_assign() for documentation
617 typedef int (*validate_fn_t
)(void*,void*,int,char**);
619 /** Information on the keys, value types, key-to-struct-member mappings,
620 * variable descriptions, validation functions, and abbreviations for a
621 * configuration or storage format. */
623 size_t size
; /**< Size of the struct that everything gets parsed into. */
624 uint32_t magic
; /**< Required 'magic value' to make sure we have a struct
625 * of the right type. */
626 off_t magic_offset
; /**< Offset of the magic value within the struct. */
627 config_abbrev_t
*abbrevs
; /**< List of abbreviations that we expand when
628 * parsing this format. */
629 config_var_t
*vars
; /**< List of variables we recognize, their default
630 * values, and where we stick them in the structure. */
631 validate_fn_t validate_fn
; /**< Function to validate config. */
632 /** Documentation for configuration variables. */
633 config_var_description_t
*descriptions
;
634 /** If present, extra is a LINELIST variable for unrecognized
635 * lines. Otherwise, unrecognized lines are an error. */
639 /** Macro: assert that <b>cfg</b> has the right magic field for format
641 #define CHECK(fmt, cfg) STMT_BEGIN \
642 tor_assert(fmt && cfg); \
643 tor_assert((fmt)->magic == \
644 *(uint32_t*)STRUCT_VAR_P(cfg,fmt->magic_offset)); \
648 static char *get_windows_conf_root(void);
650 static void config_line_append(config_line_t
**lst
,
651 const char *key
, const char *val
);
652 static void option_clear(config_format_t
*fmt
, or_options_t
*options
,
654 static void option_reset(config_format_t
*fmt
, or_options_t
*options
,
655 config_var_t
*var
, int use_defaults
);
656 static void config_free(config_format_t
*fmt
, void *options
);
657 static int config_lines_eq(config_line_t
*a
, config_line_t
*b
);
658 static int option_is_same(config_format_t
*fmt
,
659 or_options_t
*o1
, or_options_t
*o2
,
661 static or_options_t
*options_dup(config_format_t
*fmt
, or_options_t
*old
);
662 static int options_validate(or_options_t
*old_options
, or_options_t
*options
,
663 int from_setconf
, char **msg
);
664 static int options_act_reversible(or_options_t
*old_options
, char **msg
);
665 static int options_act(or_options_t
*old_options
);
666 static int options_transition_allowed(or_options_t
*old
, or_options_t
*new,
668 static int options_transition_affects_workers(or_options_t
*old_options
,
669 or_options_t
*new_options
);
670 static int options_transition_affects_descriptor(or_options_t
*old_options
,
671 or_options_t
*new_options
);
672 static int check_nickname_list(const char *lst
, const char *name
, char **msg
);
673 static void config_register_addressmaps(or_options_t
*options
);
675 static int parse_bridge_line(const char *line
, int validate_only
);
676 static int parse_dir_server_line(const char *line
,
677 authority_type_t required_type
,
679 static int validate_data_directory(or_options_t
*options
);
680 static int write_configuration_file(const char *fname
, or_options_t
*options
);
681 static config_line_t
*get_assigned_option(config_format_t
*fmt
,
682 or_options_t
*options
, const char *key
,
684 static void config_init(config_format_t
*fmt
, void *options
);
685 static int or_state_validate(or_state_t
*old_options
, or_state_t
*options
,
686 int from_setconf
, char **msg
);
687 static int or_state_load(void);
688 static int options_init_logs(or_options_t
*options
, int validate_only
);
690 static uint64_t config_parse_memunit(const char *s
, int *ok
);
691 static int config_parse_interval(const char *s
, int *ok
);
692 static void print_svn_version(void);
693 static void init_libevent(void);
694 static int opt_streq(const char *s1
, const char *s2
);
695 /** Versions of libevent. */
697 /* Note: we compare these, so it's important that "old" precede everything,
698 * and that "other" come last. */
699 LE_OLD
=0, LE_10C
, LE_10D
, LE_10E
, LE_11
, LE_11A
, LE_11B
, LE_12
, LE_12A
,
700 LE_13
, LE_13A
, LE_13B
, LE_13C
, LE_13D
,
703 static le_version_t
decode_libevent_version(void);
704 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
705 static void check_libevent_version(const char *m
, int server
);
708 /** Magic value for or_options_t. */
709 #define OR_OPTIONS_MAGIC 9090909
711 /** Configuration format for or_options_t. */
712 static config_format_t options_format
= {
713 sizeof(or_options_t
),
715 STRUCT_OFFSET(or_options_t
, _magic
),
718 (validate_fn_t
)options_validate
,
723 /** Magic value for or_state_t. */
724 #define OR_STATE_MAGIC 0x57A73f57
726 /** "Extra" variable in the state that receives lines we can't parse. This
727 * lets us preserve options from versions of Tor newer than us. */
728 static config_var_t state_extra_var
= {
729 "__extra", CONFIG_TYPE_LINELIST
, STRUCT_OFFSET(or_state_t
, ExtraLines
), NULL
732 /** Configuration format for or_state_t. */
733 static config_format_t state_format
= {
736 STRUCT_OFFSET(or_state_t
, _magic
),
739 (validate_fn_t
)or_state_validate
,
745 * Functions to read and write the global options pointer.
748 /** Command-line and config-file options. */
749 static or_options_t
*global_options
= NULL
;
750 /** Name of most recently read torrc file. */
751 static char *torrc_fname
= NULL
;
752 /** Persistent serialized state. */
753 static or_state_t
*global_state
= NULL
;
754 /** Configuration Options set by command line. */
755 static config_line_t
*global_cmdline_options
= NULL
;
756 /** Contents of most recently read DirPortFrontPage file. */
757 static char *global_dirfrontpagecontents
= NULL
;
759 /** Return the contents of our frontpage string, or NULL if not configured. */
761 get_dirportfrontpage(void)
763 return global_dirfrontpagecontents
;
766 /** Allocate an empty configuration object of a given format type. */
768 config_alloc(config_format_t
*fmt
)
770 void *opts
= tor_malloc_zero(fmt
->size
);
771 *(uint32_t*)STRUCT_VAR_P(opts
, fmt
->magic_offset
) = fmt
->magic
;
776 /** Return the currently configured options. */
780 tor_assert(global_options
);
781 return global_options
;
784 /** Change the current global options to contain <b>new_val</b> instead of
785 * their current value; take action based on the new value; free the old value
786 * as necessary. Returns 0 on success, -1 on failure.
789 set_options(or_options_t
*new_val
, char **msg
)
791 or_options_t
*old_options
= global_options
;
792 global_options
= new_val
;
793 /* Note that we pass the *old* options below, for comparison. It
794 * pulls the new options directly out of global_options. */
795 if (options_act_reversible(old_options
, msg
)<0) {
797 global_options
= old_options
;
800 if (options_act(old_options
) < 0) { /* acting on the options failed. die. */
802 "Acting on config options left us in a broken state. Dying.");
806 config_free(&options_format
, old_options
);
811 extern const char tor_svn_revision
[]; /* from tor_main.c */
813 static char *_version
= NULL
;
815 /** Return the current Tor version, possibly */
819 if (_version
== NULL
) {
820 if (strlen(tor_svn_revision
)) {
821 size_t len
= strlen(VERSION
)+strlen(tor_svn_revision
)+8;
822 _version
= tor_malloc(len
);
823 tor_snprintf(_version
, len
, "%s (r%s)", VERSION
, tor_svn_revision
);
825 _version
= tor_strdup(VERSION
);
831 /** Release additional memory allocated in options
834 or_options_free(or_options_t
*options
)
836 if (options
->_ExcludeExitNodesUnion
)
837 routerset_free(options
->_ExcludeExitNodesUnion
);
838 config_free(&options_format
, options
);
841 /** Release all memory and resources held by global configuration structures.
844 config_free_all(void)
846 if (global_options
) {
847 or_options_free(global_options
);
848 global_options
= NULL
;
851 config_free(&state_format
, global_state
);
854 if (global_cmdline_options
) {
855 config_free_lines(global_cmdline_options
);
856 global_cmdline_options
= NULL
;
858 tor_free(torrc_fname
);
860 tor_free(global_dirfrontpagecontents
);
863 /** If options->SafeLogging is on, return a not very useful string,
864 * else return address.
867 safe_str(const char *address
)
870 if (get_options()->SafeLogging
)
876 /** Equivalent to escaped(safe_str(address)). See reentrancy note on
877 * escaped(): don't use this outside the main thread, or twice in the same
880 escaped_safe_str(const char *address
)
882 if (get_options()->SafeLogging
)
885 return escaped(address
);
888 /** Add the default directory authorities directly into the trusted dir list,
889 * but only add them insofar as they share bits with <b>type</b>. */
891 add_default_trusted_dir_authorities(authority_type_t type
)
894 const char *dirservers
[] = {
895 "moria1 v1 orport=9001 v3ident=E2A2AF570166665D738736D0DD58169CC61D8A8B "
896 "128.31.0.34:9031 FFCB 46DB 1339 DA84 674C 70D7 CB58 6434 C437 0441",
897 "moria2 v1 orport=9002 128.31.0.34:9032 "
898 "719B E45D E224 B607 C537 07D0 E214 3E2D 423E 74CF",
899 "tor26 v1 orport=443 v3ident=14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4 "
900 "86.59.21.38:80 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D",
901 "dizum orport=443 v3ident=E8A9C45EDE6D711294FADF8E7951F4DE6CA56B58 "
902 "194.109.206.212:80 7EA6 EAD6 FD83 083C 538F 4403 8BBF A077 587D D755",
903 "Tonga orport=443 bridge no-v2 82.94.251.206:80 "
904 "4A0C CD2D DC79 9508 3D73 F5D6 6710 0C8A 5831 F16D",
905 "ides orport=9090 no-v2 v3ident=27B6B5996C426270A5C95488AA5BCEB6BCC86956 "
906 "216.224.124.114:9030 F397 038A DC51 3361 35E7 B80B D99C A384 4360 292B",
907 "gabelmoo orport=443 no-v2 "
908 "v3ident=81349FC1F2DBA2C2C11B45CB9706637D480AB913 "
909 "141.13.4.202:80 6833 3D07 61BC F397 A587 A0C0 B963 E4A9 E99E C4D3",
910 "dannenberg orport=443 no-v2 "
911 "v3ident=585769C78764D58426B8B52B6651A5A71137189A "
912 "213.73.91.31:80 7BE6 83E6 5D48 1413 21C5 ED92 F075 C553 64AC 7123",
915 for (i
=0; dirservers
[i
]; i
++) {
916 if (parse_dir_server_line(dirservers
[i
], type
, 0)<0) {
917 log_err(LD_BUG
, "Couldn't parse internal dirserver line %s",
923 /** Look at all the config options for using alternate directory
924 * authorities, and make sure none of them are broken. Also, warn the
925 * user if we changed any dangerous ones.
928 validate_dir_authorities(or_options_t
*options
, or_options_t
*old_options
)
932 if (options
->DirServers
&&
933 (options
->AlternateDirAuthority
|| options
->AlternateBridgeAuthority
||
934 options
->AlternateHSAuthority
)) {
936 "You cannot set both DirServers and Alternate*Authority.");
940 /* do we want to complain to the user about being partitionable? */
941 if ((options
->DirServers
&&
943 !config_lines_eq(options
->DirServers
, old_options
->DirServers
))) ||
944 (options
->AlternateDirAuthority
&&
946 !config_lines_eq(options
->AlternateDirAuthority
,
947 old_options
->AlternateDirAuthority
)))) {
949 "You have used DirServer or AlternateDirAuthority to "
950 "specify alternate directory authorities in "
951 "your configuration. This is potentially dangerous: it can "
952 "make you look different from all other Tor users, and hurt "
953 "your anonymity. Even if you've specified the same "
954 "authorities as Tor uses by default, the defaults could "
955 "change in the future. Be sure you know what you're doing.");
958 /* Now go through the four ways you can configure an alternate
959 * set of directory authorities, and make sure none are broken. */
960 for (cl
= options
->DirServers
; cl
; cl
= cl
->next
)
961 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 1)<0)
963 for (cl
= options
->AlternateBridgeAuthority
; cl
; cl
= cl
->next
)
964 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 1)<0)
966 for (cl
= options
->AlternateDirAuthority
; cl
; cl
= cl
->next
)
967 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 1)<0)
969 for (cl
= options
->AlternateHSAuthority
; cl
; cl
= cl
->next
)
970 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 1)<0)
975 /** Look at all the config options and assign new dir authorities
979 consider_adding_dir_authorities(or_options_t
*options
,
980 or_options_t
*old_options
)
984 !smartlist_len(router_get_trusted_dir_servers()) || !old_options
||
985 !config_lines_eq(options
->DirServers
, old_options
->DirServers
) ||
986 !config_lines_eq(options
->AlternateBridgeAuthority
,
987 old_options
->AlternateBridgeAuthority
) ||
988 !config_lines_eq(options
->AlternateDirAuthority
,
989 old_options
->AlternateDirAuthority
) ||
990 !config_lines_eq(options
->AlternateHSAuthority
,
991 old_options
->AlternateHSAuthority
);
994 return 0; /* all done */
996 /* Start from a clean slate. */
997 clear_trusted_dir_servers();
999 if (!options
->DirServers
) {
1000 /* then we may want some of the defaults */
1001 authority_type_t type
= NO_AUTHORITY
;
1002 if (!options
->AlternateBridgeAuthority
)
1003 type
|= BRIDGE_AUTHORITY
;
1004 if (!options
->AlternateDirAuthority
)
1005 type
|= V1_AUTHORITY
| V2_AUTHORITY
| V3_AUTHORITY
;
1006 if (!options
->AlternateHSAuthority
)
1007 type
|= HIDSERV_AUTHORITY
;
1008 add_default_trusted_dir_authorities(type
);
1011 for (cl
= options
->DirServers
; cl
; cl
= cl
->next
)
1012 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 0)<0)
1014 for (cl
= options
->AlternateBridgeAuthority
; cl
; cl
= cl
->next
)
1015 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 0)<0)
1017 for (cl
= options
->AlternateDirAuthority
; cl
; cl
= cl
->next
)
1018 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 0)<0)
1020 for (cl
= options
->AlternateHSAuthority
; cl
; cl
= cl
->next
)
1021 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 0)<0)
1026 /** Fetch the active option list, and take actions based on it. All of the
1027 * things we do should survive being done repeatedly. If present,
1028 * <b>old_options</b> contains the previous value of the options.
1030 * Return 0 if all goes well, return -1 if things went badly.
1033 options_act_reversible(or_options_t
*old_options
, char **msg
)
1035 smartlist_t
*new_listeners
= smartlist_create();
1036 smartlist_t
*replaced_listeners
= smartlist_create();
1037 static int libevent_initialized
= 0;
1038 or_options_t
*options
= get_options();
1039 int running_tor
= options
->command
== CMD_RUN_TOR
;
1040 int set_conn_limit
= 0;
1042 int logs_marked
= 0;
1044 /* Daemonize _first_, since we only want to open most of this stuff in
1045 * the subprocess. Libevent bases can't be reliably inherited across
1047 if (running_tor
&& options
->RunAsDaemon
) {
1048 /* No need to roll back, since you can't change the value. */
1052 #ifndef HAVE_SYS_UN_H
1053 if (options
->ControlSocket
) {
1054 *msg
= tor_strdup("Unix domain sockets (ControlSocket) not supported"
1055 " on this OS/with this build.");
1061 /* We need to set the connection limit before we can open the listeners. */
1062 if (set_max_file_descriptors((unsigned)options
->ConnLimit
,
1063 &options
->_ConnLimit
) < 0) {
1064 *msg
= tor_strdup("Problem with ConnLimit value. See logs for details.");
1069 /* Set up libevent. (We need to do this before we can register the
1070 * listeners as listeners.) */
1071 if (running_tor
&& !libevent_initialized
) {
1073 libevent_initialized
= 1;
1076 /* Launch the listeners. (We do this before we setuid, so we can bind to
1077 * ports under 1024.) */
1078 if (retry_all_listeners(replaced_listeners
, new_listeners
) < 0) {
1079 *msg
= tor_strdup("Failed to bind one of the listener ports.");
1084 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
1085 /* Open /dev/pf before dropping privileges. */
1086 if (options
->TransPort
) {
1087 if (get_pf_socket() < 0) {
1088 *msg
= tor_strdup("Unable to open /dev/pf for transparent proxy.");
1094 /* Setuid/setgid as appropriate */
1095 if (options
->User
) {
1096 if (switch_id(options
->User
) != 0) {
1097 /* No need to roll back, since you can't change the value. */
1098 *msg
= tor_strdup("Problem with User value. See logs for details.");
1103 /* Ensure data directory is private; create if possible. */
1104 if (check_private_dir(options
->DataDirectory
,
1105 running_tor
? CPD_CREATE
: CPD_CHECK
)<0) {
1107 int tmp
= tor_snprintf(buf
, sizeof(buf
),
1108 "Couldn't access/create private data directory \"%s\"",
1109 options
->DataDirectory
);
1110 *msg
= tor_strdup(tmp
>= 0 ? buf
: "internal error");
1112 /* No need to roll back, since you can't change the value. */
1115 if (directory_caches_v2_dir_info(options
)) {
1116 size_t len
= strlen(options
->DataDirectory
)+32;
1117 char *fn
= tor_malloc(len
);
1118 tor_snprintf(fn
, len
, "%s"PATH_SEPARATOR
"cached-status",
1119 options
->DataDirectory
);
1120 if (check_private_dir(fn
, running_tor
? CPD_CREATE
: CPD_CHECK
) < 0) {
1122 int tmp
= tor_snprintf(buf
, sizeof(buf
),
1123 "Couldn't access/create private data directory \"%s\"", fn
);
1124 *msg
= tor_strdup(tmp
>= 0 ? buf
: "internal error");
1131 /* Bail out at this point if we're not going to be a client or server:
1132 * we don't run Tor itself. */
1136 mark_logs_temp(); /* Close current logs once new logs are open. */
1138 if (options_init_logs(options
, 0)<0) { /* Configure the log(s) */
1139 *msg
= tor_strdup("Failed to init Log options. See logs for details.");
1146 log_severity_list_t
*severity
=
1147 tor_malloc_zero(sizeof(log_severity_list_t
));
1149 add_callback_log(severity
, control_event_logmsg
);
1150 control_adjust_event_log_severity();
1153 SMARTLIST_FOREACH(replaced_listeners
, connection_t
*, conn
,
1155 log_notice(LD_NET
, "Closing old %s on %s:%d",
1156 conn_type_to_string(conn
->type
), conn
->address
, conn
->port
);
1157 connection_close_immediate(conn
);
1158 connection_mark_for_close(conn
);
1167 rollback_log_changes();
1168 control_adjust_event_log_severity();
1171 if (set_conn_limit
&& old_options
)
1172 set_max_file_descriptors((unsigned)old_options
->ConnLimit
,
1173 &options
->_ConnLimit
);
1175 SMARTLIST_FOREACH(new_listeners
, connection_t
*, conn
,
1177 log_notice(LD_NET
, "Closing partially-constructed listener %s on %s:%d",
1178 conn_type_to_string(conn
->type
), conn
->address
, conn
->port
);
1179 connection_close_immediate(conn
);
1180 connection_mark_for_close(conn
);
1184 smartlist_free(new_listeners
);
1185 smartlist_free(replaced_listeners
);
1189 /** If we need to have a GEOIP ip-to-country map to run with our configured
1190 * options, return 1 and set *<b>reason_out</b> to a description of why. */
1192 options_need_geoip_info(or_options_t
*options
, const char **reason_out
)
1195 options
->BridgeRelay
&& options
->BridgeRecordUsageByCountry
;
1196 int routerset_usage
=
1197 routerset_needs_geoip(options
->EntryNodes
) ||
1198 routerset_needs_geoip(options
->ExitNodes
) ||
1199 routerset_needs_geoip(options
->ExcludeExitNodes
) ||
1200 routerset_needs_geoip(options
->ExcludeNodes
);
1202 if (routerset_usage
&& reason_out
) {
1203 *reason_out
= "We've been configured to use (or avoid) nodes in certain "
1204 "contries, and we need GEOIP information to figure out which ones they "
1206 } else if (bridge_usage
&& reason_out
) {
1207 *reason_out
= "We've been configured to see which countries can access "
1208 "us as a bridge, and we need GEOIP information to tell which countries "
1211 return bridge_usage
|| routerset_usage
;
1214 /** Fetch the active option list, and take actions based on it. All of the
1215 * things we do should survive being done repeatedly. If present,
1216 * <b>old_options</b> contains the previous value of the options.
1218 * Return 0 if all goes well, return -1 if it's time to die.
1220 * Note: We haven't moved all the "act on new configuration" logic
1221 * here yet. Some is still in do_hup() and other places.
1224 options_act(or_options_t
*old_options
)
1227 or_options_t
*options
= get_options();
1228 int running_tor
= options
->command
== CMD_RUN_TOR
;
1231 if (running_tor
&& !have_lockfile()) {
1232 if (try_locking(options
, 1) < 0)
1236 if (consider_adding_dir_authorities(options
, old_options
) < 0)
1239 if (options
->Bridges
) {
1240 clear_bridge_list();
1241 for (cl
= options
->Bridges
; cl
; cl
= cl
->next
) {
1242 if (parse_bridge_line(cl
->value
, 0)<0) {
1244 "Previously validated Bridge line could not be added!");
1250 if (running_tor
&& rend_config_services(options
, 0)<0) {
1252 "Previously validated hidden services line could not be added!");
1256 if (running_tor
&& rend_parse_service_authorization(options
, 0) < 0) {
1257 log_warn(LD_BUG
, "Previously validated client authorization for "
1258 "hidden services could not be added!");
1263 if (! global_state
&& running_tor
) {
1264 if (or_state_load())
1266 rep_hist_load_mtbf_data(time(NULL
));
1269 /* Bail out at this point if we're not going to be a client or server:
1270 * we want to not fork, and to log stuff to stderr. */
1274 /* Finish backgrounding the process */
1275 if (running_tor
&& options
->RunAsDaemon
) {
1276 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
1277 finish_daemon(options
->DataDirectory
);
1280 /* Write our pid to the pid file. If we do not have write permissions we
1281 * will log a warning */
1282 if (running_tor
&& options
->PidFile
)
1283 write_pidfile(options
->PidFile
);
1285 /* Register addressmap directives */
1286 config_register_addressmaps(options
);
1287 parse_virtual_addr_network(options
->VirtualAddrNetwork
, 0, &msg
);
1289 /* Update address policies. */
1290 if (policies_parse_from_options(options
) < 0) {
1291 /* This should be impossible, but let's be sure. */
1292 log_warn(LD_BUG
,"Error parsing already-validated policy options.");
1296 if (init_cookie_authentication(options
->CookieAuthentication
) < 0) {
1297 log_warn(LD_CONFIG
,"Error creating cookie authentication file.");
1301 /* reload keys as needed for rendezvous services. */
1302 if (rend_service_load_keys()<0) {
1303 log_warn(LD_GENERAL
,"Error loading rendezvous service keys");
1307 /* Set up accounting */
1308 if (accounting_parse_options(options
, 0)<0) {
1309 log_warn(LD_CONFIG
,"Error in accounting options");
1312 if (accounting_is_enabled(options
))
1313 configure_accounting(time(NULL
));
1315 /* Check for transitions that need action. */
1317 if (options
->UseEntryGuards
&& !old_options
->UseEntryGuards
) {
1319 "Switching to entry guards; abandoning previous circuits");
1320 circuit_mark_all_unused_circs();
1321 circuit_expire_all_dirty_circs();
1324 if (options_transition_affects_workers(old_options
, options
)) {
1325 log_info(LD_GENERAL
,
1326 "Worker-related options changed. Rotating workers.");
1327 if (server_mode(options
) && !server_mode(old_options
)) {
1328 if (init_keys() < 0) {
1329 log_warn(LD_BUG
,"Error initializing keys; exiting");
1332 ip_address_changed(0);
1333 if (has_completed_circuit
|| !any_predicted_circuits(time(NULL
)))
1334 inform_testing_reachability();
1336 cpuworkers_rotate();
1344 if (options
->V3AuthoritativeDir
&& !old_options
->V3AuthoritativeDir
)
1348 /* Maybe load geoip file */
1349 if (options
->GeoIPFile
&&
1350 ((!old_options
|| !opt_streq(old_options
->GeoIPFile
, options
->GeoIPFile
))
1351 || !geoip_is_loaded())) {
1352 /* XXXX Don't use this "<default>" junk; make our filename options
1353 * understand prefixes somehow. -NM */
1354 /* XXXX021 Reload GeoIPFile on SIGHUP. -NM */
1355 char *actual_fname
= tor_strdup(options
->GeoIPFile
);
1357 if (!strcmp(actual_fname
, "<default>")) {
1358 const char *conf_root
= get_windows_conf_root();
1359 size_t len
= strlen(conf_root
)+16;
1360 tor_free(actual_fname
);
1361 actual_fname
= tor_malloc(len
+1);
1362 tor_snprintf(actual_fname
, len
, "%s\\geoip", conf_root
);
1365 geoip_load_file(actual_fname
, options
);
1366 tor_free(actual_fname
);
1368 /* XXXX Would iterating through all option_var's routersets be better? */
1369 if (options
->EntryNodes
)
1370 routerset_refresh_countries(options
->EntryNodes
);
1371 if (options
->ExitNodes
)
1372 routerset_refresh_countries(options
->ExitNodes
);
1373 if (options
->ExcludeNodes
)
1374 routerset_refresh_countries(options
->ExcludeNodes
);
1375 if (options
->ExcludeExitNodes
)
1376 routerset_refresh_countries(options
->ExcludeExitNodes
);
1377 routerlist_refresh_countries();
1379 /* Check if we need to parse and add the EntryNodes config option. */
1380 if (options
->EntryNodes
&&
1382 (!routerset_equal(old_options
->EntryNodes
,options
->EntryNodes
))))
1383 entry_nodes_should_be_added();
1385 /* Since our options changed, we might need to regenerate and upload our
1386 * server descriptor.
1389 options_transition_affects_descriptor(old_options
, options
))
1390 mark_my_descriptor_dirty();
1392 /* We may need to reschedule some directory stuff if our status changed. */
1394 if (authdir_mode_v3(options
) && !authdir_mode_v3(old_options
))
1395 dirvote_recalculate_timing(options
, time(NULL
));
1396 if (!bool_eq(directory_fetches_dir_info_early(options
),
1397 directory_fetches_dir_info_early(old_options
)) ||
1398 !bool_eq(directory_fetches_dir_info_later(options
),
1399 directory_fetches_dir_info_later(old_options
))) {
1400 /* Make sure update_router_have_min_dir_info gets called. */
1401 router_dir_info_changed();
1402 /* We might need to download a new consensus status later or sooner than
1403 * we had expected. */
1404 update_consensus_networkstatus_fetch_time(time(NULL
));
1408 /* Load the webpage we're going to serve everytime someone asks for '/' on
1410 tor_free(global_dirfrontpagecontents
);
1411 if (options
->DirPortFrontPage
) {
1412 global_dirfrontpagecontents
=
1413 read_file_to_str(options
->DirPortFrontPage
, 0, NULL
);
1414 if (!global_dirfrontpagecontents
) {
1416 "DirPortFrontPage file '%s' not found. Continuing anyway.",
1417 options
->DirPortFrontPage
);
1425 * Functions to parse config options
1428 /** If <b>option</b> is an official abbreviation for a longer option,
1429 * return the longer option. Otherwise return <b>option</b>.
1430 * If <b>command_line</b> is set, apply all abbreviations. Otherwise, only
1431 * apply abbreviations that work for the config file and the command line.
1432 * If <b>warn_obsolete</b> is set, warn about deprecated names. */
1434 expand_abbrev(config_format_t
*fmt
, const char *option
, int command_line
,
1440 for (i
=0; fmt
->abbrevs
[i
].abbreviated
; ++i
) {
1441 /* Abbreviations are casei. */
1442 if (!strcasecmp(option
,fmt
->abbrevs
[i
].abbreviated
) &&
1443 (command_line
|| !fmt
->abbrevs
[i
].commandline_only
)) {
1444 if (warn_obsolete
&& fmt
->abbrevs
[i
].warn
) {
1446 "The configuration option '%s' is deprecated; "
1447 "use '%s' instead.",
1448 fmt
->abbrevs
[i
].abbreviated
,
1449 fmt
->abbrevs
[i
].full
);
1451 return fmt
->abbrevs
[i
].full
;
1457 /** Helper: Read a list of configuration options from the command line.
1458 * If successful, put them in *<b>result</b> and return 0, and return
1459 * -1 and leave *<b>result</b> alone. */
1461 config_get_commandlines(int argc
, char **argv
, config_line_t
**result
)
1463 config_line_t
*front
= NULL
;
1464 config_line_t
**new = &front
;
1469 if (!strcmp(argv
[i
],"-f") ||
1470 !strcmp(argv
[i
],"--hash-password")) {
1471 i
+= 2; /* command-line option with argument. ignore them. */
1473 } else if (!strcmp(argv
[i
],"--list-fingerprint") ||
1474 !strcmp(argv
[i
],"--verify-config") ||
1475 !strcmp(argv
[i
],"--ignore-missing-torrc") ||
1476 !strcmp(argv
[i
],"--quiet") ||
1477 !strcmp(argv
[i
],"--hush")) {
1478 i
+= 1; /* command-line option. ignore it. */
1480 } else if (!strcmp(argv
[i
],"--nt-service") ||
1481 !strcmp(argv
[i
],"-nt-service")) {
1487 log_warn(LD_CONFIG
,"Command-line option '%s' with no value. Failing.",
1489 config_free_lines(front
);
1493 *new = tor_malloc_zero(sizeof(config_line_t
));
1499 (*new)->key
= tor_strdup(expand_abbrev(&options_format
, s
, 1, 1));
1500 (*new)->value
= tor_strdup(argv
[i
+1]);
1501 (*new)->next
= NULL
;
1502 log(LOG_DEBUG
, LD_CONFIG
, "Commandline: parsed keyword '%s', value '%s'",
1503 (*new)->key
, (*new)->value
);
1505 new = &((*new)->next
);
1512 /** Helper: allocate a new configuration option mapping 'key' to 'val',
1513 * append it to *<b>lst</b>. */
1515 config_line_append(config_line_t
**lst
,
1519 config_line_t
*newline
;
1521 newline
= tor_malloc(sizeof(config_line_t
));
1522 newline
->key
= tor_strdup(key
);
1523 newline
->value
= tor_strdup(val
);
1524 newline
->next
= NULL
;
1526 lst
= &((*lst
)->next
);
1531 /** Helper: parse the config string and strdup into key/value
1532 * strings. Set *result to the list, or NULL if parsing the string
1533 * failed. Return 0 on success, -1 on failure. Warn and ignore any
1534 * misformatted lines. */
1536 config_get_lines(const char *string
, config_line_t
**result
)
1538 config_line_t
*list
= NULL
, **next
;
1544 string
= parse_config_line_from_str(string
, &k
, &v
);
1546 config_free_lines(list
);
1552 /* This list can get long, so we keep a pointer to the end of it
1553 * rather than using config_line_append over and over and getting
1554 * n^2 performance. */
1555 *next
= tor_malloc(sizeof(config_line_t
));
1558 (*next
)->next
= NULL
;
1559 next
= &((*next
)->next
);
1571 * Free all the configuration lines on the linked list <b>front</b>.
1574 config_free_lines(config_line_t
*front
)
1583 tor_free(tmp
->value
);
1588 /** Return the description for a given configuration variable, or NULL if no
1589 * description exists. */
1591 config_find_description(config_format_t
*fmt
, const char *name
)
1594 for (i
=0; fmt
->descriptions
[i
].name
; ++i
) {
1595 if (!strcasecmp(name
, fmt
->descriptions
[i
].name
))
1596 return fmt
->descriptions
[i
].description
;
1601 /** If <b>key</b> is a configuration option, return the corresponding
1602 * config_var_t. Otherwise, if <b>key</b> is a non-standard abbreviation,
1603 * warn, and return the corresponding config_var_t. Otherwise return NULL.
1605 static config_var_t
*
1606 config_find_option(config_format_t
*fmt
, const char *key
)
1609 size_t keylen
= strlen(key
);
1611 return NULL
; /* if they say "--" on the commandline, it's not an option */
1612 /* First, check for an exact (case-insensitive) match */
1613 for (i
=0; fmt
->vars
[i
].name
; ++i
) {
1614 if (!strcasecmp(key
, fmt
->vars
[i
].name
)) {
1615 return &fmt
->vars
[i
];
1618 /* If none, check for an abbreviated match */
1619 for (i
=0; fmt
->vars
[i
].name
; ++i
) {
1620 if (!strncasecmp(key
, fmt
->vars
[i
].name
, keylen
)) {
1621 log_warn(LD_CONFIG
, "The abbreviation '%s' is deprecated. "
1622 "Please use '%s' instead",
1623 key
, fmt
->vars
[i
].name
);
1624 return &fmt
->vars
[i
];
1627 /* Okay, unrecognized option */
1632 * Functions to assign config options.
1635 /** <b>c</b>-\>key is known to be a real key. Update <b>options</b>
1636 * with <b>c</b>-\>value and return 0, or return -1 if bad value.
1638 * Called from config_assign_line() and option_reset().
1641 config_assign_value(config_format_t
*fmt
, or_options_t
*options
,
1642 config_line_t
*c
, char **msg
)
1649 CHECK(fmt
, options
);
1651 var
= config_find_option(fmt
, c
->key
);
1654 lvalue
= STRUCT_VAR_P(options
, var
->var_offset
);
1656 switch (var
->type
) {
1658 case CONFIG_TYPE_UINT
:
1659 i
= (int)tor_parse_long(c
->value
, 10, 0, INT_MAX
, &ok
, NULL
);
1661 r
= tor_snprintf(buf
, sizeof(buf
),
1662 "Int keyword '%s %s' is malformed or out of bounds.",
1664 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
1670 case CONFIG_TYPE_INTERVAL
: {
1671 i
= config_parse_interval(c
->value
, &ok
);
1673 r
= tor_snprintf(buf
, sizeof(buf
),
1674 "Interval '%s %s' is malformed or out of bounds.",
1676 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
1683 case CONFIG_TYPE_MEMUNIT
: {
1684 uint64_t u64
= config_parse_memunit(c
->value
, &ok
);
1686 r
= tor_snprintf(buf
, sizeof(buf
),
1687 "Value '%s %s' is malformed or out of bounds.",
1689 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
1692 *(uint64_t *)lvalue
= u64
;
1696 case CONFIG_TYPE_BOOL
:
1697 i
= (int)tor_parse_long(c
->value
, 10, 0, 1, &ok
, NULL
);
1699 r
= tor_snprintf(buf
, sizeof(buf
),
1700 "Boolean '%s %s' expects 0 or 1.",
1702 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
1708 case CONFIG_TYPE_STRING
:
1709 case CONFIG_TYPE_FILENAME
:
1710 tor_free(*(char **)lvalue
);
1711 *(char **)lvalue
= tor_strdup(c
->value
);
1714 case CONFIG_TYPE_DOUBLE
:
1715 *(double *)lvalue
= atof(c
->value
);
1718 case CONFIG_TYPE_ISOTIME
:
1719 if (parse_iso_time(c
->value
, (time_t *)lvalue
)) {
1720 r
= tor_snprintf(buf
, sizeof(buf
),
1721 "Invalid time '%s' for keyword '%s'", c
->value
, c
->key
);
1722 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
1727 case CONFIG_TYPE_ROUTERSET
:
1728 if (*(routerset_t
**)lvalue
) {
1729 routerset_free(*(routerset_t
**)lvalue
);
1731 *(routerset_t
**)lvalue
= routerset_new();
1732 if (routerset_parse(*(routerset_t
**)lvalue
, c
->value
, c
->key
)<0) {
1733 tor_snprintf(buf
, sizeof(buf
), "Invalid exit list '%s' for option '%s'",
1735 *msg
= tor_strdup(buf
);
1740 case CONFIG_TYPE_CSV
:
1741 if (*(smartlist_t
**)lvalue
) {
1742 SMARTLIST_FOREACH(*(smartlist_t
**)lvalue
, char *, cp
, tor_free(cp
));
1743 smartlist_clear(*(smartlist_t
**)lvalue
);
1745 *(smartlist_t
**)lvalue
= smartlist_create();
1748 smartlist_split_string(*(smartlist_t
**)lvalue
, c
->value
, ",",
1749 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1752 case CONFIG_TYPE_LINELIST
:
1753 case CONFIG_TYPE_LINELIST_S
:
1754 config_line_append((config_line_t
**)lvalue
, c
->key
, c
->value
);
1756 case CONFIG_TYPE_OBSOLETE
:
1757 log_warn(LD_CONFIG
, "Skipping obsolete configuration option '%s'", c
->key
);
1759 case CONFIG_TYPE_LINELIST_V
:
1760 r
= tor_snprintf(buf
, sizeof(buf
),
1761 "You may not provide a value for virtual option '%s'", c
->key
);
1762 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
1771 /** If <b>c</b> is a syntactically valid configuration line, update
1772 * <b>options</b> with its value and return 0. Otherwise return -1 for bad
1773 * key, -2 for bad value.
1775 * If <b>clear_first</b> is set, clear the value first. Then if
1776 * <b>use_defaults</b> is set, set the value to the default.
1778 * Called from config_assign().
1781 config_assign_line(config_format_t
*fmt
, or_options_t
*options
,
1782 config_line_t
*c
, int use_defaults
,
1783 int clear_first
, char **msg
)
1787 CHECK(fmt
, options
);
1789 var
= config_find_option(fmt
, c
->key
);
1792 void *lvalue
= STRUCT_VAR_P(options
, fmt
->extra
->var_offset
);
1794 "Found unrecognized option '%s'; saving it.", c
->key
);
1795 config_line_append((config_line_t
**)lvalue
, c
->key
, c
->value
);
1799 int tmp
= tor_snprintf(buf
, sizeof(buf
),
1800 "Unknown option '%s'. Failing.", c
->key
);
1801 *msg
= tor_strdup(tmp
>= 0 ? buf
: "internal error");
1805 /* Put keyword into canonical case. */
1806 if (strcmp(var
->name
, c
->key
)) {
1808 c
->key
= tor_strdup(var
->name
);
1811 if (!strlen(c
->value
)) {
1812 /* reset or clear it, then return */
1814 if (var
->type
== CONFIG_TYPE_LINELIST
||
1815 var
->type
== CONFIG_TYPE_LINELIST_S
) {
1816 /* We got an empty linelist from the torrc or commandline.
1817 As a special case, call this an error. Warn and ignore. */
1819 "Linelist option '%s' has no value. Skipping.", c
->key
);
1820 } else { /* not already cleared */
1821 option_reset(fmt
, options
, var
, use_defaults
);
1827 if (config_assign_value(fmt
, options
, c
, msg
) < 0)
1832 /** Restore the option named <b>key</b> in options to its default value.
1833 * Called from config_assign(). */
1835 config_reset_line(config_format_t
*fmt
, or_options_t
*options
,
1836 const char *key
, int use_defaults
)
1840 CHECK(fmt
, options
);
1842 var
= config_find_option(fmt
, key
);
1844 return; /* give error on next pass. */
1846 option_reset(fmt
, options
, var
, use_defaults
);
1849 /** Return true iff key is a valid configuration option. */
1851 option_is_recognized(const char *key
)
1853 config_var_t
*var
= config_find_option(&options_format
, key
);
1854 return (var
!= NULL
);
1857 /** Return the canonical name of a configuration option, or NULL
1858 * if no such option exists. */
1860 option_get_canonical_name(const char *key
)
1862 config_var_t
*var
= config_find_option(&options_format
, key
);
1863 return var
? var
->name
: NULL
;
1866 /** Return a canonicalized list of the options assigned for key.
1869 option_get_assignment(or_options_t
*options
, const char *key
)
1871 return get_assigned_option(&options_format
, options
, key
, 1);
1874 /** Return true iff value needs to be quoted and escaped to be used in
1875 * a configuration file. */
1877 config_value_needs_escape(const char *value
)
1887 /* Note: quotes and backspaces need special handling when we are using
1888 * quotes, not otherwise, so they don't trigger escaping on their
1892 if (!TOR_ISPRINT(*value
))
1900 /** Return a newly allocated deep copy of the lines in <b>inp</b>. */
1901 static config_line_t
*
1902 config_lines_dup(const config_line_t
*inp
)
1904 config_line_t
*result
= NULL
;
1905 config_line_t
**next_out
= &result
;
1907 *next_out
= tor_malloc(sizeof(config_line_t
));
1908 (*next_out
)->key
= tor_strdup(inp
->key
);
1909 (*next_out
)->value
= tor_strdup(inp
->value
);
1911 next_out
= &((*next_out
)->next
);
1917 /** Return newly allocated line or lines corresponding to <b>key</b> in the
1918 * configuration <b>options</b>. If <b>escape_val</b> is true and a
1919 * value needs to be quoted before it's put in a config file, quote and
1920 * escape that value. Return NULL if no such key exists. */
1921 static config_line_t
*
1922 get_assigned_option(config_format_t
*fmt
, or_options_t
*options
,
1923 const char *key
, int escape_val
)
1924 /* XXXX argument is options, but fmt is provided. Inconsistent. */
1929 config_line_t
*result
;
1930 tor_assert(options
&& key
);
1932 CHECK(fmt
, options
);
1934 var
= config_find_option(fmt
, key
);
1936 log_warn(LD_CONFIG
, "Unknown option '%s'. Failing.", key
);
1939 value
= STRUCT_VAR_P(options
, var
->var_offset
);
1941 result
= tor_malloc_zero(sizeof(config_line_t
));
1942 result
->key
= tor_strdup(var
->name
);
1945 case CONFIG_TYPE_STRING
:
1946 case CONFIG_TYPE_FILENAME
:
1947 if (*(char**)value
) {
1948 result
->value
= tor_strdup(*(char**)value
);
1950 tor_free(result
->key
);
1955 case CONFIG_TYPE_ISOTIME
:
1956 if (*(time_t*)value
) {
1957 result
->value
= tor_malloc(ISO_TIME_LEN
+1);
1958 format_iso_time(result
->value
, *(time_t*)value
);
1960 tor_free(result
->key
);
1963 escape_val
= 0; /* Can't need escape. */
1965 case CONFIG_TYPE_INTERVAL
:
1966 case CONFIG_TYPE_UINT
:
1967 /* This means every or_options_t uint or bool element
1968 * needs to be an int. Not, say, a uint16_t or char. */
1969 tor_snprintf(buf
, sizeof(buf
), "%d", *(int*)value
);
1970 result
->value
= tor_strdup(buf
);
1971 escape_val
= 0; /* Can't need escape. */
1973 case CONFIG_TYPE_MEMUNIT
:
1974 tor_snprintf(buf
, sizeof(buf
), U64_FORMAT
,
1975 U64_PRINTF_ARG(*(uint64_t*)value
));
1976 result
->value
= tor_strdup(buf
);
1977 escape_val
= 0; /* Can't need escape. */
1979 case CONFIG_TYPE_DOUBLE
:
1980 tor_snprintf(buf
, sizeof(buf
), "%f", *(double*)value
);
1981 result
->value
= tor_strdup(buf
);
1982 escape_val
= 0; /* Can't need escape. */
1984 case CONFIG_TYPE_BOOL
:
1985 result
->value
= tor_strdup(*(int*)value
? "1" : "0");
1986 escape_val
= 0; /* Can't need escape. */
1988 case CONFIG_TYPE_ROUTERSET
:
1989 result
->value
= routerset_to_string(*(routerset_t
**)value
);
1991 case CONFIG_TYPE_CSV
:
1992 if (*(smartlist_t
**)value
)
1994 smartlist_join_strings(*(smartlist_t
**)value
, ",", 0, NULL
);
1996 result
->value
= tor_strdup("");
1998 case CONFIG_TYPE_OBSOLETE
:
1999 log_fn(LOG_PROTOCOL_WARN
, LD_CONFIG
,
2000 "You asked me for the value of an obsolete config option '%s'.",
2002 tor_free(result
->key
);
2005 case CONFIG_TYPE_LINELIST_S
:
2007 "Can't return context-sensitive '%s' on its own", key
);
2008 tor_free(result
->key
);
2011 case CONFIG_TYPE_LINELIST
:
2012 case CONFIG_TYPE_LINELIST_V
:
2013 tor_free(result
->key
);
2015 result
= config_lines_dup(*(const config_line_t
**)value
);
2018 tor_free(result
->key
);
2020 log_warn(LD_BUG
,"Unknown type %d for known key '%s'",
2026 config_line_t
*line
;
2027 for (line
= result
; line
; line
= line
->next
) {
2028 if (line
->value
&& config_value_needs_escape(line
->value
)) {
2029 char *newval
= esc_for_log(line
->value
);
2030 tor_free(line
->value
);
2031 line
->value
= newval
;
2039 /** Iterate through the linked list of requested options <b>list</b>.
2040 * For each item, convert as appropriate and assign to <b>options</b>.
2041 * If an item is unrecognized, set *msg and return -1 immediately,
2042 * else return 0 for success.
2044 * If <b>clear_first</b>, interpret config options as replacing (not
2045 * extending) their previous values. If <b>clear_first</b> is set,
2046 * then <b>use_defaults</b> to decide if you set to defaults after
2047 * clearing, or make the value 0 or NULL.
2049 * Here are the use cases:
2050 * 1. A non-empty AllowInvalid line in your torrc. Appends to current
2051 * if linelist, replaces current if csv.
2052 * 2. An empty AllowInvalid line in your torrc. Should clear it.
2053 * 3. "RESETCONF AllowInvalid" sets it to default.
2054 * 4. "SETCONF AllowInvalid" makes it NULL.
2055 * 5. "SETCONF AllowInvalid=foo" clears it and sets it to "foo".
2057 * Use_defaults Clear_first
2059 * 1 0 undefined, don't use
2060 * 0 1 "set to null first"
2061 * 1 1 "set to defaults first"
2062 * Return 0 on success, -1 on bad key, -2 on bad value.
2064 * As an additional special case, if a LINELIST config option has
2065 * no value and clear_first is 0, then warn and ignore it.
2069 There are three call cases for config_assign() currently.
2071 Case one: Torrc entry
2072 options_init_from_torrc() calls config_assign(0, 0)
2073 calls config_assign_line(0, 0).
2074 if value is empty, calls option_reset(0) and returns.
2075 calls config_assign_value(), appends.
2078 options_trial_assign() calls config_assign(0, 1)
2079 calls config_reset_line(0)
2080 calls option_reset(0)
2081 calls option_clear().
2082 calls config_assign_line(0, 1).
2083 if value is empty, returns.
2084 calls config_assign_value(), appends.
2086 Case three: resetconf
2087 options_trial_assign() calls config_assign(1, 1)
2088 calls config_reset_line(1)
2089 calls option_reset(1)
2090 calls option_clear().
2091 calls config_assign_value(default)
2092 calls config_assign_line(1, 1).
2096 config_assign(config_format_t
*fmt
, void *options
, config_line_t
*list
,
2097 int use_defaults
, int clear_first
, char **msg
)
2101 CHECK(fmt
, options
);
2103 /* pass 1: normalize keys */
2104 for (p
= list
; p
; p
= p
->next
) {
2105 const char *full
= expand_abbrev(fmt
, p
->key
, 0, 1);
2106 if (strcmp(full
,p
->key
)) {
2108 p
->key
= tor_strdup(full
);
2112 /* pass 2: if we're reading from a resetting source, clear all
2113 * mentioned config options, and maybe set to their defaults. */
2115 for (p
= list
; p
; p
= p
->next
)
2116 config_reset_line(fmt
, options
, p
->key
, use_defaults
);
2119 /* pass 3: assign. */
2122 if ((r
=config_assign_line(fmt
, options
, list
, use_defaults
,
2130 /** Try assigning <b>list</b> to the global options. You do this by duping
2131 * options, assigning list to the new one, then validating it. If it's
2132 * ok, then throw out the old one and stick with the new one. Else,
2133 * revert to old and return failure. Return SETOPT_OK on success, or
2134 * a setopt_err_t on failure.
2136 * If not success, point *<b>msg</b> to a newly allocated string describing
2140 options_trial_assign(config_line_t
*list
, int use_defaults
,
2141 int clear_first
, char **msg
)
2144 or_options_t
*trial_options
= options_dup(&options_format
, get_options());
2146 if ((r
=config_assign(&options_format
, trial_options
,
2147 list
, use_defaults
, clear_first
, msg
)) < 0) {
2148 config_free(&options_format
, trial_options
);
2152 if (options_validate(get_options(), trial_options
, 1, msg
) < 0) {
2153 config_free(&options_format
, trial_options
);
2154 return SETOPT_ERR_PARSE
; /*XXX make this a separate return value. */
2157 if (options_transition_allowed(get_options(), trial_options
, msg
) < 0) {
2158 config_free(&options_format
, trial_options
);
2159 return SETOPT_ERR_TRANSITION
;
2162 if (set_options(trial_options
, msg
)<0) {
2163 config_free(&options_format
, trial_options
);
2164 return SETOPT_ERR_SETTING
;
2167 /* we liked it. put it in place. */
2171 /** Reset config option <b>var</b> to 0, 0.0, NULL, or the equivalent.
2172 * Called from option_reset() and config_free(). */
2174 option_clear(config_format_t
*fmt
, or_options_t
*options
, config_var_t
*var
)
2176 void *lvalue
= STRUCT_VAR_P(options
, var
->var_offset
);
2177 (void)fmt
; /* unused */
2178 switch (var
->type
) {
2179 case CONFIG_TYPE_STRING
:
2180 case CONFIG_TYPE_FILENAME
:
2181 tor_free(*(char**)lvalue
);
2183 case CONFIG_TYPE_DOUBLE
:
2184 *(double*)lvalue
= 0.0;
2186 case CONFIG_TYPE_ISOTIME
:
2187 *(time_t*)lvalue
= 0;
2188 case CONFIG_TYPE_INTERVAL
:
2189 case CONFIG_TYPE_UINT
:
2190 case CONFIG_TYPE_BOOL
:
2193 case CONFIG_TYPE_MEMUNIT
:
2194 *(uint64_t*)lvalue
= 0;
2196 case CONFIG_TYPE_ROUTERSET
:
2197 if (*(routerset_t
**)lvalue
) {
2198 routerset_free(*(routerset_t
**)lvalue
);
2199 *(routerset_t
**)lvalue
= NULL
;
2201 case CONFIG_TYPE_CSV
:
2202 if (*(smartlist_t
**)lvalue
) {
2203 SMARTLIST_FOREACH(*(smartlist_t
**)lvalue
, char *, cp
, tor_free(cp
));
2204 smartlist_free(*(smartlist_t
**)lvalue
);
2205 *(smartlist_t
**)lvalue
= NULL
;
2208 case CONFIG_TYPE_LINELIST
:
2209 case CONFIG_TYPE_LINELIST_S
:
2210 config_free_lines(*(config_line_t
**)lvalue
);
2211 *(config_line_t
**)lvalue
= NULL
;
2213 case CONFIG_TYPE_LINELIST_V
:
2214 /* handled by linelist_s. */
2216 case CONFIG_TYPE_OBSOLETE
:
2221 /** Clear the option indexed by <b>var</b> in <b>options</b>. Then if
2222 * <b>use_defaults</b>, set it to its default value.
2223 * Called by config_init() and option_reset_line() and option_assign_line(). */
2225 option_reset(config_format_t
*fmt
, or_options_t
*options
,
2226 config_var_t
*var
, int use_defaults
)
2230 CHECK(fmt
, options
);
2231 option_clear(fmt
, options
, var
); /* clear it first */
2233 return; /* all done */
2234 if (var
->initvalue
) {
2235 c
= tor_malloc_zero(sizeof(config_line_t
));
2236 c
->key
= tor_strdup(var
->name
);
2237 c
->value
= tor_strdup(var
->initvalue
);
2238 if (config_assign_value(fmt
, options
, c
, &msg
) < 0) {
2239 log_warn(LD_BUG
, "Failed to assign default: %s", msg
);
2240 tor_free(msg
); /* if this happens it's a bug */
2242 config_free_lines(c
);
2246 /** Print a usage message for tor. */
2251 "Copyright (c) 2001-2004, Roger Dingledine\n"
2252 "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
2253 "Copyright (c) 2007-2008, The Tor Project, Inc.\n\n"
2254 "tor -f <torrc> [args]\n"
2255 "See man page for options, or https://www.torproject.org/ for "
2256 "documentation.\n");
2259 /** Print all non-obsolete torrc options. */
2261 list_torrc_options(void)
2264 smartlist_t
*lines
= smartlist_create();
2265 for (i
= 0; _option_vars
[i
].name
; ++i
) {
2266 config_var_t
*var
= &_option_vars
[i
];
2268 if (var
->type
== CONFIG_TYPE_OBSOLETE
||
2269 var
->type
== CONFIG_TYPE_LINELIST_V
)
2271 desc
= config_find_description(&options_format
, var
->name
);
2272 printf("%s\n", var
->name
);
2274 wrap_string(lines
, desc
, 76, " ", " ");
2275 SMARTLIST_FOREACH(lines
, char *, cp
, {
2279 smartlist_clear(lines
);
2282 smartlist_free(lines
);
2285 /** Last value actually set by resolve_my_address. */
2286 static uint32_t last_resolved_addr
= 0;
2288 * Based on <b>options-\>Address</b>, guess our public IP address and put it
2289 * (in host order) into *<b>addr_out</b>. If <b>hostname_out</b> is provided,
2290 * set *<b>hostname_out</b> to a new string holding the hostname we used to
2291 * get the address. Return 0 if all is well, or -1 if we can't find a suitable
2292 * public IP address.
2295 resolve_my_address(int warn_severity
, or_options_t
*options
,
2296 uint32_t *addr_out
, char **hostname_out
)
2299 struct hostent
*rent
;
2302 int explicit_hostname
=1;
2303 int from_interface
=0;
2304 char tmpbuf
[INET_NTOA_BUF_LEN
];
2305 const char *address
= options
->Address
;
2306 int notice_severity
= warn_severity
<= LOG_NOTICE
?
2307 LOG_NOTICE
: warn_severity
;
2309 tor_assert(addr_out
);
2311 if (address
&& *address
) {
2312 strlcpy(hostname
, address
, sizeof(hostname
));
2313 } else { /* then we need to guess our address */
2314 explicit_ip
= 0; /* it's implicit */
2315 explicit_hostname
= 0; /* it's implicit */
2317 if (gethostname(hostname
, sizeof(hostname
)) < 0) {
2318 log_fn(warn_severity
, LD_NET
,"Error obtaining local hostname");
2321 log_debug(LD_CONFIG
,"Guessed local host name as '%s'",hostname
);
2324 /* now we know hostname. resolve it and keep only the IP address */
2326 if (tor_inet_aton(hostname
, &in
) == 0) {
2327 /* then we have to resolve it */
2329 rent
= (struct hostent
*)gethostbyname(hostname
);
2331 uint32_t interface_ip
;
2333 if (explicit_hostname
) {
2334 log_fn(warn_severity
, LD_CONFIG
,
2335 "Could not resolve local Address '%s'. Failing.", hostname
);
2338 log_fn(notice_severity
, LD_CONFIG
,
2339 "Could not resolve guessed local hostname '%s'. "
2340 "Trying something else.", hostname
);
2341 if (get_interface_address(warn_severity
, &interface_ip
)) {
2342 log_fn(warn_severity
, LD_CONFIG
,
2343 "Could not get local interface IP address. Failing.");
2347 in
.s_addr
= htonl(interface_ip
);
2348 tor_inet_ntoa(&in
,tmpbuf
,sizeof(tmpbuf
));
2349 log_fn(notice_severity
, LD_CONFIG
, "Learned IP address '%s' for "
2350 "local interface. Using that.", tmpbuf
);
2351 strlcpy(hostname
, "<guessed from interfaces>", sizeof(hostname
));
2353 tor_assert(rent
->h_length
== 4);
2354 memcpy(&in
.s_addr
, rent
->h_addr
, rent
->h_length
);
2356 if (!explicit_hostname
&&
2357 is_internal_IP(ntohl(in
.s_addr
), 0)) {
2358 uint32_t interface_ip
;
2360 tor_inet_ntoa(&in
,tmpbuf
,sizeof(tmpbuf
));
2361 log_fn(notice_severity
, LD_CONFIG
, "Guessed local hostname '%s' "
2362 "resolves to a private IP address (%s). Trying something "
2363 "else.", hostname
, tmpbuf
);
2365 if (get_interface_address(warn_severity
, &interface_ip
)) {
2366 log_fn(warn_severity
, LD_CONFIG
,
2367 "Could not get local interface IP address. Too bad.");
2368 } else if (is_internal_IP(interface_ip
, 0)) {
2370 in2
.s_addr
= htonl(interface_ip
);
2371 tor_inet_ntoa(&in2
,tmpbuf
,sizeof(tmpbuf
));
2372 log_fn(notice_severity
, LD_CONFIG
,
2373 "Interface IP address '%s' is a private address too. "
2374 "Ignoring.", tmpbuf
);
2377 in
.s_addr
= htonl(interface_ip
);
2378 tor_inet_ntoa(&in
,tmpbuf
,sizeof(tmpbuf
));
2379 log_fn(notice_severity
, LD_CONFIG
,
2380 "Learned IP address '%s' for local interface."
2381 " Using that.", tmpbuf
);
2382 strlcpy(hostname
, "<guessed from interfaces>", sizeof(hostname
));
2388 tor_inet_ntoa(&in
,tmpbuf
,sizeof(tmpbuf
));
2389 if (is_internal_IP(ntohl(in
.s_addr
), 0) &&
2390 options
->_PublishServerDescriptor
) {
2391 /* make sure we're ok with publishing an internal IP */
2392 if (!options
->DirServers
&& !options
->AlternateDirAuthority
) {
2393 /* if they are using the default dirservers, disallow internal IPs
2395 log_fn(warn_severity
, LD_CONFIG
,
2396 "Address '%s' resolves to private IP address '%s'. "
2397 "Tor servers that use the default DirServers must have public "
2398 "IP addresses.", hostname
, tmpbuf
);
2402 /* even if they've set their own dirservers, require an explicit IP if
2403 * they're using an internal address. */
2404 log_fn(warn_severity
, LD_CONFIG
, "Address '%s' resolves to private "
2405 "IP address '%s'. Please set the Address config option to be "
2406 "the IP address you want to use.", hostname
, tmpbuf
);
2411 log_debug(LD_CONFIG
, "Resolved Address to '%s'.", tmpbuf
);
2412 *addr_out
= ntohl(in
.s_addr
);
2413 if (last_resolved_addr
&& last_resolved_addr
!= *addr_out
) {
2414 /* Leave this as a notice, regardless of the requested severity,
2415 * at least until dynamic IP address support becomes bulletproof. */
2417 "Your IP address seems to have changed to %s. Updating.",
2419 ip_address_changed(0);
2421 if (last_resolved_addr
!= *addr_out
) {
2423 const char *h
= hostname
;
2425 method
= "CONFIGURED";
2427 } else if (explicit_hostname
) {
2428 method
= "RESOLVED";
2429 } else if (from_interface
) {
2430 method
= "INTERFACE";
2433 method
= "GETHOSTNAME";
2435 control_event_server_status(LOG_NOTICE
,
2436 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s %s%s",
2437 tmpbuf
, method
, h
?"HOSTNAME=":"", h
);
2439 last_resolved_addr
= *addr_out
;
2441 *hostname_out
= tor_strdup(hostname
);
2445 /** Return true iff <b>addr</b> is judged to be on the same network as us, or
2446 * on a private network.
2449 is_local_addr(const tor_addr_t
*addr
)
2451 if (tor_addr_is_internal(addr
, 0))
2453 /* Check whether ip is on the same /24 as we are. */
2454 if (get_options()->EnforceDistinctSubnets
== 0)
2456 if (tor_addr_family(addr
) == AF_INET
) {
2457 /*XXXX021 IP6 what corresponds to an /24? */
2458 uint32_t ip
= tor_addr_to_ipv4h(addr
);
2460 /* It's possible that this next check will hit before the first time
2461 * resolve_my_address actually succeeds. (For clients, it is likely that
2462 * resolve_my_address will never be called at all). In those cases,
2463 * last_resolved_addr will be 0, and so checking to see whether ip is on
2464 * the same /24 as last_resolved_addr will be the same as checking whether
2465 * it was on net 0, which is already done by is_internal_IP.
2467 if ((last_resolved_addr
& 0xffffff00ul
) == (ip
& 0xffffff00ul
))
2473 /** Called when we don't have a nickname set. Try to guess a good nickname
2474 * based on the hostname, and return it in a newly allocated string. If we
2475 * can't, return NULL and let the caller warn if it wants to. */
2477 get_default_nickname(void)
2479 static const char * const bad_default_nicknames
[] = {
2483 char localhostname
[256];
2484 char *cp
, *out
, *outp
;
2487 if (gethostname(localhostname
, sizeof(localhostname
)) < 0)
2490 /* Put it in lowercase; stop at the first dot. */
2491 if ((cp
= strchr(localhostname
, '.')))
2493 tor_strlower(localhostname
);
2495 /* Strip invalid characters. */
2497 out
= outp
= tor_malloc(strlen(localhostname
) + 1);
2499 if (strchr(LEGAL_NICKNAME_CHARACTERS
, *cp
))
2506 /* Enforce length. */
2507 if (strlen(out
) > MAX_NICKNAME_LEN
)
2508 out
[MAX_NICKNAME_LEN
]='\0';
2510 /* Check for dumb names. */
2511 for (i
= 0; bad_default_nicknames
[i
]; ++i
) {
2512 if (!strcmp(out
, bad_default_nicknames
[i
])) {
2521 /** Release storage held by <b>options</b>. */
2523 config_free(config_format_t
*fmt
, void *options
)
2527 tor_assert(options
);
2529 for (i
=0; fmt
->vars
[i
].name
; ++i
)
2530 option_clear(fmt
, options
, &(fmt
->vars
[i
]));
2532 config_line_t
**linep
= STRUCT_VAR_P(options
, fmt
->extra
->var_offset
);
2533 config_free_lines(*linep
);
2539 /** Return true iff a and b contain identical keys and values in identical
2542 config_lines_eq(config_line_t
*a
, config_line_t
*b
)
2545 if (strcasecmp(a
->key
, b
->key
) || strcmp(a
->value
, b
->value
))
2555 /** Return true iff the option <b>name</b> has the same value in <b>o1</b>
2556 * and <b>o2</b>. Must not be called for LINELIST_S or OBSOLETE options.
2559 option_is_same(config_format_t
*fmt
,
2560 or_options_t
*o1
, or_options_t
*o2
, const char *name
)
2562 config_line_t
*c1
, *c2
;
2567 c1
= get_assigned_option(fmt
, o1
, name
, 0);
2568 c2
= get_assigned_option(fmt
, o2
, name
, 0);
2569 r
= config_lines_eq(c1
, c2
);
2570 config_free_lines(c1
);
2571 config_free_lines(c2
);
2575 /** Copy storage held by <b>old</b> into a new or_options_t and return it. */
2576 static or_options_t
*
2577 options_dup(config_format_t
*fmt
, or_options_t
*old
)
2579 or_options_t
*newopts
;
2581 config_line_t
*line
;
2583 newopts
= config_alloc(fmt
);
2584 for (i
=0; fmt
->vars
[i
].name
; ++i
) {
2585 if (fmt
->vars
[i
].type
== CONFIG_TYPE_LINELIST_S
)
2587 if (fmt
->vars
[i
].type
== CONFIG_TYPE_OBSOLETE
)
2589 line
= get_assigned_option(fmt
, old
, fmt
->vars
[i
].name
, 0);
2592 if (config_assign(fmt
, newopts
, line
, 0, 0, &msg
) < 0) {
2593 log_err(LD_BUG
, "Config_get_assigned_option() generated "
2594 "something we couldn't config_assign(): %s", msg
);
2599 config_free_lines(line
);
2604 /** Return a new empty or_options_t. Used for testing. */
2608 return config_alloc(&options_format
);
2611 /** Set <b>options</b> to hold reasonable defaults for most options.
2612 * Each option defaults to zero. */
2614 options_init(or_options_t
*options
)
2616 config_init(&options_format
, options
);
2619 /** Set all vars in the configuration object <b>options</b> to their default
2622 config_init(config_format_t
*fmt
, void *options
)
2626 CHECK(fmt
, options
);
2628 for (i
=0; fmt
->vars
[i
].name
; ++i
) {
2629 var
= &fmt
->vars
[i
];
2630 if (!var
->initvalue
)
2631 continue; /* defaults to NULL or 0 */
2632 option_reset(fmt
, options
, var
, 1);
2636 /** Allocate and return a new string holding the written-out values of the vars
2637 * in 'options'. If 'minimal', do not write out any default-valued vars.
2638 * Else, if comment_defaults, write default values as comments.
2641 config_dump(config_format_t
*fmt
, void *options
, int minimal
,
2642 int comment_defaults
)
2644 smartlist_t
*elements
;
2645 or_options_t
*defaults
;
2646 config_line_t
*line
, *assigned
;
2652 defaults
= config_alloc(fmt
);
2653 config_init(fmt
, defaults
);
2655 /* XXX use a 1 here so we don't add a new log line while dumping */
2656 if (fmt
->validate_fn(NULL
,defaults
, 1, &msg
) < 0) {
2657 log_err(LD_BUG
, "Failed to validate default config.");
2662 elements
= smartlist_create();
2663 for (i
=0; fmt
->vars
[i
].name
; ++i
) {
2664 int comment_option
= 0;
2665 if (fmt
->vars
[i
].type
== CONFIG_TYPE_OBSOLETE
||
2666 fmt
->vars
[i
].type
== CONFIG_TYPE_LINELIST_S
)
2668 /* Don't save 'hidden' control variables. */
2669 if (!strcmpstart(fmt
->vars
[i
].name
, "__"))
2671 if (minimal
&& option_is_same(fmt
, options
, defaults
, fmt
->vars
[i
].name
))
2673 else if (comment_defaults
&&
2674 option_is_same(fmt
, options
, defaults
, fmt
->vars
[i
].name
))
2677 desc
= config_find_description(fmt
, fmt
->vars
[i
].name
);
2678 line
= assigned
= get_assigned_option(fmt
, options
, fmt
->vars
[i
].name
, 1);
2681 /* Only dump the description if there's something to describe. */
2682 wrap_string(elements
, desc
, 78, "# ", "# ");
2685 for (; line
; line
= line
->next
) {
2686 size_t len
= strlen(line
->key
) + strlen(line
->value
) + 5;
2688 tmp
= tor_malloc(len
);
2689 if (tor_snprintf(tmp
, len
, "%s%s %s\n",
2690 comment_option
? "# " : "",
2691 line
->key
, line
->value
)<0) {
2692 log_err(LD_BUG
,"Internal error writing option value");
2695 smartlist_add(elements
, tmp
);
2697 config_free_lines(assigned
);
2701 line
= *(config_line_t
**)STRUCT_VAR_P(options
, fmt
->extra
->var_offset
);
2702 for (; line
; line
= line
->next
) {
2703 size_t len
= strlen(line
->key
) + strlen(line
->value
) + 3;
2705 tmp
= tor_malloc(len
);
2706 if (tor_snprintf(tmp
, len
, "%s %s\n", line
->key
, line
->value
)<0) {
2707 log_err(LD_BUG
,"Internal error writing option value");
2710 smartlist_add(elements
, tmp
);
2714 result
= smartlist_join_strings(elements
, "", 0, NULL
);
2715 SMARTLIST_FOREACH(elements
, char *, cp
, tor_free(cp
));
2716 smartlist_free(elements
);
2717 config_free(fmt
, defaults
);
2721 /** Return a string containing a possible configuration file that would give
2722 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
2723 * include options that are the same as Tor's defaults.
2726 options_dump(or_options_t
*options
, int minimal
)
2728 return config_dump(&options_format
, options
, minimal
, 0);
2731 /** Return 0 if every element of sl is a string holding a decimal
2732 * representation of a port number, or if sl is NULL.
2733 * Otherwise set *msg and return -1. */
2735 validate_ports_csv(smartlist_t
*sl
, const char *name
, char **msg
)
2744 SMARTLIST_FOREACH(sl
, const char *, cp
,
2747 if (i
< 1 || i
> 65535) {
2748 int r
= tor_snprintf(buf
, sizeof(buf
),
2749 "Port '%s' out of range in %s", cp
, name
);
2750 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
2757 /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
2758 * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
2762 ensure_bandwidth_cap(uint64_t *value
, const char *desc
, char **msg
)
2766 if (*value
> ROUTER_MAX_DECLARED_BANDWIDTH
) {
2767 /* This handles an understandable special case where somebody says "2gb"
2768 * whereas our actual maximum is 2gb-1 (INT_MAX) */
2771 if (*value
> ROUTER_MAX_DECLARED_BANDWIDTH
) {
2772 r
= tor_snprintf(buf
, sizeof(buf
), "%s ("U64_FORMAT
") must be at most %d",
2773 desc
, U64_PRINTF_ARG(*value
),
2774 ROUTER_MAX_DECLARED_BANDWIDTH
);
2775 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
2781 /** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
2782 * and write it to <b>options</b>-\>_PublishServerDescriptor. Treat "1"
2783 * as "v2,v3" unless BridgeRelay is 1, in which case treat it as "bridge".
2785 * Return 0 on success or -1 if not a recognized authority type (in which
2786 * case the value of _PublishServerDescriptor is undefined). */
2788 compute_publishserverdescriptor(or_options_t
*options
)
2790 smartlist_t
*list
= options
->PublishServerDescriptor
;
2791 authority_type_t
*auth
= &options
->_PublishServerDescriptor
;
2792 *auth
= NO_AUTHORITY
;
2793 if (!list
) /* empty list, answer is none */
2795 SMARTLIST_FOREACH(list
, const char *, string
, {
2796 if (!strcasecmp(string
, "v1"))
2797 *auth
|= V1_AUTHORITY
;
2798 else if (!strcmp(string
, "1"))
2799 if (options
->BridgeRelay
)
2800 *auth
|= BRIDGE_AUTHORITY
;
2802 *auth
|= V2_AUTHORITY
| V3_AUTHORITY
;
2803 else if (!strcasecmp(string
, "v2"))
2804 *auth
|= V2_AUTHORITY
;
2805 else if (!strcasecmp(string
, "v3"))
2806 *auth
|= V3_AUTHORITY
;
2807 else if (!strcasecmp(string
, "bridge"))
2808 *auth
|= BRIDGE_AUTHORITY
;
2809 else if (!strcasecmp(string
, "hidserv"))
2810 *auth
|= HIDSERV_AUTHORITY
;
2811 else if (!strcasecmp(string
, "") || !strcmp(string
, "0"))
2819 /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
2820 * services can overload the directory system. */
2821 #define MIN_REND_POST_PERIOD (10*60)
2823 /** Highest allowable value for RendPostPeriod. */
2824 #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
2826 /** Lowest allowable value for CircuitBuildTimeout; values too low will
2827 * increase network load because of failing connections being retried, and
2828 * might prevent users from connecting to the network at all. */
2829 #define MIN_CIRCUIT_BUILD_TIMEOUT 30
2831 /** Lowest allowable value for MaxCircuitDirtiness; if this is too low, Tor
2832 * will generate too many circuits and potentially overload the network. */
2833 #define MIN_MAX_CIRCUIT_DIRTINESS 10
2835 /** Return 0 if every setting in <b>options</b> is reasonable, and a
2836 * permissible transition from <b>old_options</b>. Else return -1.
2837 * Should have no side effects, except for normalizing the contents of
2840 * On error, tor_strdup an error explanation into *<b>msg</b>.
2843 * If <b>from_setconf</b>, we were called by the controller, and our
2844 * Log line should stay empty. If it's 0, then give us a default log
2845 * if there are no logs defined.
2848 options_validate(or_options_t
*old_options
, or_options_t
*options
,
2849 int from_setconf
, char **msg
)
2853 const char *uname
= get_uname();
2855 #define REJECT(arg) \
2856 STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
2857 #define COMPLAIN(arg) STMT_BEGIN log(LOG_WARN, LD_CONFIG, arg); STMT_END
2862 if (options
->ORPort
< 0 || options
->ORPort
> 65535)
2863 REJECT("ORPort option out of bounds.");
2865 if (server_mode(options
) &&
2866 (!strcmpstart(uname
, "Windows 95") ||
2867 !strcmpstart(uname
, "Windows 98") ||
2868 !strcmpstart(uname
, "Windows Me"))) {
2869 log(LOG_WARN
, LD_CONFIG
, "Tor is running as a server, but you are "
2870 "running %s; this probably won't work. See "
2871 "http://wiki.noreply.org/noreply/TheOnionRouter/TorFAQ#ServerOS "
2872 "for details.", uname
);
2875 if (options
->ORPort
== 0 && options
->ORListenAddress
!= NULL
)
2876 REJECT("ORPort must be defined if ORListenAddress is defined.");
2878 if (options
->DirPort
== 0 && options
->DirListenAddress
!= NULL
)
2879 REJECT("DirPort must be defined if DirListenAddress is defined.");
2881 if (options
->DNSPort
== 0 && options
->DNSListenAddress
!= NULL
)
2882 REJECT("DNSPort must be defined if DNSListenAddress is defined.");
2884 if (options
->ControlPort
== 0 && options
->ControlListenAddress
!= NULL
)
2885 REJECT("ControlPort must be defined if ControlListenAddress is defined.");
2887 if (options
->TransPort
== 0 && options
->TransListenAddress
!= NULL
)
2888 REJECT("TransPort must be defined if TransListenAddress is defined.");
2890 if (options
->NatdPort
== 0 && options
->NatdListenAddress
!= NULL
)
2891 REJECT("NatdPort must be defined if NatdListenAddress is defined.");
2893 /* Don't gripe about SocksPort 0 with SocksListenAddress set; a standard
2894 * configuration does this. */
2896 for (i
= 0; i
< 3; ++i
) {
2897 int is_socks
= i
==0;
2898 int is_trans
= i
==1;
2899 config_line_t
*line
, *opt
, *old
;
2902 opt
= options
->SocksListenAddress
;
2903 old
= old_options
? old_options
->SocksListenAddress
: NULL
;
2905 } else if (is_trans
) {
2906 opt
= options
->TransListenAddress
;
2907 old
= old_options
? old_options
->TransListenAddress
: NULL
;
2908 tp
= "transparent proxy";
2910 opt
= options
->NatdListenAddress
;
2911 old
= old_options
? old_options
->NatdListenAddress
: NULL
;
2915 for (line
= opt
; line
; line
= line
->next
) {
2916 char *address
= NULL
;
2919 if (parse_addr_port(LOG_WARN
, line
->value
, &address
, &addr
, &port
)<0)
2920 continue; /* We'll warn about this later. */
2921 if (!is_internal_IP(addr
, 1) &&
2922 (!old_options
|| !config_lines_eq(old
, opt
))) {
2924 "You specified a public address '%s' for a %s. Other "
2925 "people on the Internet might find your computer and use it as "
2926 "an open %s. Please don't allow this unless you have "
2927 "a good reason.", address
, tp
, tp
);
2933 if (validate_data_directory(options
)<0)
2934 REJECT("Invalid DataDirectory");
2936 if (options
->Nickname
== NULL
) {
2937 if (server_mode(options
)) {
2938 if (!(options
->Nickname
= get_default_nickname())) {
2939 log_notice(LD_CONFIG
, "Couldn't pick a nickname based on "
2940 "our hostname; using %s instead.", UNNAMED_ROUTER_NICKNAME
);
2941 options
->Nickname
= tor_strdup(UNNAMED_ROUTER_NICKNAME
);
2943 log_notice(LD_CONFIG
, "Choosing default nickname '%s'",
2948 if (!is_legal_nickname(options
->Nickname
)) {
2949 r
= tor_snprintf(buf
, sizeof(buf
),
2950 "Nickname '%s' is wrong length or contains illegal characters.",
2952 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
2957 if (server_mode(options
) && !options
->ContactInfo
)
2958 log(LOG_NOTICE
, LD_CONFIG
, "Your ContactInfo config option is not set. "
2959 "Please consider setting it, so we can contact you if your server is "
2960 "misconfigured or something else goes wrong.");
2962 /* Special case on first boot if no Log options are given. */
2963 if (!options
->Logs
&& !options
->RunAsDaemon
&& !from_setconf
)
2964 config_line_append(&options
->Logs
, "Log", "notice stdout");
2966 if (options_init_logs(options
, 1)<0) /* Validate the log(s) */
2967 REJECT("Failed to validate Log options. See logs for details.");
2969 if (options
->NoPublish
) {
2970 log(LOG_WARN
, LD_CONFIG
,
2971 "NoPublish is obsolete. Use PublishServerDescriptor instead.");
2972 SMARTLIST_FOREACH(options
->PublishServerDescriptor
, char *, s
,
2974 smartlist_clear(options
->PublishServerDescriptor
);
2977 if (authdir_mode(options
)) {
2978 /* confirm that our address isn't broken, so we can complain now */
2980 if (resolve_my_address(LOG_WARN
, options
, &tmp
, NULL
) < 0)
2981 REJECT("Failed to resolve/guess local address. See logs for details.");
2985 if (options
->RunAsDaemon
&& torrc_fname
&& path_is_relative(torrc_fname
))
2986 REJECT("Can't use a relative path to torrc when RunAsDaemon is set.");
2989 if (options
->SocksPort
< 0 || options
->SocksPort
> 65535)
2990 REJECT("SocksPort option out of bounds.");
2992 if (options
->DNSPort
< 0 || options
->DNSPort
> 65535)
2993 REJECT("DNSPort option out of bounds.");
2995 if (options
->TransPort
< 0 || options
->TransPort
> 65535)
2996 REJECT("TransPort option out of bounds.");
2998 if (options
->NatdPort
< 0 || options
->NatdPort
> 65535)
2999 REJECT("NatdPort option out of bounds.");
3001 if (options
->SocksPort
== 0 && options
->TransPort
== 0 &&
3002 options
->NatdPort
== 0 && options
->ORPort
== 0 &&
3003 options
->DNSPort
== 0 && !options
->RendConfigLines
)
3004 log(LOG_WARN
, LD_CONFIG
,
3005 "SocksPort, TransPort, NatdPort, DNSPort, and ORPort are all "
3006 "undefined, and there aren't any hidden services configured. "
3007 "Tor will still run, but probably won't do anything.");
3009 if (options
->ControlPort
< 0 || options
->ControlPort
> 65535)
3010 REJECT("ControlPort option out of bounds.");
3012 if (options
->DirPort
< 0 || options
->DirPort
> 65535)
3013 REJECT("DirPort option out of bounds.");
3015 #ifndef USE_TRANSPARENT
3016 if (options
->TransPort
|| options
->TransListenAddress
)
3017 REJECT("TransPort and TransListenAddress are disabled in this build.");
3020 if (options
->ExcludeExitNodes
|| options
->ExcludeNodes
) {
3021 options
->_ExcludeExitNodesUnion
= routerset_new();
3022 routerset_union(options
->_ExcludeExitNodesUnion
,options
->ExcludeExitNodes
);
3023 routerset_union(options
->_ExcludeExitNodesUnion
,options
->ExcludeNodes
);
3026 if (options
->StrictExitNodes
&&
3027 (!options
->ExitNodes
) &&
3029 (old_options
->StrictExitNodes
!= options
->StrictExitNodes
) ||
3030 (!routerset_equal(old_options
->ExitNodes
,options
->ExitNodes
))))
3031 COMPLAIN("StrictExitNodes set, but no ExitNodes listed.");
3033 if (options
->StrictEntryNodes
&&
3034 (!options
->EntryNodes
) &&
3036 (old_options
->StrictEntryNodes
!= options
->StrictEntryNodes
) ||
3037 (!routerset_equal(old_options
->EntryNodes
,options
->EntryNodes
))))
3038 COMPLAIN("StrictEntryNodes set, but no EntryNodes listed.");
3040 if (options
->EntryNodes
&& !routerset_is_list(options
->EntryNodes
)) {
3041 /* XXXX fix this; see entry_guards_prepend_from_config(). */
3042 REJECT("IPs or countries are not yet supported in EntryNodes.");
3045 if (options
->AuthoritativeDir
) {
3046 if (!options
->ContactInfo
)
3047 REJECT("Authoritative directory servers must set ContactInfo");
3048 if (options
->V1AuthoritativeDir
&& !options
->RecommendedVersions
)
3049 REJECT("V1 auth dir servers must set RecommendedVersions.");
3050 if (!options
->RecommendedClientVersions
)
3051 options
->RecommendedClientVersions
=
3052 config_lines_dup(options
->RecommendedVersions
);
3053 if (!options
->RecommendedServerVersions
)
3054 options
->RecommendedServerVersions
=
3055 config_lines_dup(options
->RecommendedVersions
);
3056 if (options
->VersioningAuthoritativeDir
&&
3057 (!options
->RecommendedClientVersions
||
3058 !options
->RecommendedServerVersions
))
3059 REJECT("Versioning auth dir servers must set Recommended*Versions.");
3060 if (options
->UseEntryGuards
) {
3061 log_info(LD_CONFIG
, "Authoritative directory servers can't set "
3062 "UseEntryGuards. Disabling.");
3063 options
->UseEntryGuards
= 0;
3065 if (!options
->DownloadExtraInfo
&& authdir_mode_any_main(options
)) {
3066 log_info(LD_CONFIG
, "Authoritative directories always try to download "
3067 "extra-info documents. Setting DownloadExtraInfo.");
3068 options
->DownloadExtraInfo
= 1;
3070 if (!(options
->BridgeAuthoritativeDir
|| options
->HSAuthoritativeDir
||
3071 options
->V1AuthoritativeDir
|| options
->V2AuthoritativeDir
||
3072 options
->V3AuthoritativeDir
))
3073 REJECT("AuthoritativeDir is set, but none of "
3074 "(Bridge/HS/V1/V2/V3)AuthoritativeDir is set.");
3077 if (options
->AuthoritativeDir
&& !options
->DirPort
)
3078 REJECT("Running as authoritative directory, but no DirPort set.");
3080 if (options
->AuthoritativeDir
&& !options
->ORPort
)
3081 REJECT("Running as authoritative directory, but no ORPort set.");
3083 if (options
->AuthoritativeDir
&& options
->ClientOnly
)
3084 REJECT("Running as authoritative directory, but ClientOnly also set.");
3086 if (options
->HSAuthorityRecordStats
&& !options
->HSAuthoritativeDir
)
3087 REJECT("HSAuthorityRecordStats is set but we're not running as "
3088 "a hidden service authority.");
3090 if (options
->ConnLimit
<= 0) {
3091 r
= tor_snprintf(buf
, sizeof(buf
),
3092 "ConnLimit must be greater than 0, but was set to %d",
3093 options
->ConnLimit
);
3094 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
3098 if (validate_ports_csv(options
->FirewallPorts
, "FirewallPorts", msg
) < 0)
3101 if (validate_ports_csv(options
->LongLivedPorts
, "LongLivedPorts", msg
) < 0)
3104 if (validate_ports_csv(options
->RejectPlaintextPorts
,
3105 "RejectPlaintextPorts", msg
) < 0)
3108 if (validate_ports_csv(options
->WarnPlaintextPorts
,
3109 "WarnPlaintextPorts", msg
) < 0)
3112 if (options
->FascistFirewall
&& !options
->ReachableAddresses
) {
3113 if (options
->FirewallPorts
&& smartlist_len(options
->FirewallPorts
)) {
3114 /* We already have firewall ports set, so migrate them to
3115 * ReachableAddresses, which will set ReachableORAddresses and
3116 * ReachableDirAddresses if they aren't set explicitly. */
3117 smartlist_t
*instead
= smartlist_create();
3118 config_line_t
*new_line
= tor_malloc_zero(sizeof(config_line_t
));
3119 new_line
->key
= tor_strdup("ReachableAddresses");
3120 /* If we're configured with the old format, we need to prepend some
3122 SMARTLIST_FOREACH(options
->FirewallPorts
, const char *, portno
,
3124 int p
= atoi(portno
);
3128 tor_snprintf(s
, 16, "*:%d", p
);
3129 smartlist_add(instead
, s
);
3131 new_line
->value
= smartlist_join_strings(instead
,",",0,NULL
);
3132 /* These have been deprecated since 0.1.1.5-alpha-cvs */
3133 log(LOG_NOTICE
, LD_CONFIG
,
3134 "Converting FascistFirewall and FirewallPorts "
3135 "config options to new format: \"ReachableAddresses %s\"",
3137 options
->ReachableAddresses
= new_line
;
3138 SMARTLIST_FOREACH(instead
, char *, cp
, tor_free(cp
));
3139 smartlist_free(instead
);
3141 /* We do not have FirewallPorts set, so add 80 to
3142 * ReachableDirAddresses, and 443 to ReachableORAddresses. */
3143 if (!options
->ReachableDirAddresses
) {
3144 config_line_t
*new_line
= tor_malloc_zero(sizeof(config_line_t
));
3145 new_line
->key
= tor_strdup("ReachableDirAddresses");
3146 new_line
->value
= tor_strdup("*:80");
3147 options
->ReachableDirAddresses
= new_line
;
3148 log(LOG_NOTICE
, LD_CONFIG
, "Converting FascistFirewall config option "
3149 "to new format: \"ReachableDirAddresses *:80\"");
3151 if (!options
->ReachableORAddresses
) {
3152 config_line_t
*new_line
= tor_malloc_zero(sizeof(config_line_t
));
3153 new_line
->key
= tor_strdup("ReachableORAddresses");
3154 new_line
->value
= tor_strdup("*:443");
3155 options
->ReachableORAddresses
= new_line
;
3156 log(LOG_NOTICE
, LD_CONFIG
, "Converting FascistFirewall config option "
3157 "to new format: \"ReachableORAddresses *:443\"");
3162 for (i
=0; i
<3; i
++) {
3163 config_line_t
**linep
=
3164 (i
==0) ? &options
->ReachableAddresses
:
3165 (i
==1) ? &options
->ReachableORAddresses
:
3166 &options
->ReachableDirAddresses
;
3169 /* We need to end with a reject *:*, not an implicit accept *:* */
3171 if (!strcmp((*linep
)->value
, "reject *:*")) /* already there */
3173 linep
= &((*linep
)->next
);
3175 *linep
= tor_malloc_zero(sizeof(config_line_t
));
3176 (*linep
)->key
= tor_strdup(
3177 (i
==0) ? "ReachableAddresses" :
3178 (i
==1) ? "ReachableORAddresses" :
3179 "ReachableDirAddresses");
3180 (*linep
)->value
= tor_strdup("reject *:*");
3186 if ((options
->ReachableAddresses
||
3187 options
->ReachableORAddresses
||
3188 options
->ReachableDirAddresses
) &&
3189 server_mode(options
))
3190 REJECT("Servers must be able to freely connect to the rest "
3191 "of the Internet, so they must not set Reachable*Addresses "
3192 "or FascistFirewall.");
3194 if (options
->UseBridges
&&
3195 server_mode(options
))
3196 REJECT("Servers must be able to freely connect to the rest "
3197 "of the Internet, so they must not set UseBridges.");
3199 options
->_AllowInvalid
= 0;
3200 if (options
->AllowInvalidNodes
) {
3201 SMARTLIST_FOREACH(options
->AllowInvalidNodes
, const char *, cp
, {
3202 if (!strcasecmp(cp
, "entry"))
3203 options
->_AllowInvalid
|= ALLOW_INVALID_ENTRY
;
3204 else if (!strcasecmp(cp
, "exit"))
3205 options
->_AllowInvalid
|= ALLOW_INVALID_EXIT
;
3206 else if (!strcasecmp(cp
, "middle"))
3207 options
->_AllowInvalid
|= ALLOW_INVALID_MIDDLE
;
3208 else if (!strcasecmp(cp
, "introduction"))
3209 options
->_AllowInvalid
|= ALLOW_INVALID_INTRODUCTION
;
3210 else if (!strcasecmp(cp
, "rendezvous"))
3211 options
->_AllowInvalid
|= ALLOW_INVALID_RENDEZVOUS
;
3213 r
= tor_snprintf(buf
, sizeof(buf
),
3214 "Unrecognized value '%s' in AllowInvalidNodes", cp
);
3215 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
3221 if (compute_publishserverdescriptor(options
) < 0) {
3222 r
= tor_snprintf(buf
, sizeof(buf
),
3223 "Unrecognized value in PublishServerDescriptor");
3224 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
3228 if (options
->MinUptimeHidServDirectoryV2
< 0) {
3229 log_warn(LD_CONFIG
, "MinUptimeHidServDirectoryV2 option must be at "
3230 "least 0 seconds. Changing to 0.");
3231 options
->MinUptimeHidServDirectoryV2
= 0;
3234 if (options
->RendPostPeriod
< MIN_REND_POST_PERIOD
) {
3235 log(LOG_WARN
,LD_CONFIG
,"RendPostPeriod option is too short; "
3236 "raising to %d seconds.", MIN_REND_POST_PERIOD
);
3237 options
->RendPostPeriod
= MIN_REND_POST_PERIOD
;
3240 if (options
->RendPostPeriod
> MAX_DIR_PERIOD
) {
3241 log(LOG_WARN
, LD_CONFIG
, "RendPostPeriod is too large; clipping to %ds.",
3243 options
->RendPostPeriod
= MAX_DIR_PERIOD
;
3246 if (options
->CircuitBuildTimeout
< MIN_CIRCUIT_BUILD_TIMEOUT
) {
3247 log(LOG_WARN
, LD_CONFIG
, "CircuitBuildTimeout option is too short; "
3248 "raising to %d seconds.", MIN_CIRCUIT_BUILD_TIMEOUT
);
3249 options
->CircuitBuildTimeout
= MIN_CIRCUIT_BUILD_TIMEOUT
;
3252 if (options
->MaxCircuitDirtiness
< MIN_MAX_CIRCUIT_DIRTINESS
) {
3253 log(LOG_WARN
, LD_CONFIG
, "MaxCircuitDirtiness option is too short; "
3254 "raising to %d seconds.", MIN_MAX_CIRCUIT_DIRTINESS
);
3255 options
->MaxCircuitDirtiness
= MIN_MAX_CIRCUIT_DIRTINESS
;
3258 if (options
->KeepalivePeriod
< 1)
3259 REJECT("KeepalivePeriod option must be positive.");
3261 if (ensure_bandwidth_cap(&options
->BandwidthRate
,
3262 "BandwidthRate", msg
) < 0)
3264 if (ensure_bandwidth_cap(&options
->BandwidthBurst
,
3265 "BandwidthBurst", msg
) < 0)
3267 if (ensure_bandwidth_cap(&options
->MaxAdvertisedBandwidth
,
3268 "MaxAdvertisedBandwidth", msg
) < 0)
3270 if (ensure_bandwidth_cap(&options
->RelayBandwidthRate
,
3271 "RelayBandwidthRate", msg
) < 0)
3273 if (ensure_bandwidth_cap(&options
->RelayBandwidthBurst
,
3274 "RelayBandwidthBurst", msg
) < 0)
3277 if (server_mode(options
)) {
3278 if (options
->BandwidthRate
< ROUTER_REQUIRED_MIN_BANDWIDTH
*2) {
3279 r
= tor_snprintf(buf
, sizeof(buf
),
3280 "BandwidthRate is set to %d bytes/second. "
3281 "For servers, it must be at least %d.",
3282 (int)options
->BandwidthRate
,
3283 ROUTER_REQUIRED_MIN_BANDWIDTH
*2);
3284 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
3286 } else if (options
->MaxAdvertisedBandwidth
<
3287 ROUTER_REQUIRED_MIN_BANDWIDTH
) {
3288 r
= tor_snprintf(buf
, sizeof(buf
),
3289 "MaxAdvertisedBandwidth is set to %d bytes/second. "
3290 "For servers, it must be at least %d.",
3291 (int)options
->MaxAdvertisedBandwidth
,
3292 ROUTER_REQUIRED_MIN_BANDWIDTH
);
3293 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
3296 if (options
->RelayBandwidthRate
&&
3297 options
->RelayBandwidthRate
< ROUTER_REQUIRED_MIN_BANDWIDTH
) {
3298 r
= tor_snprintf(buf
, sizeof(buf
),
3299 "RelayBandwidthRate is set to %d bytes/second. "
3300 "For servers, it must be at least %d.",
3301 (int)options
->RelayBandwidthRate
,
3302 ROUTER_REQUIRED_MIN_BANDWIDTH
);
3303 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
3308 if (options
->RelayBandwidthRate
&& !options
->RelayBandwidthBurst
)
3309 options
->RelayBandwidthBurst
= options
->RelayBandwidthRate
;
3311 if (options
->RelayBandwidthRate
> options
->RelayBandwidthBurst
)
3312 REJECT("RelayBandwidthBurst must be at least equal "
3313 "to RelayBandwidthRate.");
3315 if (options
->BandwidthRate
> options
->BandwidthBurst
)
3316 REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
3318 /* if they set relaybandwidth* really high but left bandwidth*
3319 * at the default, raise the defaults. */
3320 if (options
->RelayBandwidthRate
> options
->BandwidthRate
)
3321 options
->BandwidthRate
= options
->RelayBandwidthRate
;
3322 if (options
->RelayBandwidthBurst
> options
->BandwidthBurst
)
3323 options
->BandwidthBurst
= options
->RelayBandwidthBurst
;
3325 if (accounting_parse_options(options
, 1)<0)
3326 REJECT("Failed to parse accounting options. See logs for details.");
3328 if (options
->HttpProxy
) { /* parse it now */
3329 if (parse_addr_port(LOG_WARN
, options
->HttpProxy
, NULL
,
3330 &options
->HttpProxyAddr
, &options
->HttpProxyPort
) < 0)
3331 REJECT("HttpProxy failed to parse or resolve. Please fix.");
3332 if (options
->HttpProxyPort
== 0) { /* give it a default */
3333 options
->HttpProxyPort
= 80;
3337 if (options
->HttpProxyAuthenticator
) {
3338 if (strlen(options
->HttpProxyAuthenticator
) >= 48)
3339 REJECT("HttpProxyAuthenticator is too long (>= 48 chars).");
3342 if (options
->HttpsProxy
) { /* parse it now */
3343 if (parse_addr_port(LOG_WARN
, options
->HttpsProxy
, NULL
,
3344 &options
->HttpsProxyAddr
, &options
->HttpsProxyPort
) <0)
3345 REJECT("HttpsProxy failed to parse or resolve. Please fix.");
3346 if (options
->HttpsProxyPort
== 0) { /* give it a default */
3347 options
->HttpsProxyPort
= 443;
3351 if (options
->HttpsProxyAuthenticator
) {
3352 if (strlen(options
->HttpsProxyAuthenticator
) >= 48)
3353 REJECT("HttpsProxyAuthenticator is too long (>= 48 chars).");
3356 if (options
->HashedControlPassword
) {
3357 smartlist_t
*sl
= decode_hashed_passwords(options
->HashedControlPassword
);
3359 REJECT("Bad HashedControlPassword: wrong length or bad encoding");
3361 SMARTLIST_FOREACH(sl
, char*, cp
, tor_free(cp
));
3366 if (options
->HashedControlSessionPassword
) {
3367 smartlist_t
*sl
= decode_hashed_passwords(
3368 options
->HashedControlSessionPassword
);
3370 REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
3372 SMARTLIST_FOREACH(sl
, char*, cp
, tor_free(cp
));
3377 if (options
->ControlListenAddress
) {
3378 int all_are_local
= 1;
3380 for (ln
= options
->ControlListenAddress
; ln
; ln
= ln
->next
) {
3381 if (strcmpstart(ln
->value
, "127."))
3384 if (!all_are_local
) {
3385 if (!options
->HashedControlPassword
&&
3386 !options
->HashedControlSessionPassword
&&
3387 !options
->CookieAuthentication
) {
3388 log_warn(LD_CONFIG
, "You have a ControlListenAddress set to accept "
3389 "connections from a non-local address. This means that "
3390 "any program on the internet can reconfigure your Tor. "
3391 "That's so bad that I'm closing your ControlPort for you.");
3392 options
->ControlPort
= 0;
3394 log_warn(LD_CONFIG
, "You have a ControlListenAddress set to accept "
3395 "connections from a non-local address. This means that "
3396 "programs not running on your computer can reconfigure your "
3397 "Tor. That's pretty bad!");
3402 if (options
->ControlPort
&& !options
->HashedControlPassword
&&
3403 !options
->HashedControlSessionPassword
&&
3404 !options
->CookieAuthentication
) {
3405 log_warn(LD_CONFIG
, "ControlPort is open, but no authentication method "
3406 "has been configured. This means that any program on your "
3407 "computer can reconfigure your Tor. That's bad! You should "
3408 "upgrade your Tor controller as soon as possible.");
3411 if (options
->UseEntryGuards
&& ! options
->NumEntryGuards
)
3412 REJECT("Cannot enable UseEntryGuards with NumEntryGuards set to 0");
3414 if (check_nickname_list(options
->MyFamily
, "MyFamily", msg
))
3416 for (cl
= options
->NodeFamilies
; cl
; cl
= cl
->next
) {
3417 if (check_nickname_list(cl
->value
, "NodeFamily", msg
))
3421 if (validate_addr_policies(options
, msg
) < 0)
3424 if (validate_dir_authorities(options
, old_options
) < 0)
3425 REJECT("Directory authority line did not parse. See logs for details.");
3427 if (options
->UseBridges
&& !options
->Bridges
)
3428 REJECT("If you set UseBridges, you must specify at least one bridge.");
3429 if (options
->UseBridges
&& !options
->TunnelDirConns
)
3430 REJECT("If you set UseBridges, you must set TunnelDirConns.");
3431 if (options
->Bridges
) {
3432 for (cl
= options
->Bridges
; cl
; cl
= cl
->next
) {
3433 if (parse_bridge_line(cl
->value
, 1)<0)
3434 REJECT("Bridge line did not parse. See logs for details.");
3438 if (options
->ConstrainedSockets
) {
3439 /* If the user wants to constrain socket buffer use, make sure the desired
3440 * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
3441 if (options
->ConstrainedSockSize
< MIN_CONSTRAINED_TCP_BUFFER
||
3442 options
->ConstrainedSockSize
> MAX_CONSTRAINED_TCP_BUFFER
||
3443 options
->ConstrainedSockSize
% 1024) {
3444 r
= tor_snprintf(buf
, sizeof(buf
),
3445 "ConstrainedSockSize is invalid. Must be a value between %d and %d "
3446 "in 1024 byte increments.",
3447 MIN_CONSTRAINED_TCP_BUFFER
, MAX_CONSTRAINED_TCP_BUFFER
);
3448 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
3451 if (options
->DirPort
) {
3452 /* Providing cached directory entries while system TCP buffers are scarce
3453 * will exacerbate the socket errors. Suggest that this be disabled. */
3454 COMPLAIN("You have requested constrained socket buffers while also "
3455 "serving directory entries via DirPort. It is strongly "
3456 "suggested that you disable serving directory requests when "
3457 "system TCP buffer resources are scarce.");
3461 if (options
->V3AuthVoteDelay
+ options
->V3AuthDistDelay
>=
3462 options
->V3AuthVotingInterval
/2) {
3463 REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
3464 "V3AuthVotingInterval");
3466 if (options
->V3AuthVoteDelay
< MIN_VOTE_SECONDS
)
3467 REJECT("V3AuthVoteDelay is way too low.");
3468 if (options
->V3AuthDistDelay
< MIN_DIST_SECONDS
)
3469 REJECT("V3AuthDistDelay is way too low.");
3471 if (options
->V3AuthNIntervalsValid
< 2)
3472 REJECT("V3AuthNIntervalsValid must be at least 2.");
3474 if (options
->V3AuthVotingInterval
< MIN_VOTE_INTERVAL
) {
3475 REJECT("V3AuthVotingInterval is insanely low.");
3476 } else if (options
->V3AuthVotingInterval
> 24*60*60) {
3477 REJECT("V3AuthVotingInterval is insanely high.");
3478 } else if (((24*60*60) % options
->V3AuthVotingInterval
) != 0) {
3479 COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
3482 if (rend_config_services(options
, 1) < 0)
3483 REJECT("Failed to configure rendezvous options. See logs for details.");
3485 /* Parse client-side authorization for hidden services. */
3486 if (rend_parse_service_authorization(options
, 1) < 0)
3487 REJECT("Failed to configure client authorization for hidden services. "
3488 "See logs for details.");
3490 if (parse_virtual_addr_network(options
->VirtualAddrNetwork
, 1, NULL
)<0)
3493 if (options
->PreferTunneledDirConns
&& !options
->TunnelDirConns
)
3494 REJECT("Must set TunnelDirConns if PreferTunneledDirConns is set.");
3496 if (options
->AutomapHostsSuffixes
) {
3497 SMARTLIST_FOREACH(options
->AutomapHostsSuffixes
, char *, suf
,
3499 size_t len
= strlen(suf
);
3500 if (len
&& suf
[len
-1] == '.')
3505 if (options
->TestingTorNetwork
&& !options
->DirServers
) {
3506 REJECT("TestingTorNetwork may only be configured in combination with "
3507 "a non-default set of DirServers.");
3510 /*XXXX021 checking for defaults manually like this is a bit fragile.*/
3512 /* Keep changes to hard-coded values synchronous to man page and default
3514 if (options
->TestingV3AuthInitialVotingInterval
!= 30*60 &&
3515 !options
->TestingTorNetwork
) {
3516 REJECT("TestingV3AuthInitialVotingInterval may only be changed in testing "
3518 } else if (options
->TestingV3AuthInitialVotingInterval
< MIN_VOTE_INTERVAL
) {
3519 REJECT("TestingV3AuthInitialVotingInterval is insanely low.");
3520 } else if (((30*60) % options
->TestingV3AuthInitialVotingInterval
) != 0) {
3521 REJECT("TestingV3AuthInitialVotingInterval does not divide evenly into "
3525 if (options
->TestingV3AuthInitialVoteDelay
!= 5*60 &&
3526 !options
->TestingTorNetwork
) {
3527 REJECT("TestingV3AuthInitialVoteDelay may only be changed in testing "
3529 } else if (options
->TestingV3AuthInitialVoteDelay
< MIN_VOTE_SECONDS
) {
3530 REJECT("TestingV3AuthInitialVoteDelay is way too low.");
3533 if (options
->TestingV3AuthInitialDistDelay
!= 5*60 &&
3534 !options
->TestingTorNetwork
) {
3535 REJECT("TestingV3AuthInitialDistDelay may only be changed in testing "
3537 } else if (options
->TestingV3AuthInitialDistDelay
< MIN_DIST_SECONDS
) {
3538 REJECT("TestingV3AuthInitialDistDelay is way too low.");
3541 if (options
->TestingV3AuthInitialVoteDelay
+
3542 options
->TestingV3AuthInitialDistDelay
>=
3543 options
->TestingV3AuthInitialVotingInterval
/2) {
3544 REJECT("TestingV3AuthInitialVoteDelay plus TestingV3AuthInitialDistDelay "
3545 "must be less than half TestingV3AuthInitialVotingInterval");
3548 if (options
->TestingAuthDirTimeToLearnReachability
!= 30*60 &&
3549 !options
->TestingTorNetwork
) {
3550 REJECT("TestingAuthDirTimeToLearnReachability may only be changed in "
3551 "testing Tor networks!");
3552 } else if (options
->TestingAuthDirTimeToLearnReachability
< 0) {
3553 REJECT("TestingAuthDirTimeToLearnReachability must be non-negative.");
3554 } else if (options
->TestingAuthDirTimeToLearnReachability
> 2*60*60) {
3555 COMPLAIN("TestingAuthDirTimeToLearnReachability is insanely high.");
3558 if (options
->TestingEstimatedDescriptorPropagationTime
!= 10*60 &&
3559 !options
->TestingTorNetwork
) {
3560 REJECT("TestingEstimatedDescriptorPropagationTime may only be changed in "
3561 "testing Tor networks!");
3562 } else if (options
->TestingEstimatedDescriptorPropagationTime
< 0) {
3563 REJECT("TestingEstimatedDescriptorPropagationTime must be non-negative.");
3564 } else if (options
->TestingEstimatedDescriptorPropagationTime
> 60*60) {
3565 COMPLAIN("TestingEstimatedDescriptorPropagationTime is insanely high.");
3568 if (options
->TestingTorNetwork
) {
3569 log_warn(LD_CONFIG
, "TestingTorNetwork is set. This will make your node "
3570 "almost unusable in the public Tor network, and is "
3571 "therefore only advised if you are building a "
3572 "testing Tor network!");
3580 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
3583 opt_streq(const char *s1
, const char *s2
)
3587 else if (s1
&& s2
&& !strcmp(s1
,s2
))
3593 /** Check if any of the previous options have changed but aren't allowed to. */
3595 options_transition_allowed(or_options_t
*old
, or_options_t
*new_val
,
3601 if (!opt_streq(old
->PidFile
, new_val
->PidFile
)) {
3602 *msg
= tor_strdup("PidFile is not allowed to change.");
3606 if (old
->RunAsDaemon
!= new_val
->RunAsDaemon
) {
3607 *msg
= tor_strdup("While Tor is running, changing RunAsDaemon "
3612 if (strcmp(old
->DataDirectory
,new_val
->DataDirectory
)!=0) {
3614 int r
= tor_snprintf(buf
, sizeof(buf
),
3615 "While Tor is running, changing DataDirectory "
3616 "(\"%s\"->\"%s\") is not allowed.",
3617 old
->DataDirectory
, new_val
->DataDirectory
);
3618 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
3622 if (!opt_streq(old
->User
, new_val
->User
)) {
3623 *msg
= tor_strdup("While Tor is running, changing User is not allowed.");
3627 if (!opt_streq(old
->Group
, new_val
->Group
)) {
3628 *msg
= tor_strdup("While Tor is running, changing Group is not allowed.");
3632 if (old
->HardwareAccel
!= new_val
->HardwareAccel
) {
3633 *msg
= tor_strdup("While Tor is running, changing HardwareAccel is "
3638 if (old
->TestingTorNetwork
!= new_val
->TestingTorNetwork
) {
3639 *msg
= tor_strdup("While Tor is running, changing TestingTorNetwork "
3647 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3648 * will require us to rotate the cpu and dns workers; else return 0. */
3650 options_transition_affects_workers(or_options_t
*old_options
,
3651 or_options_t
*new_options
)
3653 if (!opt_streq(old_options
->DataDirectory
, new_options
->DataDirectory
) ||
3654 old_options
->NumCpus
!= new_options
->NumCpus
||
3655 old_options
->ORPort
!= new_options
->ORPort
||
3656 old_options
->ServerDNSSearchDomains
!=
3657 new_options
->ServerDNSSearchDomains
||
3658 old_options
->SafeLogging
!= new_options
->SafeLogging
||
3659 old_options
->ClientOnly
!= new_options
->ClientOnly
||
3660 !config_lines_eq(old_options
->Logs
, new_options
->Logs
))
3663 /* Check whether log options match. */
3665 /* Nothing that changed matters. */
3669 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3670 * will require us to generate a new descriptor; else return 0. */
3672 options_transition_affects_descriptor(or_options_t
*old_options
,
3673 or_options_t
*new_options
)
3675 /* XXX We can be smarter here. If your DirPort isn't being
3676 * published and you just turned it off, no need to republish. If
3677 * you changed your bandwidthrate but maxadvertisedbandwidth still
3678 * trumps, no need to republish. Etc. */
3679 if (!opt_streq(old_options
->DataDirectory
, new_options
->DataDirectory
) ||
3680 !opt_streq(old_options
->Nickname
,new_options
->Nickname
) ||
3681 !opt_streq(old_options
->Address
,new_options
->Address
) ||
3682 !config_lines_eq(old_options
->ExitPolicy
,new_options
->ExitPolicy
) ||
3683 old_options
->ExitPolicyRejectPrivate
!=
3684 new_options
->ExitPolicyRejectPrivate
||
3685 old_options
->ORPort
!= new_options
->ORPort
||
3686 old_options
->DirPort
!= new_options
->DirPort
||
3687 old_options
->ClientOnly
!= new_options
->ClientOnly
||
3688 old_options
->NoPublish
!= new_options
->NoPublish
||
3689 old_options
->_PublishServerDescriptor
!=
3690 new_options
->_PublishServerDescriptor
||
3691 old_options
->BandwidthRate
!= new_options
->BandwidthRate
||
3692 old_options
->BandwidthBurst
!= new_options
->BandwidthBurst
||
3693 old_options
->MaxAdvertisedBandwidth
!=
3694 new_options
->MaxAdvertisedBandwidth
||
3695 !opt_streq(old_options
->ContactInfo
, new_options
->ContactInfo
) ||
3696 !opt_streq(old_options
->MyFamily
, new_options
->MyFamily
) ||
3697 !opt_streq(old_options
->AccountingStart
, new_options
->AccountingStart
) ||
3698 old_options
->AccountingMax
!= new_options
->AccountingMax
)
3705 /** Return the directory on windows where we expect to find our application
3708 get_windows_conf_root(void)
3710 static int is_set
= 0;
3711 static char path
[MAX_PATH
+1];
3720 /* Find X:\documents and settings\username\application data\ .
3721 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
3723 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL
, CSIDL_APPDATA
,
3725 GetCurrentDirectory(MAX_PATH
, path
);
3728 "I couldn't find your application data folder: are you "
3729 "running an ancient version of Windows 95? Defaulting to \"%s\"",
3733 /* Convert the path from an "ID List" (whatever that is!) to a path. */
3734 result
= SHGetPathFromIDList(idl
, path
);
3735 /* Now we need to free the */
3738 m
->lpVtbl
->Free(m
, idl
);
3739 m
->lpVtbl
->Release(m
);
3741 if (!SUCCEEDED(result
)) {
3744 strlcat(path
,"\\tor",MAX_PATH
);
3750 /** Return the default location for our torrc file. */
3752 get_default_conf_file(void)
3755 static char path
[MAX_PATH
+1];
3756 strlcpy(path
, get_windows_conf_root(), MAX_PATH
);
3757 strlcat(path
,"\\torrc",MAX_PATH
);
3760 return (CONFDIR
"/torrc");
3764 /** Verify whether lst is a string containing valid-looking comma-separated
3765 * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
3768 check_nickname_list(const char *lst
, const char *name
, char **msg
)
3775 sl
= smartlist_create();
3777 smartlist_split_string(sl
, lst
, ",",
3778 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
|SPLIT_STRIP_SPACE
, 0);
3780 SMARTLIST_FOREACH(sl
, const char *, s
,
3782 if (!is_legal_nickname_or_hexdigest(s
)) {
3784 int tmp
= tor_snprintf(buf
, sizeof(buf
),
3785 "Invalid nickname '%s' in %s line", s
, name
);
3786 *msg
= tor_strdup(tmp
>= 0 ? buf
: "internal error");
3791 SMARTLIST_FOREACH(sl
, char *, s
, tor_free(s
));
3796 /** Learn config file name from command line arguments, or use the default */
3798 find_torrc_filename(int argc
, char **argv
,
3799 int *using_default_torrc
, int *ignore_missing_torrc
)
3804 for (i
= 1; i
< argc
; ++i
) {
3805 if (i
< argc
-1 && !strcmp(argv
[i
],"-f")) {
3807 log(LOG_WARN
, LD_CONFIG
, "Duplicate -f options on command line.");
3811 /* XXX one day we might want to extend expand_filename to work
3812 * under Windows as well. */
3813 fname
= tor_strdup(argv
[i
+1]);
3815 fname
= expand_filename(argv
[i
+1]);
3817 *using_default_torrc
= 0;
3819 } else if (!strcmp(argv
[i
],"--ignore-missing-torrc")) {
3820 *ignore_missing_torrc
= 1;
3824 if (*using_default_torrc
) {
3825 /* didn't find one, try CONFDIR */
3826 const char *dflt
= get_default_conf_file();
3827 if (dflt
&& file_status(dflt
) == FN_FILE
) {
3828 fname
= tor_strdup(dflt
);
3832 fn
= expand_filename("~/.torrc");
3833 if (fn
&& file_status(fn
) == FN_FILE
) {
3837 fname
= tor_strdup(dflt
);
3840 fname
= tor_strdup(dflt
);
3847 /** Load torrc from disk, setting torrc_fname if successful */
3849 load_torrc_from_disk(int argc
, char **argv
)
3853 int using_default_torrc
= 1;
3854 int ignore_missing_torrc
= 0;
3856 fname
= find_torrc_filename(argc
, argv
,
3857 &using_default_torrc
, &ignore_missing_torrc
);
3859 log(LOG_DEBUG
, LD_CONFIG
, "Opening config file \"%s\"", fname
);
3861 tor_free(torrc_fname
);
3862 torrc_fname
= fname
;
3864 /* Open config file */
3865 if (file_status(fname
) != FN_FILE
||
3866 !(cf
= read_file_to_str(fname
,0,NULL
))) {
3867 if (using_default_torrc
== 1 || ignore_missing_torrc
) {
3868 log(LOG_NOTICE
, LD_CONFIG
, "Configuration file \"%s\" not present, "
3869 "using reasonable defaults.", fname
);
3870 tor_free(fname
); /* sets fname to NULL */
3872 cf
= tor_strdup("");
3874 log(LOG_WARN
, LD_CONFIG
,
3875 "Unable to open configuration file \"%s\".", fname
);
3887 /** Read a configuration file into <b>options</b>, finding the configuration
3888 * file location based on the command line. After loading the file
3889 * call options_init_from_string() to load the config.
3890 * Return 0 if success, -1 if failure. */
3892 options_init_from_torrc(int argc
, char **argv
)
3895 int i
, retval
, command
;
3896 static char **backup_argv
;
3897 static int backup_argc
;
3898 char *command_arg
= NULL
;
3901 if (argv
) { /* first time we're called. save commandline args */
3904 } else { /* we're reloading. need to clean up old options first. */
3908 if (argc
> 1 && (!strcmp(argv
[1], "-h") || !strcmp(argv
[1],"--help"))) {
3912 if (argc
> 1 && !strcmp(argv
[1], "--list-torrc-options")) {
3913 /* For documenting validating whether we've documented everything. */
3914 list_torrc_options();
3918 if (argc
> 1 && (!strcmp(argv
[1],"--version"))) {
3919 printf("Tor version %s.\n",get_version());
3920 if (argc
> 2 && (!strcmp(argv
[2],"--version"))) {
3921 print_svn_version();
3926 /* Go through command-line variables */
3927 if (!global_cmdline_options
) {
3928 /* Or we could redo the list every time we pass this place.
3929 * It does not really matter */
3930 if (config_get_commandlines(argc
, argv
, &global_cmdline_options
) < 0) {
3935 command
= CMD_RUN_TOR
;
3936 for (i
= 1; i
< argc
; ++i
) {
3937 if (!strcmp(argv
[i
],"--list-fingerprint")) {
3938 command
= CMD_LIST_FINGERPRINT
;
3939 } else if (!strcmp(argv
[i
],"--hash-password")) {
3940 command
= CMD_HASH_PASSWORD
;
3941 command_arg
= tor_strdup( (i
< argc
-1) ? argv
[i
+1] : "");
3943 } else if (!strcmp(argv
[i
],"--verify-config")) {
3944 command
= CMD_VERIFY_CONFIG
;
3948 if (command
== CMD_HASH_PASSWORD
) {
3949 cf
= tor_strdup("");
3951 cf
= load_torrc_from_disk(argc
, argv
);
3956 retval
= options_init_from_string(cf
, command
, command_arg
, &errmsg
);
3965 log(LOG_WARN
,LD_CONFIG
,"%s", errmsg
);
3971 /** Load the options from the configuration in <b>cf</b>, validate
3972 * them for consistency and take actions based on them.
3974 * Return 0 if success, negative on error:
3975 * * -1 for general errors.
3976 * * -2 for failure to parse/validate,
3977 * * -3 for transition not allowed
3978 * * -4 for error while setting the new options
3981 options_init_from_string(const char *cf
,
3982 int command
, const char *command_arg
,
3985 or_options_t
*oldoptions
, *newoptions
;
3988 setopt_err_t err
= SETOPT_ERR_MISC
;
3991 oldoptions
= global_options
; /* get_options unfortunately asserts if
3992 this is the first time we run*/
3994 newoptions
= tor_malloc_zero(sizeof(or_options_t
));
3995 newoptions
->_magic
= OR_OPTIONS_MAGIC
;
3996 options_init(newoptions
);
3997 newoptions
->command
= command
;
3998 newoptions
->command_arg
= command_arg
;
4000 /* get config lines, assign them */
4001 retval
= config_get_lines(cf
, &cl
);
4003 err
= SETOPT_ERR_PARSE
;
4006 retval
= config_assign(&options_format
, newoptions
, cl
, 0, 0, msg
);
4007 config_free_lines(cl
);
4009 err
= SETOPT_ERR_PARSE
;
4013 /* Go through command-line variables too */
4014 retval
= config_assign(&options_format
, newoptions
,
4015 global_cmdline_options
, 0, 0, msg
);
4017 err
= SETOPT_ERR_PARSE
;
4021 /* If this is a testing network configuration, change defaults
4022 * for a list of dependent config options, re-initialize newoptions
4023 * with the new defaults, and assign all options to it second time. */
4024 if (newoptions
->TestingTorNetwork
) {
4025 /* XXXX this is a bit of a kludge. perhaps there's a better way to do
4026 * this? We could, for example, make the parsing algorithm do two passes
4027 * over the configuration. If it finds any "suite" options like
4028 * TestingTorNetwork, it could change the defaults before its second pass.
4029 * Not urgent so long as this seems to work, but at any sign of trouble,
4030 * let's clean it up. -NM */
4032 /* Change defaults. */
4034 for (i
= 0; testing_tor_network_defaults
[i
].name
; ++i
) {
4035 config_var_t
*new_var
= &testing_tor_network_defaults
[i
];
4036 config_var_t
*old_var
=
4037 config_find_option(&options_format
, new_var
->name
);
4038 tor_assert(new_var
);
4039 tor_assert(old_var
);
4040 old_var
->initvalue
= new_var
->initvalue
;
4043 /* Clear newoptions and re-initialize them with new defaults. */
4044 config_free(&options_format
, newoptions
);
4045 newoptions
= tor_malloc_zero(sizeof(or_options_t
));
4046 newoptions
->_magic
= OR_OPTIONS_MAGIC
;
4047 options_init(newoptions
);
4048 newoptions
->command
= command
;
4049 newoptions
->command_arg
= command_arg
;
4051 /* Assign all options a second time. */
4052 retval
= config_get_lines(cf
, &cl
);
4054 err
= SETOPT_ERR_PARSE
;
4057 retval
= config_assign(&options_format
, newoptions
, cl
, 0, 0, msg
);
4058 config_free_lines(cl
);
4060 err
= SETOPT_ERR_PARSE
;
4063 retval
= config_assign(&options_format
, newoptions
,
4064 global_cmdline_options
, 0, 0, msg
);
4066 err
= SETOPT_ERR_PARSE
;
4071 /* Validate newoptions */
4072 if (options_validate(oldoptions
, newoptions
, 0, msg
) < 0) {
4073 err
= SETOPT_ERR_PARSE
; /*XXX make this a separate return value.*/
4077 if (options_transition_allowed(oldoptions
, newoptions
, msg
) < 0) {
4078 err
= SETOPT_ERR_TRANSITION
;
4082 if (set_options(newoptions
, msg
)) {
4083 err
= SETOPT_ERR_SETTING
;
4084 goto err
; /* frees and replaces old options */
4090 config_free(&options_format
, newoptions
);
4092 int len
= strlen(*msg
)+256;
4093 char *newmsg
= tor_malloc(len
);
4095 tor_snprintf(newmsg
, len
, "Failed to parse/validate config: %s", *msg
);
4102 /** Return the location for our configuration file.
4105 get_torrc_fname(void)
4110 return get_default_conf_file();
4113 /** Adjust the address map mased on the MapAddress elements in the
4114 * configuration <b>options</b>
4117 config_register_addressmaps(or_options_t
*options
)
4123 addressmap_clear_configured();
4124 elts
= smartlist_create();
4125 for (opt
= options
->AddressMap
; opt
; opt
= opt
->next
) {
4126 smartlist_split_string(elts
, opt
->value
, NULL
,
4127 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 2);
4128 if (smartlist_len(elts
) >= 2) {
4129 from
= smartlist_get(elts
,0);
4130 to
= smartlist_get(elts
,1);
4131 if (address_is_invalid_destination(to
, 1)) {
4133 "Skipping invalid argument '%s' to MapAddress", to
);
4135 addressmap_register(from
, tor_strdup(to
), 0, ADDRMAPSRC_TORRC
);
4136 if (smartlist_len(elts
)>2) {
4137 log_warn(LD_CONFIG
,"Ignoring extra arguments to MapAddress.");
4141 log_warn(LD_CONFIG
,"MapAddress '%s' has too few arguments. Ignoring.",
4144 SMARTLIST_FOREACH(elts
, char*, cp
, tor_free(cp
));
4145 smartlist_clear(elts
);
4147 smartlist_free(elts
);
4151 * Initialize the logs based on the configuration file.
4154 options_init_logs(or_options_t
*options
, int validate_only
)
4163 options
->RunAsDaemon
;
4167 elts
= smartlist_create();
4169 for (opt
= options
->Logs
; opt
; opt
= opt
->next
) {
4170 log_severity_list_t
*severity
;
4171 const char *cfg
= opt
->value
;
4172 severity
= tor_malloc_zero(sizeof(log_severity_list_t
));
4173 if (parse_log_severity_config(&cfg
, severity
) < 0) {
4174 log_warn(LD_CONFIG
, "Couldn't parse log levels in Log option 'Log %s'",
4176 ok
= 0; goto cleanup
;
4179 smartlist_split_string(elts
, cfg
, NULL
,
4180 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 2);
4182 if (smartlist_len(elts
) == 0)
4183 smartlist_add(elts
, tor_strdup("stdout"));
4185 if (smartlist_len(elts
) == 1 &&
4186 (!strcasecmp(smartlist_get(elts
,0), "stdout") ||
4187 !strcasecmp(smartlist_get(elts
,0), "stderr"))) {
4188 int err
= smartlist_len(elts
) &&
4189 !strcasecmp(smartlist_get(elts
,0), "stderr");
4190 if (!validate_only
) {
4193 "Can't log to %s with RunAsDaemon set; skipping stdout",
4194 err
?"stderr":"stdout");
4196 add_stream_log(severity
, err
?"<stderr>":"<stdout>",
4197 fileno(err
?stderr
:stdout
));
4202 if (smartlist_len(elts
) == 1 &&
4203 !strcasecmp(smartlist_get(elts
,0), "syslog")) {
4204 #ifdef HAVE_SYSLOG_H
4205 if (!validate_only
) {
4206 add_syslog_log(severity
);
4209 log_warn(LD_CONFIG
, "Syslog is not supported on this system. Sorry.");
4214 if (smartlist_len(elts
) == 2 &&
4215 !strcasecmp(smartlist_get(elts
,0), "file")) {
4216 if (!validate_only
) {
4217 if (add_file_log(severity
, smartlist_get(elts
, 1)) < 0) {
4218 log_warn(LD_CONFIG
, "Couldn't open file for 'Log %s': %s",
4219 opt
->value
, strerror(errno
));
4226 log_warn(LD_CONFIG
, "Bad syntax on file Log option 'Log %s'",
4228 ok
= 0; goto cleanup
;
4231 SMARTLIST_FOREACH(elts
, char*, cp
, tor_free(cp
));
4232 smartlist_clear(elts
);
4235 smartlist_free(elts
);
4240 /** Read the contents of a Bridge line from <b>line</b>. Return 0
4241 * if the line is well-formed, and -1 if it isn't. If
4242 * <b>validate_only</b> is 0, and the line is well-formed, then add
4243 * the bridge described in the line to our internal bridge list. */
4245 parse_bridge_line(const char *line
, int validate_only
)
4247 smartlist_t
*items
= NULL
;
4249 char *addrport
=NULL
, *fingerprint
=NULL
;
4252 char digest
[DIGEST_LEN
];
4254 items
= smartlist_create();
4255 smartlist_split_string(items
, line
, NULL
,
4256 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, -1);
4257 if (smartlist_len(items
) < 1) {
4258 log_warn(LD_CONFIG
, "Too few arguments to Bridge line.");
4261 addrport
= smartlist_get(items
, 0);
4262 smartlist_del_keeporder(items
, 0);
4263 if (tor_addr_port_parse(addrport
, &addr
, &port
)<0) {
4264 log_warn(LD_CONFIG
, "Error parsing Bridge address '%s'", addrport
);
4268 log_warn(LD_CONFIG
, "Missing port in Bridge address '%s'",addrport
);
4272 if (smartlist_len(items
)) {
4273 fingerprint
= smartlist_join_strings(items
, "", 0, NULL
);
4274 if (strlen(fingerprint
) != HEX_DIGEST_LEN
) {
4275 log_warn(LD_CONFIG
, "Key digest for Bridge is wrong length.");
4278 if (base16_decode(digest
, DIGEST_LEN
, fingerprint
, HEX_DIGEST_LEN
)<0) {
4279 log_warn(LD_CONFIG
, "Unable to decode Bridge key digest.");
4284 if (!validate_only
) {
4285 log_debug(LD_DIR
, "Bridge at %s:%d (%s)", fmt_addr(&addr
),
4287 fingerprint
? fingerprint
: "no key listed");
4288 bridge_add_from_config(&addr
, port
, fingerprint
? digest
: NULL
);
4298 SMARTLIST_FOREACH(items
, char*, s
, tor_free(s
));
4299 smartlist_free(items
);
4301 tor_free(fingerprint
);
4305 /** Read the contents of a DirServer line from <b>line</b>. If
4306 * <b>validate_only</b> is 0, and the line is well-formed, and it
4307 * shares any bits with <b>required_type</b> or <b>required_type</b>
4308 * is 0, then add the dirserver described in the line (minus whatever
4309 * bits it's missing) as a valid authority. Return 0 on success,
4310 * or -1 if the line isn't well-formed or if we can't add it. */
4312 parse_dir_server_line(const char *line
, authority_type_t required_type
,
4315 smartlist_t
*items
= NULL
;
4317 char *addrport
=NULL
, *address
=NULL
, *nickname
=NULL
, *fingerprint
=NULL
;
4318 uint16_t dir_port
= 0, or_port
= 0;
4319 char digest
[DIGEST_LEN
];
4320 char v3_digest
[DIGEST_LEN
];
4321 authority_type_t type
= V2_AUTHORITY
;
4322 int is_not_hidserv_authority
= 0, is_not_v2_authority
= 0;
4324 items
= smartlist_create();
4325 smartlist_split_string(items
, line
, NULL
,
4326 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, -1);
4327 if (smartlist_len(items
) < 1) {
4328 log_warn(LD_CONFIG
, "No arguments on DirServer line.");
4332 if (is_legal_nickname(smartlist_get(items
, 0))) {
4333 nickname
= smartlist_get(items
, 0);
4334 smartlist_del_keeporder(items
, 0);
4337 while (smartlist_len(items
)) {
4338 char *flag
= smartlist_get(items
, 0);
4339 if (TOR_ISDIGIT(flag
[0]))
4341 if (!strcasecmp(flag
, "v1")) {
4342 type
|= (V1_AUTHORITY
| HIDSERV_AUTHORITY
);
4343 } else if (!strcasecmp(flag
, "hs")) {
4344 type
|= HIDSERV_AUTHORITY
;
4345 } else if (!strcasecmp(flag
, "no-hs")) {
4346 is_not_hidserv_authority
= 1;
4347 } else if (!strcasecmp(flag
, "bridge")) {
4348 type
|= BRIDGE_AUTHORITY
;
4349 } else if (!strcasecmp(flag
, "no-v2")) {
4350 is_not_v2_authority
= 1;
4351 } else if (!strcasecmpstart(flag
, "orport=")) {
4353 char *portstring
= flag
+ strlen("orport=");
4354 or_port
= (uint16_t) tor_parse_long(portstring
, 10, 1, 65535, &ok
, NULL
);
4356 log_warn(LD_CONFIG
, "Invalid orport '%s' on DirServer line.",
4358 } else if (!strcasecmpstart(flag
, "v3ident=")) {
4359 char *idstr
= flag
+ strlen("v3ident=");
4360 if (strlen(idstr
) != HEX_DIGEST_LEN
||
4361 base16_decode(v3_digest
, DIGEST_LEN
, idstr
, HEX_DIGEST_LEN
)<0) {
4362 log_warn(LD_CONFIG
, "Bad v3 identity digest '%s' on DirServer line",
4365 type
|= V3_AUTHORITY
;
4368 log_warn(LD_CONFIG
, "Unrecognized flag '%s' on DirServer line",
4372 smartlist_del_keeporder(items
, 0);
4374 if (is_not_hidserv_authority
)
4375 type
&= ~HIDSERV_AUTHORITY
;
4376 if (is_not_v2_authority
)
4377 type
&= ~V2_AUTHORITY
;
4379 if (smartlist_len(items
) < 2) {
4380 log_warn(LD_CONFIG
, "Too few arguments to DirServer line.");
4383 addrport
= smartlist_get(items
, 0);
4384 smartlist_del_keeporder(items
, 0);
4385 if (parse_addr_port(LOG_WARN
, addrport
, &address
, NULL
, &dir_port
)<0) {
4386 log_warn(LD_CONFIG
, "Error parsing DirServer address '%s'", addrport
);
4390 log_warn(LD_CONFIG
, "Missing port in DirServer address '%s'",addrport
);
4394 fingerprint
= smartlist_join_strings(items
, "", 0, NULL
);
4395 if (strlen(fingerprint
) != HEX_DIGEST_LEN
) {
4396 log_warn(LD_CONFIG
, "Key digest for DirServer is wrong length %d.",
4397 (int)strlen(fingerprint
));
4400 if (!strcmp(fingerprint
, "E623F7625FBE0C87820F11EC5F6D5377ED816294")) {
4401 /* a known bad fingerprint. refuse to use it. We can remove this
4402 * clause once Tor 0.1.2.17 is obsolete. */
4403 log_warn(LD_CONFIG
, "Dangerous dirserver line. To correct, erase your "
4404 "torrc file (%s), or reinstall Tor and use the default torrc.",
4408 if (base16_decode(digest
, DIGEST_LEN
, fingerprint
, HEX_DIGEST_LEN
)<0) {
4409 log_warn(LD_CONFIG
, "Unable to decode DirServer key digest.");
4413 if (!validate_only
&& (!required_type
|| required_type
& type
)) {
4415 type
&= required_type
; /* pare down what we think of them as an
4417 log_debug(LD_DIR
, "Trusted %d dirserver at %s:%d (%s)", (int)type
,
4418 address
, (int)dir_port
, (char*)smartlist_get(items
,0));
4419 if (!add_trusted_dir_server(nickname
, address
, dir_port
, or_port
,
4420 digest
, v3_digest
, type
))
4431 SMARTLIST_FOREACH(items
, char*, s
, tor_free(s
));
4432 smartlist_free(items
);
4436 tor_free(fingerprint
);
4440 /** Adjust the value of options->DataDirectory, or fill it in if it's
4441 * absent. Return 0 on success, -1 on failure. */
4443 normalize_data_directory(or_options_t
*options
)
4447 if (options
->DataDirectory
)
4448 return 0; /* all set */
4449 p
= tor_malloc(MAX_PATH
);
4450 strlcpy(p
,get_windows_conf_root(),MAX_PATH
);
4451 options
->DataDirectory
= p
;
4454 const char *d
= options
->DataDirectory
;
4458 if (strncmp(d
,"~/",2) == 0) {
4459 char *fn
= expand_filename(d
);
4461 log_warn(LD_CONFIG
,"Failed to expand filename \"%s\".", d
);
4464 if (!options
->DataDirectory
&& !strcmp(fn
,"/.tor")) {
4465 /* If our homedir is /, we probably don't want to use it. */
4466 /* Default to LOCALSTATEDIR/tor which is probably closer to what we
4469 "Default DataDirectory is \"~/.tor\". This expands to "
4470 "\"%s\", which is probably not what you want. Using "
4471 "\"%s"PATH_SEPARATOR
"tor\" instead
", fn, LOCALSTATEDIR);
4473 fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor
");
4475 tor_free(options->DataDirectory);
4476 options->DataDirectory = fn;
4482 /** Check and normalize the value of options->DataDirectory; return 0 if it
4483 * sane, -1 otherwise. */
4485 validate_data_directory(or_options_t *options)
4487 if (normalize_data_directory(options) < 0)
4489 tor_assert(options->DataDirectory);
4490 if (strlen(options->DataDirectory) > (512-128)) {
4491 log_warn(LD_CONFIG, "DataDirectory is too
long.");
4497 /** This string must remain the same forevermore. It is how we
4498 * recognize that the torrc file doesn't need to be backed up. */
4499 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
4500 "if you edit it, comments will not be preserved"
4501 /** This string can change; it tries to give the reader an idea
4502 * that editing this file by hand is not a good plan. */
4503 #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
4504 "to torrc.orig.1 or similar, and Tor will ignore it"
4506 /** Save a configuration file for the configuration in <b>options</b>
4507 * into the file <b>fname</b>. If the file already exists, and
4508 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
4509 * replace it. Return 0 on success, -1 on failure. */
4511 write_configuration_file(const char *fname, or_options_t *options)
4513 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
4514 int rename_old = 0, r;
4519 switch (file_status(fname)) {
4521 old_val = read_file_to_str(fname, 0, NULL);
4522 if (strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
4533 "Config file \"%s\" is not a file? Failing.", fname);
4537 if (!(new_conf = options_dump(options, 1))) {
4538 log_warn(LD_BUG, "Couldn't get configuration string");
4542 len = strlen(new_conf)+256;
4543 new_val = tor_malloc(len);
4544 tor_snprintf(new_val, len, "%s\n%s\n\n%s",
4545 GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
4549 size_t fn_tmp_len = strlen(fname)+32;
4551 tor_assert(fn_tmp_len > strlen(fname)); /*check for overflow*/
4552 fn_tmp = tor_malloc(fn_tmp_len);
4554 if (tor_snprintf(fn_tmp, fn_tmp_len, "%s.orig.%d", fname, i)<0) {
4555 log_warn(LD_BUG, "tor_snprintf failed inexplicably");
4559 if (file_status(fn_tmp) == FN_NOENT)
4563 log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
4564 if (rename(fname, fn_tmp) < 0) {
4566 "Couldn't rename configuration file \"%s\" to \"%s\": %s",
4567 fname, fn_tmp, strerror(errno));
4574 if (write_str_to_file(fname, new_val, 0) < 0)
4588 * Save the current configuration file value to disk. Return 0 on
4589 * success, -1 on failure.
4592 options_save_current(void)
4595 /* This fails if we can't write to our configuration file.
4597 * If we try falling back to datadirectory or something, we have a better
4598 * chance of saving the configuration, but a better chance of doing
4599 * something the user never expected. Let's just warn instead. */
4600 return write_configuration_file(torrc_fname, get_options());
4602 return write_configuration_file(get_default_conf_file(), get_options());
4605 /** Mapping from a unit name to a multiplier for converting that unit into a
4607 struct unit_table_t {
4609 uint64_t multiplier;
4612 static struct unit_table_t memory_units[] = {
4619 { "kbytes", 1<<10 },
4620 { "kilobyte", 1<<10 },
4621 { "kilobytes", 1<<10 },
4625 { "mbytes", 1<<20 },
4626 { "megabyte", 1<<20 },
4627 { "megabytes", 1<<20 },
4630 { "gbytes", 1<<30 },
4631 { "gigabyte", 1<<30 },
4632 { "gigabytes", 1<<30 },
4633 { "tb", U64_LITERAL(1)<<40 },
4634 { "terabyte", U64_LITERAL(1)<<40 },
4635 { "terabytes", U64_LITERAL(1)<<40 },
4639 static struct unit_table_t time_units[] = {
4647 { "day", 24*60*60 },
4648 { "days", 24*60*60 },
4649 { "week", 7*24*60*60 },
4650 { "weeks", 7*24*60*60 },
4654 /** Parse a string <b>val</b> containing a number, zero or more
4655 * spaces, and an optional unit string. If the unit appears in the
4656 * table <b>u</b>, then multiply the number by the unit multiplier.
4657 * On success, set *<b>ok</b> to 1 and return this product.
4658 * Otherwise, set *<b>ok</b> to 0.
4661 config_parse_units(const char *val, struct unit_table_t *u, int *ok)
4668 v = tor_parse_uint64(val, 10, 0, UINT64_MAX, ok, &cp);
4675 while (TOR_ISSPACE(*cp))
4677 for ( ;u->unit;++u) {
4678 if (!strcasecmp(u->unit, cp)) {
4684 log_warn(LD_CONFIG, "Unknown unit '%s'.", cp);
4689 /** Parse a string in the format "number unit", where unit is a unit of
4690 * information (byte, KB, M, etc). On success, set *<b>ok</b> to true
4691 * and return the number of bytes specified. Otherwise, set
4692 * *<b>ok</b> to false and return 0. */
4694 config_parse_memunit(const char *s, int *ok)
4696 return config_parse_units(s, memory_units, ok);
4699 /** Parse a string in the format "number unit", where unit is a unit of time.
4700 * On success, set *<b>ok</b> to true and return the number of seconds in
4701 * the provided interval. Otherwise, set *<b>ok</b> to 0 and return -1.
4704 config_parse_interval(const char *s, int *ok)
4707 r = config_parse_units(s, time_units, ok);
4711 log_warn(LD_CONFIG, "Interval '%s' is too long", s);
4719 * Initialize the libevent library.
4724 configure_libevent_logging();
4725 /* If the kernel complains that some method (say, epoll) doesn't
4726 * exist, we don't care about it, since libevent will cope.
4728 suppress_libevent_log_msg("Function not implemented");
4730 if (decode_libevent_version() < LE_11B) {
4731 setenv("EVENT_NOKQUEUE","1",1);
4735 suppress_libevent_log_msg(NULL);
4736 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
4737 /* Making this a NOTICE for now so we can link bugs to a libevent versions
4738 * or methods better. */
4739 log(LOG_NOTICE, LD_GENERAL,
4740 "Initialized libevent version %s using method %s. Good.",
4741 event_get_version(), event_get_method());
4742 check_libevent_version(event_get_method(), get_options()->ORPort != 0);
4744 log(LOG_NOTICE, LD_GENERAL,
4745 "Initialized old libevent (version 1.0b or earlier).");
4746 log(LOG_WARN, LD_GENERAL,
4747 "You have a *VERY* old version of libevent. It is likely to be buggy; "
4748 "please build Tor with a more recent version.");
4752 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
4753 /** Table mapping return value of event_get_version() to le_version_t. */
4754 static const struct {
4755 const char *name; le_version_t version;
4756 } le_version_table[] = {
4757 /* earlier versions don't have get_version. */
4774 /** Return the le_version_t for the current version of libevent. If the
4775 * version is very new, return LE_OTHER. If the version is so old that it
4776 * doesn't support event_get_version(), return LE_OLD. */
4778 decode_libevent_version(void)
4780 const char *v = event_get_version();
4782 for (i=0; le_version_table[i].name; ++i) {
4783 if (!strcmp(le_version_table[i].name, v)) {
4784 return le_version_table[i].version;
4791 * Compare the given libevent method and version to a list of versions
4792 * which are known not to work. Warn the user as appropriate.
4795 check_libevent_version(const char *m, int server)
4797 int buggy = 0, iffy = 0, slow = 0, thread_unsafe = 0;
4798 le_version_t version;
4799 const char *v = event_get_version();
4800 const char *badness = NULL;
4801 const char *sad_os = "";
4803 version = decode_libevent_version();
4805 /* XXX Would it be worthwhile disabling the methods that we know
4806 * are buggy, rather than just warning about them and then proceeding
4807 * to use them? If so, we should probably not wrap this whole thing
4808 * in HAVE_EVENT_GET_VERSION and HAVE_EVENT_GET_METHOD. -RD */
4809 /* XXXX The problem is that it's not trivial to get libevent to change it's
4810 * method once it's initialized, and it's not trivial to tell what method it
4811 * will use without initializing it. I guess we could preemptively disable
4812 * buggy libevent modes based on the version _before_ initializing it,
4813 * though, but then there's no good way (afaict) to warn "I would have used
4814 * kqueue
, but instead I
'm using select." -NM */
4815 if (!strcmp(m, "kqueue")) {
4816 if (version < LE_11B)
4818 } else if (!strcmp(m, "epoll")) {
4819 if (version < LE_11)
4821 } else if (!strcmp(m, "poll")) {
4822 if (version < LE_10E)
4824 else if (version < LE_11)
4826 } else if (!strcmp(m, "select")) {
4827 if (version < LE_11)
4829 } else if (!strcmp(m, "win32")) {
4830 if (version < LE_11B)
4834 /* Libevent versions before 1.3b do very badly on operating systems with
4835 * user-space threading implementations. */
4836 #if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__)
4837 if (server && version < LE_13B) {
4839 sad_os = "BSD variants";
4841 #elif defined(__APPLE__) || defined(__darwin__)
4842 if (server && version < LE_13B) {
4844 sad_os = "Mac OS X";
4848 if (thread_unsafe) {
4849 log(LOG_WARN, LD_GENERAL,
4850 "Libevent version %s often crashes when running a Tor server with %s. "
4851 "Please use the latest version of libevent (1.3b or later)",v,sad_os);
4854 log(LOG_WARN, LD_GENERAL,
4855 "There are serious bugs in using %s with libevent %s. "
4856 "Please use the latest version of libevent.", m, v);
4859 log(LOG_WARN, LD_GENERAL,
4860 "There are minor bugs in using %s with libevent %s. "
4861 "You may want to use the latest version of libevent.", m, v);
4863 } else if (slow && server) {
4864 log(LOG_WARN, LD_GENERAL,
4865 "libevent %s can be very slow with %s. "
4866 "When running a server, please use the latest version of libevent.",
4871 control_event_general_status(LOG_WARN,
4872 "BAD_LIBEVENT VERSION=%s METHOD=%s BADNESS=%s RECOVERED=NO",
4879 decode_libevent_version(void)
4885 /** Return the persistent state struct for this Tor. */
4889 tor_assert(global_state);
4890 return global_state;
4893 /** Return a newly allocated string holding a filename relative to the data
4894 * directory. If <b>sub1</b> is present, it is the first path component after
4895 * the data directory. If <b>sub2</b> is also present, it is the second path
4896 * component after the data directory. If <b>suffix</b> is present, it
4897 * is appended to the filename.
4900 * get_datadir_fname2_suffix("a", NULL, NULL) -> $DATADIR/a
4901 * get_datadir_fname2_suffix("a", NULL, ".tmp") -> $DATADIR/a.tmp
4902 * get_datadir_fname2_suffix("a", "b", ".tmp") -> $DATADIR/a/b/.tmp
4903 * get_datadir_fname2_suffix("a", "b", NULL) -> $DATADIR/a/b
4905 * Note: Consider using the get_datadir_fname* macros in or.h.
4908 options_get_datadir_fname2_suffix(or_options_t *options,
4909 const char *sub1, const char *sub2,
4914 tor_assert(options);
4915 tor_assert(options->DataDirectory);
4916 tor_assert(sub1 || !sub2); /* If sub2 is present, sub1 must be present. */
4917 len = strlen(options->DataDirectory);
4919 len += strlen(sub1)+1;
4921 len += strlen(sub2)+1;
4924 len += strlen(suffix);
4926 fname = tor_malloc(len);
4929 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s",
4930 options->DataDirectory, sub1, sub2);
4932 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s",
4933 options->DataDirectory, sub1);
4936 strlcpy(fname, options->DataDirectory, len);
4939 strlcat(fname, suffix, len);
4943 /** Return 0 if every setting in <b>state</b> is reasonable, and a
4944 * permissible transition from <b>old_state</b>. Else warn and return -1.
4945 * Should have no side effects, except for normalizing the contents of
4948 /* XXX from_setconf is here because of bug 238 */
4950 or_state_validate(or_state_t *old_state, or_state_t *state,
4951 int from_setconf, char **msg)
4953 /* We don't use these
; only options
do. Still
, we need to match that
4955 (void) from_setconf
;
4958 if (entry_guards_parse_state(state
, 0, msg
)<0)
4964 /** Replace the current persistent state with <b>new_state</b> */
4966 or_state_set(or_state_t
*new_state
)
4969 tor_assert(new_state
);
4971 config_free(&state_format
, global_state
);
4972 global_state
= new_state
;
4973 if (entry_guards_parse_state(global_state
, 1, &err
)<0) {
4974 log_warn(LD_GENERAL
,"%s",err
);
4977 if (rep_hist_load_state(global_state
, &err
)<0) {
4978 log_warn(LD_GENERAL
,"Unparseable bandwidth history state: %s",err
);
4983 /** Reload the persistent state from disk, generating a new state as needed.
4984 * Return 0 on success, less than 0 on failure.
4989 or_state_t
*new_state
= NULL
;
4990 char *contents
= NULL
, *fname
;
4991 char *errmsg
= NULL
;
4992 int r
= -1, badstate
= 0;
4994 fname
= get_datadir_fname("state");
4995 switch (file_status(fname
)) {
4997 if (!(contents
= read_file_to_str(fname
, 0, NULL
))) {
4998 log_warn(LD_FS
, "Unable to read state file \"%s\"", fname
);
5007 log_warn(LD_GENERAL
,"State file \"%s\" is not a file? Failing.", fname
);
5010 new_state
= tor_malloc_zero(sizeof(or_state_t
));
5011 new_state
->_magic
= OR_STATE_MAGIC
;
5012 config_init(&state_format
, new_state
);
5014 config_line_t
*lines
=NULL
;
5016 if (config_get_lines(contents
, &lines
)<0)
5018 assign_retval
= config_assign(&state_format
, new_state
,
5019 lines
, 0, 0, &errmsg
);
5020 config_free_lines(lines
);
5021 if (assign_retval
<0)
5024 log_warn(LD_GENERAL
, "%s", errmsg
);
5029 if (!badstate
&& or_state_validate(NULL
, new_state
, 1, &errmsg
) < 0)
5033 log_warn(LD_GENERAL
, "%s", errmsg
);
5037 if (badstate
&& !contents
) {
5038 log_warn(LD_BUG
, "Uh oh. We couldn't even validate our own default state."
5039 " This is a bug in Tor.");
5041 } else if (badstate
&& contents
) {
5043 file_status_t status
;
5044 size_t len
= strlen(fname
)+16;
5045 char *fname2
= tor_malloc(len
);
5046 for (i
= 0; i
< 100; ++i
) {
5047 tor_snprintf(fname2
, len
, "%s.%d", fname
, i
);
5048 status
= file_status(fname2
);
5049 if (status
== FN_NOENT
)
5053 log_warn(LD_BUG
, "Unable to parse state in \"%s\"; too many saved bad "
5054 "state files to move aside. Discarding the old state file.",
5058 log_warn(LD_BUG
, "Unable to parse state in \"%s\". Moving it aside "
5059 "to \"%s\". This could be a bug in Tor; please tell "
5060 "the developers.", fname
, fname2
);
5061 if (rename(fname
, fname2
) < 0) {
5062 log_warn(LD_BUG
, "Weirdly, I couldn't even move the state aside. The "
5063 "OS gave an error of %s", strerror(errno
));
5068 config_free(&state_format
, new_state
);
5070 new_state
= tor_malloc_zero(sizeof(or_state_t
));
5071 new_state
->_magic
= OR_STATE_MAGIC
;
5072 config_init(&state_format
, new_state
);
5073 } else if (contents
) {
5074 log_info(LD_GENERAL
, "Loaded state from \"%s\"", fname
);
5076 log_info(LD_GENERAL
, "Initialized state");
5078 or_state_set(new_state
);
5081 global_state
->next_write
= 0;
5082 or_state_save(time(NULL
));
5090 config_free(&state_format
, new_state
);
5095 /** Write the persistent state to disk. Return 0 for success, <0 on failure. */
5097 or_state_save(time_t now
)
5099 char *state
, *contents
;
5100 char tbuf
[ISO_TIME_LEN
+1];
5104 tor_assert(global_state
);
5106 if (global_state
->next_write
> now
)
5109 /* Call everything else that might dirty the state even more, in order
5110 * to avoid redundant writes. */
5111 entry_guards_update_state(global_state
);
5112 rep_hist_update_state(global_state
);
5113 if (accounting_is_enabled(get_options()))
5114 accounting_run_housekeeping(now
);
5116 global_state
->LastWritten
= time(NULL
);
5117 tor_free(global_state
->TorVersion
);
5118 len
= strlen(get_version())+8;
5119 global_state
->TorVersion
= tor_malloc(len
);
5120 tor_snprintf(global_state
->TorVersion
, len
, "Tor %s", get_version());
5122 state
= config_dump(&state_format
, global_state
, 1, 0);
5123 len
= strlen(state
)+256;
5124 contents
= tor_malloc(len
);
5125 format_local_iso_time(tbuf
, time(NULL
));
5126 tor_snprintf(contents
, len
,
5127 "# Tor state file last generated on %s local time\n"
5128 "# Other times below are in GMT\n"
5129 "# You *do not* need to edit this file.\n\n%s",
5132 fname
= get_datadir_fname("state");
5133 if (write_str_to_file(fname
, contents
, 0)<0) {
5134 log_warn(LD_FS
, "Unable to write state to file \"%s\"", fname
);
5139 log_info(LD_GENERAL
, "Saved state to \"%s\"", fname
);
5143 global_state
->next_write
= TIME_MAX
;
5147 /** Given a file name check to see whether the file exists but has not been
5148 * modified for a very long time. If so, remove it. */
5150 remove_file_if_very_old(const char *fname
, time_t now
)
5152 #define VERY_OLD_FILE_AGE (28*24*60*60)
5155 if (stat(fname
, &st
)==0 && st
.st_mtime
< now
-VERY_OLD_FILE_AGE
) {
5156 char buf
[ISO_TIME_LEN
+1];
5157 format_local_iso_time(buf
, st
.st_mtime
);
5158 log_notice(LD_GENERAL
, "Obsolete file %s hasn't been modified since %s. "
5159 "Removing it.", fname
, buf
);
5164 /** Helper to implement GETINFO functions about configuration variables (not
5165 * their values). Given a "config/names" question, set *<b>answer</b> to a
5166 * new string describing the supported configuration variables and their
5169 getinfo_helper_config(control_connection_t
*conn
,
5170 const char *question
, char **answer
)
5173 if (!strcmp(question
, "config/names")) {
5174 smartlist_t
*sl
= smartlist_create();
5176 for (i
= 0; _option_vars
[i
].name
; ++i
) {
5177 config_var_t
*var
= &_option_vars
[i
];
5178 const char *type
, *desc
;
5181 desc
= config_find_description(&options_format
, var
->name
);
5182 switch (var
->type
) {
5183 case CONFIG_TYPE_STRING
: type
= "String"; break;
5184 case CONFIG_TYPE_FILENAME
: type
= "Filename"; break;
5185 case CONFIG_TYPE_UINT
: type
= "Integer"; break;
5186 case CONFIG_TYPE_INTERVAL
: type
= "TimeInterval"; break;
5187 case CONFIG_TYPE_MEMUNIT
: type
= "DataSize"; break;
5188 case CONFIG_TYPE_DOUBLE
: type
= "Float"; break;
5189 case CONFIG_TYPE_BOOL
: type
= "Boolean"; break;
5190 case CONFIG_TYPE_ISOTIME
: type
= "Time"; break;
5191 case CONFIG_TYPE_ROUTERSET
: type
= "RouterList"; break;
5192 case CONFIG_TYPE_CSV
: type
= "CommaList"; break;
5193 case CONFIG_TYPE_LINELIST
: type
= "LineList"; break;
5194 case CONFIG_TYPE_LINELIST_S
: type
= "Dependant"; break;
5195 case CONFIG_TYPE_LINELIST_V
: type
= "Virtual"; break;
5197 case CONFIG_TYPE_OBSOLETE
:
5202 len
= strlen(var
->name
)+strlen(type
)+16;
5204 len
+= strlen(desc
);
5205 line
= tor_malloc(len
);
5207 tor_snprintf(line
, len
, "%s %s %s\n",var
->name
,type
,desc
);
5209 tor_snprintf(line
, len
, "%s %s\n",var
->name
,type
);
5210 smartlist_add(sl
, line
);
5212 *answer
= smartlist_join_strings(sl
, "", 0, NULL
);
5213 SMARTLIST_FOREACH(sl
, char *, c
, tor_free(c
));
5223 extern const char address_c_id
[];
5224 extern const char aes_c_id
[];
5225 extern const char compat_c_id
[];
5226 extern const char container_c_id
[];
5227 extern const char crypto_c_id
[];
5228 extern const char log_c_id
[];
5229 extern const char torgzip_c_id
[];
5230 extern const char tortls_c_id
[];
5231 extern const char util_c_id
[];
5233 extern const char buffers_c_id
[];
5234 extern const char circuitbuild_c_id
[];
5235 extern const char circuitlist_c_id
[];
5236 extern const char circuituse_c_id
[];
5237 extern const char command_c_id
[];
5238 // extern const char config_c_id[];
5239 extern const char connection_c_id
[];
5240 extern const char connection_edge_c_id
[];
5241 extern const char connection_or_c_id
[];
5242 extern const char control_c_id
[];
5243 extern const char cpuworker_c_id
[];
5244 extern const char directory_c_id
[];
5245 extern const char dirserv_c_id
[];
5246 extern const char dns_c_id
[];
5247 extern const char hibernate_c_id
[];
5248 extern const char main_c_id
[];
5250 extern const char ntmain_c_id
[];
5252 extern const char onion_c_id
[];
5253 extern const char policies_c_id
[];
5254 extern const char relay_c_id
[];
5255 extern const char rendclient_c_id
[];
5256 extern const char rendcommon_c_id
[];
5257 extern const char rendmid_c_id
[];
5258 extern const char rendservice_c_id
[];
5259 extern const char rephist_c_id
[];
5260 extern const char router_c_id
[];
5261 extern const char routerlist_c_id
[];
5262 extern const char routerparse_c_id
[];
5264 /** Dump the version of every file to the log. */
5266 print_svn_version(void)
5271 puts(CONTAINER_H_ID
);
5283 puts(container_c_id
);
5292 puts(circuitbuild_c_id
);
5293 puts(circuitlist_c_id
);
5294 puts(circuituse_c_id
);
5297 puts(connection_c_id
);
5298 puts(connection_edge_c_id
);
5299 puts(connection_or_c_id
);
5301 puts(cpuworker_c_id
);
5302 puts(directory_c_id
);
5305 puts(hibernate_c_id
);
5311 puts(policies_c_id
);
5313 puts(rendclient_c_id
);
5314 puts(rendcommon_c_id
);
5316 puts(rendservice_c_id
);
5319 puts(routerlist_c_id
);
5320 puts(routerparse_c_id
);