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_UINT
, /**< A non-negative integer less than MAX_INT */
26 CONFIG_TYPE_INTERVAL
, /**< A number of seconds, with optional units*/
27 CONFIG_TYPE_MEMUNIT
, /**< A number of bytes, with optional units*/
28 CONFIG_TYPE_DOUBLE
, /**< A floating-point value */
29 CONFIG_TYPE_BOOL
, /**< A boolean value, expressed as 0 or 1. */
30 CONFIG_TYPE_ISOTIME
, /**< An ISO-formated time relative to GMT. */
31 CONFIG_TYPE_CSV
, /**< A list of strings, separated by commas and
32 * optional whitespace. */
33 CONFIG_TYPE_LINELIST
, /**< Uninterpreted config lines */
34 CONFIG_TYPE_LINELIST_S
, /**< Uninterpreted, context-sensitive config lines,
35 * mixed with other keywords. */
36 CONFIG_TYPE_LINELIST_V
, /**< Catch-all "virtual" option to summarize
37 * context-sensitive config lines when fetching.
39 CONFIG_TYPE_OBSOLETE
, /**< Obsolete (ignored) option. */
42 /** An abbreviation for a configuration option allowed on the command line. */
43 typedef struct config_abbrev_t
{
44 const char *abbreviated
;
50 /* Handy macro for declaring "In the config file or on the command line,
51 * you can abbreviate <b>tok</b>s as <b>tok</b>". */
52 #define PLURAL(tok) { #tok, #tok "s", 0, 0 }
54 /* A list of command-line abbreviations. */
55 static config_abbrev_t _option_abbrevs
[] = {
60 PLURAL(LongLivedPort
),
61 PLURAL(HiddenServiceNode
),
62 PLURAL(HiddenServiceExcludeNode
),
65 PLURAL(RendExcludeNode
),
66 PLURAL(StrictEntryNode
),
67 PLURAL(StrictExitNode
),
69 { "AllowUnverifiedNodes", "AllowInvalidNodes", 0, 0},
70 { "AutomapHostSuffixes", "AutomapHostsSuffixes", 0, 0},
71 { "AutomapHostOnResolve", "AutomapHostsOnResolve", 0, 0},
72 { "BandwidthRateBytes", "BandwidthRate", 0, 0},
73 { "BandwidthBurstBytes", "BandwidthBurst", 0, 0},
74 { "DirFetchPostPeriod", "StatusFetchPeriod", 0, 0},
75 { "MaxConn", "ConnLimit", 0, 1},
76 { "ORBindAddress", "ORListenAddress", 0, 0},
77 { "DirBindAddress", "DirListenAddress", 0, 0},
78 { "SocksBindAddress", "SocksListenAddress", 0, 0},
79 { "UseHelperNodes", "UseEntryGuards", 0, 0},
80 { "NumHelperNodes", "NumEntryGuards", 0, 0},
81 { "UseEntryNodes", "UseEntryGuards", 0, 0},
82 { "NumEntryNodes", "NumEntryGuards", 0, 0},
83 { "ResolvConf", "ServerDNSResolvConfFile", 0, 1},
84 { "SearchDomains", "ServerDNSSearchDomains", 0, 1},
85 { "PreferTunnelledDirConns", "PreferTunneledDirConns", 0, 0},
86 { "BridgeAuthoritativeDirectory", "BridgeAuthoritativeDir", 0, 0},
87 { "HashedControlPassword", "__HashedControlSessionPassword", 1, 0},
90 /* A list of state-file abbreviations, for compatibility. */
91 static config_abbrev_t _state_abbrevs
[] = {
92 { "AccountingBytesReadInterval", "AccountingBytesReadInInterval", 0, 0 },
93 { "HelperNode", "EntryGuard", 0, 0 },
94 { "HelperNodeDownSince", "EntryGuardDownSince", 0, 0 },
95 { "HelperNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
96 { "EntryNode", "EntryGuard", 0, 0 },
97 { "EntryNodeDownSince", "EntryGuardDownSince", 0, 0 },
98 { "EntryNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
103 /** A variable allowed in the configuration file or on the command line. */
104 typedef struct config_var_t
{
105 const char *name
; /**< The full keyword (case insensitive). */
106 config_type_t type
; /**< How to interpret the type and turn it into a
108 off_t var_offset
; /**< Offset of the corresponding member of or_options_t. */
109 const char *initvalue
; /**< String (or null) describing initial value. */
112 /** An entry for config_vars: "The option <b>name</b> has type
113 * CONFIG_TYPE_<b>conftype</b>, and corresponds to
114 * or_options_t.<b>member</b>"
116 #define VAR(name,conftype,member,initvalue) \
117 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_options_t, member), \
119 /** As VAR, but the option name and member name are the same. */
120 #define V(member,conftype,initvalue) \
121 VAR(#member, conftype, member, initvalue)
122 /** An entry for config_vars: "The option <b>name</b> is obsolete." */
123 #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL }
125 /** Array of configuration options. Until we disallow nonstandard
126 * abbreviations, order is significant, since the first matching option will
129 static config_var_t _option_vars
[] = {
130 OBSOLETE("AccountingMaxKB"),
131 V(AccountingMax
, MEMUNIT
, "0 bytes"),
132 V(AccountingStart
, STRING
, NULL
),
133 V(Address
, STRING
, NULL
),
134 V(AllowInvalidNodes
, CSV
, "middle,rendezvous"),
135 V(AllowNonRFC953Hostnames
, BOOL
, "0"),
136 V(AlternateBridgeAuthority
, LINELIST
, NULL
),
137 V(AlternateDirAuthority
, LINELIST
, NULL
),
138 V(AlternateHSAuthority
, LINELIST
, NULL
),
139 V(AssumeReachable
, BOOL
, "0"),
140 V(AuthDirBadDir
, LINELIST
, NULL
),
141 V(AuthDirBadExit
, LINELIST
, NULL
),
142 V(AuthDirInvalid
, LINELIST
, NULL
),
143 V(AuthDirReject
, LINELIST
, NULL
),
144 V(AuthDirRejectUnlisted
, BOOL
, "0"),
145 V(AuthDirListBadDirs
, BOOL
, "0"),
146 V(AuthDirListBadExits
, BOOL
, "0"),
147 V(AuthDirMaxServersPerAddr
, UINT
, "2"),
148 V(AuthDirMaxServersPerAuthAddr
,UINT
, "5"),
149 VAR("AuthoritativeDirectory", BOOL
, AuthoritativeDir
, "0"),
150 V(AutomapHostsOnResolve
, BOOL
, "0"),
151 V(AutomapHostsSuffixes
, CSV
, ".onion,.exit"),
152 V(AvoidDiskWrites
, BOOL
, "0"),
153 V(BandwidthBurst
, MEMUNIT
, "10 MB"),
154 V(BandwidthRate
, MEMUNIT
, "5 MB"),
155 V(BridgeAuthoritativeDir
, BOOL
, "0"),
156 VAR("Bridge", LINELIST
, Bridges
, NULL
),
157 V(BridgePassword
, STRING
, NULL
),
158 V(BridgeRecordUsageByCountry
, BOOL
, "1"),
159 V(BridgeRelay
, BOOL
, "0"),
160 V(CircuitBuildTimeout
, INTERVAL
, "1 minute"),
161 V(CircuitIdleTimeout
, INTERVAL
, "1 hour"),
162 V(ClientDNSRejectInternalAddresses
, BOOL
,"1"),
163 V(ClientOnly
, BOOL
, "0"),
164 V(ConnLimit
, UINT
, "1000"),
165 V(ConstrainedSockets
, BOOL
, "0"),
166 V(ConstrainedSockSize
, MEMUNIT
, "8192"),
167 V(ContactInfo
, STRING
, NULL
),
168 V(ControlListenAddress
, LINELIST
, NULL
),
169 V(ControlPort
, UINT
, "0"),
170 V(ControlSocket
, LINELIST
, NULL
),
171 V(CookieAuthentication
, BOOL
, "0"),
172 V(CookieAuthFileGroupReadable
, BOOL
, "0"),
173 V(CookieAuthFile
, STRING
, NULL
),
174 V(DataDirectory
, STRING
, NULL
),
175 OBSOLETE("DebugLogFile"),
176 V(DirAllowPrivateAddresses
, BOOL
, NULL
),
177 V(DirListenAddress
, LINELIST
, NULL
),
178 OBSOLETE("DirFetchPeriod"),
179 V(DirPolicy
, LINELIST
, NULL
),
180 V(DirPort
, UINT
, "0"),
181 OBSOLETE("DirPostPeriod"),
182 VAR("DirServer", LINELIST
, DirServers
, NULL
),
183 V(DNSPort
, UINT
, "0"),
184 V(DNSListenAddress
, LINELIST
, NULL
),
185 V(DownloadExtraInfo
, BOOL
, "0"),
186 V(EnforceDistinctSubnets
, BOOL
, "1"),
187 V(EntryNodes
, STRING
, NULL
),
188 V(ExcludeNodes
, STRING
, NULL
),
189 V(ExitNodes
, STRING
, NULL
),
190 V(ExitPolicy
, LINELIST
, NULL
),
191 V(ExitPolicyRejectPrivate
, BOOL
, "1"),
192 V(FallbackNetworkstatusFile
, STRING
,
193 SHARE_DATADIR PATH_SEPARATOR
"tor" PATH_SEPARATOR
"fallback-consensus"),
194 V(FascistFirewall
, BOOL
, "0"),
195 V(FirewallPorts
, CSV
, ""),
196 V(FastFirstHopPK
, BOOL
, "1"),
197 V(FetchDirInfoEarly
, BOOL
, "0"),
198 V(FetchServerDescriptors
, BOOL
, "1"),
199 V(FetchHidServDescriptors
, BOOL
, "1"),
200 V(FetchUselessDescriptors
, BOOL
, "0"),
201 V(GeoIPFile
, STRING
, NULL
),
202 V(Group
, STRING
, NULL
),
203 V(HardwareAccel
, BOOL
, "0"),
204 V(HashedControlPassword
, LINELIST
, NULL
),
205 V(HidServDirectoryV2
, BOOL
, "0"),
206 VAR("HiddenServiceDir", LINELIST_S
, RendConfigLines
, NULL
),
207 VAR("HiddenServiceExcludeNodes", LINELIST_S
, RendConfigLines
, NULL
),
208 VAR("HiddenServiceNodes", LINELIST_S
, RendConfigLines
, NULL
),
209 VAR("HiddenServiceOptions",LINELIST_V
, RendConfigLines
, NULL
),
210 VAR("HiddenServicePort", LINELIST_S
, RendConfigLines
, NULL
),
211 VAR("HiddenServiceVersion",LINELIST_S
, RendConfigLines
, NULL
),
212 V(HSAuthoritativeDir
, BOOL
, "0"),
213 V(HSAuthorityRecordStats
, BOOL
, "0"),
214 V(HttpProxy
, STRING
, NULL
),
215 V(HttpProxyAuthenticator
, STRING
, NULL
),
216 V(HttpsProxy
, STRING
, NULL
),
217 V(HttpsProxyAuthenticator
, STRING
, NULL
),
218 OBSOLETE("IgnoreVersion"),
219 V(KeepalivePeriod
, INTERVAL
, "5 minutes"),
220 VAR("Log", LINELIST
, Logs
, NULL
),
221 OBSOLETE("LinkPadding"),
222 OBSOLETE("LogLevel"),
224 V(LongLivedPorts
, CSV
,
225 "21,22,706,1863,5050,5190,5222,5223,6667,6697,8300"),
226 VAR("MapAddress", LINELIST
, AddressMap
, NULL
),
227 V(MaxAdvertisedBandwidth
, MEMUNIT
, "1 GB"),
228 V(MaxCircuitDirtiness
, INTERVAL
, "10 minutes"),
229 V(MaxOnionsPending
, UINT
, "100"),
230 OBSOLETE("MonthlyAccountingStart"),
231 V(MyFamily
, STRING
, NULL
),
232 V(NewCircuitPeriod
, INTERVAL
, "30 seconds"),
233 VAR("NamingAuthoritativeDirectory",BOOL
, NamingAuthoritativeDir
, "0"),
234 V(NatdListenAddress
, LINELIST
, NULL
),
235 V(NatdPort
, UINT
, "0"),
236 V(Nickname
, STRING
, NULL
),
237 V(NoPublish
, BOOL
, "0"),
238 VAR("NodeFamily", LINELIST
, NodeFamilies
, NULL
),
239 V(NumCpus
, UINT
, "1"),
240 V(NumEntryGuards
, UINT
, "3"),
241 V(ORListenAddress
, LINELIST
, NULL
),
242 V(ORPort
, UINT
, "0"),
243 V(OutboundBindAddress
, STRING
, NULL
),
244 OBSOLETE("PathlenCoinWeight"),
245 V(PidFile
, STRING
, NULL
),
246 V(PreferTunneledDirConns
, BOOL
, "0"),
247 V(ProtocolWarnings
, BOOL
, "0"),
248 V(PublishServerDescriptor
, CSV
, "1"),
249 V(PublishHidServDescriptors
, BOOL
, "1"),
250 V(ReachableAddresses
, LINELIST
, NULL
),
251 V(ReachableDirAddresses
, LINELIST
, NULL
),
252 V(ReachableORAddresses
, LINELIST
, NULL
),
253 V(RecommendedVersions
, LINELIST
, NULL
),
254 V(RecommendedClientVersions
, LINELIST
, NULL
),
255 V(RecommendedServerVersions
, LINELIST
, NULL
),
256 V(RedirectExit
, LINELIST
, NULL
),
257 V(RejectPlaintextPorts
, CSV
, ""),
258 V(RelayBandwidthBurst
, MEMUNIT
, "0"),
259 V(RelayBandwidthRate
, MEMUNIT
, "0"),
260 V(RendExcludeNodes
, STRING
, NULL
),
261 V(RendNodes
, STRING
, NULL
),
262 V(RendPostPeriod
, INTERVAL
, "1 hour"),
263 V(RephistTrackTime
, INTERVAL
, "24 hours"),
264 OBSOLETE("RouterFile"),
265 V(RunAsDaemon
, BOOL
, "0"),
266 V(RunTesting
, BOOL
, "0"),
267 V(SafeLogging
, BOOL
, "1"),
268 V(SafeSocks
, BOOL
, "0"),
269 V(ServerDNSAllowBrokenResolvConf
, BOOL
, "0"),
270 V(ServerDNSAllowNonRFC953Hostnames
, BOOL
,"0"),
271 V(ServerDNSDetectHijacking
, BOOL
, "1"),
272 V(ServerDNSResolvConfFile
, STRING
, NULL
),
273 V(ServerDNSSearchDomains
, BOOL
, "0"),
274 V(ServerDNSTestAddresses
, CSV
,
275 "www.google.com,www.mit.edu,www.yahoo.com,www.slashdot.org"),
276 V(ShutdownWaitLength
, INTERVAL
, "30 seconds"),
277 V(SocksListenAddress
, LINELIST
, NULL
),
278 V(SocksPolicy
, LINELIST
, NULL
),
279 V(SocksPort
, UINT
, "9050"),
280 V(SocksTimeout
, INTERVAL
, "2 minutes"),
281 OBSOLETE("StatusFetchPeriod"),
282 V(StrictEntryNodes
, BOOL
, "0"),
283 V(StrictExitNodes
, BOOL
, "0"),
285 V(TestSocks
, BOOL
, "0"),
286 V(TestVia
, STRING
, NULL
),
287 V(TrackHostExits
, CSV
, NULL
),
288 V(TrackHostExitsExpire
, INTERVAL
, "30 minutes"),
289 OBSOLETE("TrafficShaping"),
290 V(TransListenAddress
, LINELIST
, NULL
),
291 V(TransPort
, UINT
, "0"),
292 V(TunnelDirConns
, BOOL
, "0"),
293 V(UpdateBridgesFromAuthority
, BOOL
, "0"),
294 V(UseBridges
, BOOL
, "0"),
295 V(UseEntryGuards
, BOOL
, "1"),
296 V(User
, STRING
, NULL
),
297 VAR("V1AuthoritativeDirectory",BOOL
, V1AuthoritativeDir
, "0"),
298 VAR("V2AuthoritativeDirectory",BOOL
, V2AuthoritativeDir
, "0"),
299 VAR("V3AuthoritativeDirectory",BOOL
, V3AuthoritativeDir
, "0"),
300 V(V3AuthVotingInterval
, INTERVAL
, "1 hour"),
301 V(V3AuthVoteDelay
, INTERVAL
, "5 minutes"),
302 V(V3AuthDistDelay
, INTERVAL
, "5 minutes"),
303 V(V3AuthNIntervalsValid
, UINT
, "3"),
304 VAR("VersioningAuthoritativeDirectory",BOOL
,VersioningAuthoritativeDir
, "0"),
305 V(VirtualAddrNetwork
, STRING
, "127.192.0.0/10"),
306 V(WarnPlaintextPorts
, CSV
, "23,109,110,143"),
307 VAR("__AllDirActionsPrivate", BOOL
, AllDirActionsPrivate
, "0"),
308 VAR("__DisablePredictedCircuits",BOOL
,DisablePredictedCircuits
, "0"),
309 VAR("__LeaveStreamsUnattached",BOOL
, LeaveStreamsUnattached
, "0"),
310 VAR("__HashedControlSessionPassword", LINELIST
, HashedControlSessionPassword
,
312 V(MinUptimeHidServDirectoryV2
, INTERVAL
, "24 hours"),
313 { NULL
, CONFIG_TYPE_OBSOLETE
, 0, NULL
}
317 #define VAR(name,conftype,member,initvalue) \
318 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_state_t, member), \
320 static config_var_t _state_vars
[] = {
321 V(AccountingBytesReadInInterval
, MEMUNIT
, NULL
),
322 V(AccountingBytesWrittenInInterval
, MEMUNIT
, NULL
),
323 V(AccountingExpectedUsage
, MEMUNIT
, NULL
),
324 V(AccountingIntervalStart
, ISOTIME
, NULL
),
325 V(AccountingSecondsActive
, INTERVAL
, NULL
),
327 VAR("EntryGuard", LINELIST_S
, EntryGuards
, NULL
),
328 VAR("EntryGuardDownSince", LINELIST_S
, EntryGuards
, NULL
),
329 VAR("EntryGuardUnlistedSince", LINELIST_S
, EntryGuards
, NULL
),
330 VAR("EntryGuardAddedBy", LINELIST_S
, EntryGuards
, NULL
),
331 V(EntryGuards
, LINELIST_V
, NULL
),
333 V(BWHistoryReadEnds
, ISOTIME
, NULL
),
334 V(BWHistoryReadInterval
, UINT
, "900"),
335 V(BWHistoryReadValues
, CSV
, ""),
336 V(BWHistoryWriteEnds
, ISOTIME
, NULL
),
337 V(BWHistoryWriteInterval
, UINT
, "900"),
338 V(BWHistoryWriteValues
, CSV
, ""),
340 V(TorVersion
, STRING
, NULL
),
342 V(LastRotatedOnionKey
, ISOTIME
, NULL
),
343 V(LastWritten
, ISOTIME
, NULL
),
345 { NULL
, CONFIG_TYPE_OBSOLETE
, 0, NULL
}
352 /** Represents an English description of a configuration variable; used when
353 * generating configuration file comments. */
354 typedef struct config_var_description_t
{
356 const char *description
;
357 } config_var_description_t
;
359 static config_var_description_t options_description
[] = {
360 /* ==== general options */
361 { "AvoidDiskWrites", "If non-zero, try to write to disk less frequently than"
362 " we would otherwise." },
363 { "BandwidthRate", "A token bucket limits the average incoming bandwidth on "
364 "this node to the specified number of bytes per second." },
365 { "BandwidthBurst", "Limit the maximum token buffer size (also known as "
366 "burst) to the given number of bytes." },
367 { "ConnLimit", "Minimum number of simultaneous sockets we must have." },
368 { "ConstrainedSockets", "Shrink tx and rx buffers for sockets to avoid "
369 "system limits on vservers and related environments. See man page for "
370 "more information regarding this option." },
371 { "ConstrainedSockSize", "Limit socket buffers to this size when "
372 "ConstrainedSockets is enabled." },
373 /* ControlListenAddress */
374 { "ControlPort", "If set, Tor will accept connections from the same machine "
375 "(localhost only) on this port, and allow those connections to control "
376 "the Tor process using the Tor Control Protocol (described in"
377 "control-spec.txt).", },
378 { "CookieAuthentication", "If this option is set to 1, don't allow any "
379 "connections to the control port except when the connecting process "
380 "can read a file that Tor creates in its data directory." },
381 { "DataDirectory", "Store working data, state, keys, and caches here." },
382 { "DirServer", "Tor only trusts directories signed with one of these "
383 "servers' keys. Used to override the standard list of directory "
385 /* { "FastFirstHopPK", "" }, */
386 /* FetchServerDescriptors, FetchHidServDescriptors,
387 * FetchUselessDescriptors */
388 { "Group", "On startup, setgid to this group." },
389 { "HardwareAccel", "If set, Tor tries to use hardware crypto accelerators "
391 /* HashedControlPassword */
392 { "HTTPProxy", "Force Tor to make all HTTP directory requests through this "
393 "host:port (or host:80 if port is not set)." },
394 { "HTTPProxyAuthenticator", "A username:password pair to be used with "
396 { "HTTPSProxy", "Force Tor to make all TLS (SSL) connectinos through this "
397 "host:port (or host:80 if port is not set)." },
398 { "HTTPSProxyAuthenticator", "A username:password pair to be used with "
400 { "KeepalivePeriod", "Send a padding cell every N seconds to keep firewalls "
401 "from closing our connections while Tor is not in use." },
402 { "Log", "Where to send logging messages. Format is "
403 "minSeverity[-maxSeverity] (stderr|stdout|syslog|file FILENAME)." },
404 { "OutboundBindAddress", "Make all outbound connections originate from the "
405 "provided IP address (only useful for multiple network interfaces)." },
406 { "PIDFile", "On startup, write our PID to this file. On clean shutdown, "
407 "remove the file." },
408 { "PreferTunneledDirConns", "If non-zero, avoid directory servers that "
409 "don't support tunneled connections." },
410 /* PreferTunneledDirConns */
411 /* ProtocolWarnings */
412 /* RephistTrackTime */
413 { "RunAsDaemon", "If set, Tor forks and daemonizes to the background when "
414 "started. Unix only." },
415 { "SafeLogging", "If set to 0, Tor logs potentially sensitive strings "
416 "rather than replacing them with the string [scrubbed]." },
417 { "TunnelDirConns", "If non-zero, when a directory server we contact "
418 "supports it, we will build a one-hop circuit and make an encrypted "
419 "connection via its ORPort." },
420 { "User", "On startup, setuid to this user" },
422 /* ==== client options */
423 { "AllowInvalidNodes", "Where on our circuits should Tor allow servers "
424 "that the directory authorities haven't called \"valid\"?" },
425 { "AllowNonRFC953Hostnames", "If set to 1, we don't automatically reject "
426 "hostnames for having invalid characters." },
427 /* CircuitBuildTimeout, CircuitIdleTimeout */
428 { "ClientOnly", "If set to 1, Tor will under no circumstances run as a "
429 "server, even if ORPort is enabled." },
430 { "EntryNodes", "A list of preferred entry nodes to use for the first hop "
431 "in circuits, when possible." },
432 /* { "EnforceDistinctSubnets" , "" }, */
433 { "ExitNodes", "A list of preferred nodes to use for the last hop in "
434 "circuits, when possible." },
435 { "ExcludeNodes", "A list of nodes never to use when building a circuit." },
436 { "FascistFirewall", "If set, Tor will only create outgoing connections to "
437 "servers running on the ports listed in FirewallPorts." },
438 { "FirewallPorts", "A list of ports that we can connect to. Only used "
439 "when FascistFirewall is set." },
440 { "LongLivedPorts", "A list of ports for services that tend to require "
441 "high-uptime connections." },
442 { "MapAddress", "Force Tor to treat all requests for one address as if "
443 "they were for another." },
444 { "NewCircuitPeriod", "Force Tor to consider whether to build a new circuit "
445 "every NUM seconds." },
446 { "MaxCircuitDirtiness", "Do not attach new streams to a circuit that has "
447 "been used more than this many seconds ago." },
448 /* NatdPort, NatdListenAddress */
449 { "NodeFamily", "A list of servers that constitute a 'family' and should "
450 "never be used in the same circuit." },
451 { "NumEntryGuards", "How many entry guards should we keep at a time?" },
452 /* PathlenCoinWeight */
453 { "ReachableAddresses", "Addresses we can connect to, as IP/bits:port-port. "
454 "By default, we assume all addresses are reachable." },
455 /* reachablediraddresses, reachableoraddresses. */
456 { "RendNodes", "A list of preferred nodes to use for a rendezvous point, "
458 { "RendExcludenodes", "A list of nodes never to use as rendezvous points." },
460 { "SOCKSPort", "The port where we listen for SOCKS connections from "
462 { "SOCKSListenAddress", "Bind to this address to listen to connections from "
463 "SOCKS-speaking applications." },
464 { "SOCKSPolicy", "Set an entry policy to limit which addresses can connect "
465 "to the SOCKSPort." },
467 { "StrictExitNodes", "If set, Tor will fail to operate when none of the "
468 "configured ExitNodes can be used." },
469 { "StrictEntryNodes", "If set, Tor will fail to operate when none of the "
470 "configured EntryNodes can be used." },
472 { "TrackHostsExit", "Hosts and domains which should, if possible, be "
473 "accessed from the same exit node each time we connect to them." },
474 { "TrackHostsExitExpire", "Time after which we forget which exit we were "
475 "using to connect to hosts in TrackHostsExit." },
476 /* "TransPort", "TransListenAddress */
477 { "UseEntryGuards", "Set to 0 if we want to pick from the whole set of "
478 "servers for the first position in each circuit, rather than picking a "
479 "set of 'Guards' to prevent profiling attacks." },
481 /* === server options */
482 { "Address", "The advertised (external) address we should use." },
483 /* Accounting* options. */
484 /* AssumeReachable */
485 { "ContactInfo", "Administrative contact information to advertise for this "
487 { "ExitPolicy", "Address/port ranges for which to accept or reject outgoing "
488 "connections on behalf of Tor users." },
489 /* { "ExitPolicyRejectPrivate, "" }, */
490 { "MaxAdvertisedBandwidth", "If set, we will not advertise more than this "
491 "amount of bandwidth for our bandwidth rate, regardless of how much "
492 "bandwidth we actually detect." },
493 { "MaxOnionsPending", "Reject new attempts to extend circuits when we "
494 "already have this many pending." },
495 { "MyFamily", "Declare a list of other servers as belonging to the same "
496 "family as this one, so that clients will not use two from the same "
497 "family in the same circuit." },
498 { "Nickname", "Set the server nickname." },
499 { "NoPublish", "{DEPRECATED}" },
500 { "NumCPUs", "How many processes to use at once for public-key crypto." },
501 { "ORPort", "Advertise this port to listen for connections from Tor clients "
503 { "ORListenAddress", "Bind to this address to listen for connections from "
504 "clients and servers, instead of the default 0.0.0.0:ORPort." },
505 { "PublishServerDescriptor", "Set to 0 to keep the server from "
506 "uploading info to the directory authorities." },
507 /*{ "RedirectExit", "When an outgoing connection tries to connect to a "
508 *"given address, redirect it to another address instead." },
510 /* ServerDNS: DetectHijacking, ResolvConfFile, SearchDomains */
511 { "ShutdownWaitLength", "Wait this long for clients to finish when "
512 "shutting down because of a SIGINT." },
515 /* === directory cache options */
516 { "DirPort", "Serve directory information from this port, and act as a "
517 "directory cache." },
518 { "DirListenAddress", "Bind to this address to listen for connections from "
519 "clients and servers, instead of the default 0.0.0.0:DirPort." },
520 { "DirPolicy", "Set a policy to limit who can connect to the directory "
523 /* Authority options: AuthDirBadExit, AuthDirInvalid, AuthDirReject,
524 * AuthDirRejectUnlisted, AuthDirListBadExits, AuthoritativeDirectory,
525 * DirAllowPrivateAddresses, HSAuthoritativeDir,
526 * NamingAuthoritativeDirectory, RecommendedVersions,
527 * RecommendedClientVersions, RecommendedServerVersions, RendPostPeriod,
528 * RunTesting, V1AuthoritativeDirectory, VersioningAuthoritativeDirectory, */
530 /* Hidden service options: HiddenService: dir,excludenodes, nodes,
531 * options, port. PublishHidServDescriptor */
533 /* Nonpersistent options: __LeaveStreamsUnattached, __AllDirActionsPrivate */
537 static config_var_description_t state_description
[] = {
538 { "AccountingBytesReadInInterval",
539 "How many bytes have we read in this accounting period?" },
540 { "AccountingBytesWrittenInInterval",
541 "How many bytes have we written in this accounting period?" },
542 { "AccountingExpectedUsage",
543 "How many bytes did we expect to use per minute? (0 for no estimate.)" },
544 { "AccountingIntervalStart", "When did this accounting period begin?" },
545 { "AccountingSecondsActive", "How long have we been awake in this period?" },
547 { "BWHistoryReadEnds", "When does the last-recorded read-interval end?" },
548 { "BWHistoryReadInterval", "How long is each read-interval (in seconds)?" },
549 { "BWHistoryReadValues", "Number of bytes read in each interval." },
550 { "BWHistoryWriteEnds", "When does the last-recorded write-interval end?" },
551 { "BWHistoryWriteInterval", "How long is each write-interval (in seconds)?"},
552 { "BWHistoryWriteValues", "Number of bytes written in each interval." },
554 { "EntryGuard", "One of the nodes we have chosen as a fixed entry" },
555 { "EntryGuardDownSince",
556 "The last entry guard has been unreachable since this time." },
557 { "EntryGuardUnlistedSince",
558 "The last entry guard has been unusable since this time." },
560 { "LastRotatedOnionKey",
561 "The last time at which we changed the medium-term private key used for "
562 "building circuits." },
563 { "LastWritten", "When was this state file last regenerated?" },
565 { "TorVersion", "Which version of Tor generated this state file?" },
569 /** Type of a callback to validate whether a given configuration is
570 * well-formed and consistent. See options_trial_assign() for documentation
572 typedef int (*validate_fn_t
)(void*,void*,int,char**);
574 /** Information on the keys, value types, key-to-struct-member mappings,
575 * variable descriptions, validation functions, and abbreviations for a
576 * configuration or storage format. */
578 size_t size
; /**< Size of the struct that everything gets parsed into. */
579 uint32_t magic
; /**< Required 'magic value' to make sure we have a struct
580 * of the right type. */
581 off_t magic_offset
; /**< Offset of the magic value within the struct. */
582 config_abbrev_t
*abbrevs
; /**< List of abbreviations that we expand when
583 * parsing this format. */
584 config_var_t
*vars
; /**< List of variables we recognize, their default
585 * values, and where we stick them in the structure. */
586 validate_fn_t validate_fn
; /**< Function to validate config. */
587 /** Documentation for configuration variables. */
588 config_var_description_t
*descriptions
;
589 /** If present, extra is a LINELIST variable for unrecognized
590 * lines. Otherwise, unrecognized lines are an error. */
594 /** Macro: assert that <b>cfg</b> has the right magic field for format
596 #define CHECK(fmt, cfg) STMT_BEGIN \
597 tor_assert(fmt && cfg); \
598 tor_assert((fmt)->magic == \
599 *(uint32_t*)STRUCT_VAR_P(cfg,fmt->magic_offset)); \
602 static void config_line_append(config_line_t
**lst
,
603 const char *key
, const char *val
);
604 static void option_clear(config_format_t
*fmt
, or_options_t
*options
,
606 static void option_reset(config_format_t
*fmt
, or_options_t
*options
,
607 config_var_t
*var
, int use_defaults
);
608 static void config_free(config_format_t
*fmt
, void *options
);
609 static int config_lines_eq(config_line_t
*a
, config_line_t
*b
);
610 static int option_is_same(config_format_t
*fmt
,
611 or_options_t
*o1
, or_options_t
*o2
,
613 static or_options_t
*options_dup(config_format_t
*fmt
, or_options_t
*old
);
614 static int options_validate(or_options_t
*old_options
, or_options_t
*options
,
615 int from_setconf
, char **msg
);
616 static int options_act_reversible(or_options_t
*old_options
, char **msg
);
617 static int options_act(or_options_t
*old_options
);
618 static int options_transition_allowed(or_options_t
*old
, or_options_t
*new,
620 static int options_transition_affects_workers(or_options_t
*old_options
,
621 or_options_t
*new_options
);
622 static int options_transition_affects_descriptor(or_options_t
*old_options
,
623 or_options_t
*new_options
);
624 static int check_nickname_list(const char *lst
, const char *name
, char **msg
);
625 static void config_register_addressmaps(or_options_t
*options
);
627 static int parse_bridge_line(const char *line
, int validate_only
);
628 static int parse_dir_server_line(const char *line
,
629 authority_type_t required_type
,
631 static int parse_redirect_line(smartlist_t
*result
,
632 config_line_t
*line
, char **msg
);
633 static int parse_log_severity_range(const char *range
, int *min_out
,
635 static int validate_data_directory(or_options_t
*options
);
636 static int write_configuration_file(const char *fname
, or_options_t
*options
);
637 static config_line_t
*get_assigned_option(config_format_t
*fmt
,
638 or_options_t
*options
, const char *key
,
640 static void config_init(config_format_t
*fmt
, void *options
);
641 static int or_state_validate(or_state_t
*old_options
, or_state_t
*options
,
642 int from_setconf
, char **msg
);
643 static int or_state_load(void);
644 static int options_init_logs(or_options_t
*options
, int validate_only
);
646 static uint64_t config_parse_memunit(const char *s
, int *ok
);
647 static int config_parse_interval(const char *s
, int *ok
);
648 static void print_svn_version(void);
649 static void init_libevent(void);
650 static int opt_streq(const char *s1
, const char *s2
);
651 /** Versions of libevent. */
653 /* Note: we compare these, so it's important that "old" precede everything,
654 * and that "other" come last. */
655 LE_OLD
=0, LE_10C
, LE_10D
, LE_10E
, LE_11
, LE_11A
, LE_11B
, LE_12
, LE_12A
,
656 LE_13
, LE_13A
, LE_13B
, LE_13C
, LE_13D
,
659 static le_version_t
decode_libevent_version(void);
660 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
661 static void check_libevent_version(const char *m
, int server
);
664 /** Magic value for or_options_t. */
665 #define OR_OPTIONS_MAGIC 9090909
667 /** Configuration format for or_options_t. */
668 static config_format_t options_format
= {
669 sizeof(or_options_t
),
671 STRUCT_OFFSET(or_options_t
, _magic
),
674 (validate_fn_t
)options_validate
,
679 /** Magic value for or_state_t. */
680 #define OR_STATE_MAGIC 0x57A73f57
682 /** "Extra" variable in the state that receives lines we can't parse. This
683 * lets us preserve options from versions of Tor newer than us. */
684 static config_var_t state_extra_var
= {
685 "__extra", CONFIG_TYPE_LINELIST
, STRUCT_OFFSET(or_state_t
, ExtraLines
), NULL
688 /** Configuration format for or_state_t. */
689 static config_format_t state_format
= {
692 STRUCT_OFFSET(or_state_t
, _magic
),
695 (validate_fn_t
)or_state_validate
,
701 * Functions to read and write the global options pointer.
704 /** Command-line and config-file options. */
705 static or_options_t
*global_options
= NULL
;
706 /** Name of most recently read torrc file. */
707 static char *torrc_fname
= NULL
;
708 /** Persistent serialized state. */
709 static or_state_t
*global_state
= NULL
;
711 /** Allocate an empty configuration object of a given format type. */
713 config_alloc(config_format_t
*fmt
)
715 void *opts
= tor_malloc_zero(fmt
->size
);
716 *(uint32_t*)STRUCT_VAR_P(opts
, fmt
->magic_offset
) = fmt
->magic
;
721 /** Return the currently configured options. */
725 tor_assert(global_options
);
726 return global_options
;
729 /** Change the current global options to contain <b>new_val</b> instead of
730 * their current value; take action based on the new value; free the old value
734 set_options(or_options_t
*new_val
, char **msg
)
736 or_options_t
*old_options
= global_options
;
737 global_options
= new_val
;
738 /* Note that we pass the *old* options below, for comparison. It
739 * pulls the new options directly out of global_options. */
740 if (options_act_reversible(old_options
, msg
)<0) {
742 global_options
= old_options
;
745 if (options_act(old_options
) < 0) { /* acting on the options failed. die. */
747 "Acting on config options left us in a broken state. Dying.");
751 config_free(&options_format
, old_options
);
756 extern const char tor_svn_revision
[]; /* from tor_main.c */
758 static char *_version
= NULL
;
760 /** Return the current Tor version, possibly */
764 if (_version
== NULL
) {
765 if (strlen(tor_svn_revision
)) {
766 size_t len
= strlen(VERSION
)+strlen(tor_svn_revision
)+8;
767 _version
= tor_malloc(len
);
768 tor_snprintf(_version
, len
, "%s (r%s)", VERSION
, tor_svn_revision
);
770 _version
= tor_strdup(VERSION
);
776 /** Release all memory and resources held by global configuration structures.
779 config_free_all(void)
781 if (global_options
) {
782 config_free(&options_format
, global_options
);
783 global_options
= NULL
;
786 config_free(&state_format
, global_state
);
789 tor_free(torrc_fname
);
793 /** If options->SafeLogging is on, return a not very useful string,
794 * else return address.
797 safe_str(const char *address
)
800 if (get_options()->SafeLogging
)
806 /** Equivalent to escaped(safe_str(address)). See reentrancy note on
807 * escaped(): don't use this outside the main thread, or twice in the same
810 escaped_safe_str(const char *address
)
812 if (get_options()->SafeLogging
)
815 return escaped(address
);
818 /** Add the default directory authorities directly into the trusted dir list,
819 * but only add them insofar as they share bits with <b>type</b>. */
821 add_default_trusted_dir_authorities(authority_type_t type
)
824 const char *dirservers
[] = {
825 "moria1 v1 orport=9001 v3ident=5420FD8EA46BD4290F1D07A1883C9D85ECC486C4 "
826 "128.31.0.34:9031 FFCB 46DB 1339 DA84 674C 70D7 CB58 6434 C437 0441",
827 "moria2 v1 orport=9002 128.31.0.34:9032 "
828 "719B E45D E224 B607 C537 07D0 E214 3E2D 423E 74CF",
829 "tor26 v1 orport=443 v3ident=A9AC67E64B200BBF2FA26DF194AC0469E2A948C6 "
830 "86.59.21.38:80 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D",
831 "lefkada orport=443 v3ident=0D95B91896E6089AB9A3C6CB56E724CAF898C43F "
832 "140.247.60.64:80 38D4 F5FC F7B1 0232 28B8 95EA 56ED E7D5 CCDC AF32",
833 "dizum 194.109.206.212:80 "
834 "7EA6 EAD6 FD83 083C 538F 4403 8BBF A077 587D D755",
835 "Tonga orport=443 bridge no-v2 82.94.251.206:80 "
836 "4A0C CD2D DC79 9508 3D73 F5D6 6710 0C8A 5831 F16D",
837 "ides orport=9090 no-v2 v3ident=27B6B5996C426270A5C95488AA5BCEB6BCC86956 "
838 "216.224.124.114:9030 F397 038A DC51 3361 35E7 B80B D99C A384 4360 292B",
839 "gabelmoo orport=443 no-v2 "
840 "v3ident=EAA879B5C75032E462CB018630D2D0DF46EBA606 "
841 "88.198.7.215:80 6833 3D07 61BC F397 A587 A0C0 B963 E4A9 E99E C4D3",
842 "dannenberg orport=443 no-v2 "
843 "v3ident=585769C78764D58426B8B52B6651A5A71137189A "
844 "213.73.91.31:80 7BE6 83E6 5D48 1413 21C5 ED92 F075 C553 64AC 7123",
847 for (i
=0; dirservers
[i
]; i
++) {
848 if (parse_dir_server_line(dirservers
[i
], type
, 0)<0) {
849 log_err(LD_BUG
, "Couldn't parse internal dirserver line %s",
855 /** Look at all the config options for using alternate directory
856 * authorities, and make sure none of them are broken. Also, warn the
857 * user if we changed any dangerous ones.
860 validate_dir_authorities(or_options_t
*options
, or_options_t
*old_options
)
864 if (options
->DirServers
&&
865 (options
->AlternateDirAuthority
|| options
->AlternateBridgeAuthority
||
866 options
->AlternateHSAuthority
)) {
868 "You cannot set both DirServers and Alternate*Authority.");
872 /* do we want to complain to the user about being partitionable? */
873 if ((options
->DirServers
&&
875 !config_lines_eq(options
->DirServers
, old_options
->DirServers
))) ||
876 (options
->AlternateDirAuthority
&&
878 !config_lines_eq(options
->AlternateDirAuthority
,
879 old_options
->AlternateDirAuthority
)))) {
881 "You have used DirServer or AlternateDirAuthority to "
882 "specify alternate directory authorities in "
883 "your configuration. This is potentially dangerous: it can "
884 "make you look different from all other Tor users, and hurt "
885 "your anonymity. Even if you've specified the same "
886 "authorities as Tor uses by default, the defaults could "
887 "change in the future. Be sure you know what you're doing.");
890 /* Now go through the four ways you can configure an alternate
891 * set of directory authorities, and make sure none are broken. */
892 for (cl
= options
->DirServers
; cl
; cl
= cl
->next
)
893 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 1)<0)
895 for (cl
= options
->AlternateBridgeAuthority
; cl
; cl
= cl
->next
)
896 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 1)<0)
898 for (cl
= options
->AlternateDirAuthority
; cl
; cl
= cl
->next
)
899 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 1)<0)
901 for (cl
= options
->AlternateHSAuthority
; cl
; cl
= cl
->next
)
902 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 1)<0)
907 /** Look at all the config options and assign new dir authorities
911 consider_adding_dir_authorities(or_options_t
*options
,
912 or_options_t
*old_options
)
916 !smartlist_len(router_get_trusted_dir_servers()) || !old_options
||
917 !config_lines_eq(options
->DirServers
, old_options
->DirServers
) ||
918 !config_lines_eq(options
->AlternateBridgeAuthority
,
919 old_options
->AlternateBridgeAuthority
) ||
920 !config_lines_eq(options
->AlternateDirAuthority
,
921 old_options
->AlternateDirAuthority
) ||
922 !config_lines_eq(options
->AlternateHSAuthority
,
923 old_options
->AlternateHSAuthority
);
926 return 0; /* all done */
928 /* Start from a clean slate. */
929 clear_trusted_dir_servers();
931 if (!options
->DirServers
) {
932 /* then we may want some of the defaults */
933 authority_type_t type
= NO_AUTHORITY
;
934 if (!options
->AlternateBridgeAuthority
)
935 type
|= BRIDGE_AUTHORITY
;
936 if (!options
->AlternateDirAuthority
)
937 type
|= V1_AUTHORITY
| V2_AUTHORITY
| V3_AUTHORITY
;
938 if (!options
->AlternateHSAuthority
)
939 type
|= HIDSERV_AUTHORITY
;
940 add_default_trusted_dir_authorities(type
);
943 for (cl
= options
->DirServers
; cl
; cl
= cl
->next
)
944 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 0)<0)
946 for (cl
= options
->AlternateBridgeAuthority
; cl
; cl
= cl
->next
)
947 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 0)<0)
949 for (cl
= options
->AlternateDirAuthority
; cl
; cl
= cl
->next
)
950 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 0)<0)
952 for (cl
= options
->AlternateHSAuthority
; cl
; cl
= cl
->next
)
953 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 0)<0)
958 /** Fetch the active option list, and take actions based on it. All of the
959 * things we do should survive being done repeatedly. If present,
960 * <b>old_options</b> contains the previous value of the options.
962 * Return 0 if all goes well, return -1 if things went badly.
965 options_act_reversible(or_options_t
*old_options
, char **msg
)
967 smartlist_t
*new_listeners
= smartlist_create();
968 smartlist_t
*replaced_listeners
= smartlist_create();
969 static int libevent_initialized
= 0;
970 or_options_t
*options
= get_options();
971 int running_tor
= options
->command
== CMD_RUN_TOR
;
972 int set_conn_limit
= 0;
976 /* Daemonize _first_, since we only want to open most of this stuff in
977 * the subprocess. Libevent bases can't be reliably inherited across
979 if (running_tor
&& options
->RunAsDaemon
) {
980 /* No need to roll back, since you can't change the value. */
984 #ifndef HAVE_SYS_UN_H
985 if (options
->ControlSocket
) {
986 *msg
= tor_strdup("Unix domain sockets (ControlSocket) not supported"
987 " on this OS/with this build.");
993 /* We need to set the connection limit before we can open the listeners. */
994 if (set_max_file_descriptors((unsigned)options
->ConnLimit
,
995 &options
->_ConnLimit
) < 0) {
996 *msg
= tor_strdup("Problem with ConnLimit value. See logs for details.");
1001 /* Set up libevent. (We need to do this before we can register the
1002 * listeners as listeners.) */
1003 if (running_tor
&& !libevent_initialized
) {
1005 libevent_initialized
= 1;
1008 /* Launch the listeners. (We do this before we setuid, so we can bind to
1009 * ports under 1024.) */
1010 if (retry_all_listeners(replaced_listeners
, new_listeners
) < 0) {
1011 *msg
= tor_strdup("Failed to bind one of the listener ports.");
1016 /* Setuid/setgid as appropriate */
1017 if (options
->User
|| options
->Group
) {
1018 /* XXXX021 We should only do this the first time through, not on
1020 if (switch_id(options
->User
, options
->Group
) != 0) {
1021 /* No need to roll back, since you can't change the value. */
1022 *msg
= tor_strdup("Problem with User or Group value. "
1023 "See logs for details.");
1028 /* Ensure data directory is private; create if possible. */
1029 if (check_private_dir(options
->DataDirectory
,
1030 running_tor
? CPD_CREATE
: CPD_CHECK
)<0) {
1032 int tmp
= tor_snprintf(buf
, sizeof(buf
),
1033 "Couldn't access/create private data directory \"%s\"",
1034 options
->DataDirectory
);
1035 *msg
= tor_strdup(tmp
>= 0 ? buf
: "internal error");
1037 /* No need to roll back, since you can't change the value. */
1040 /* Bail out at this point if we're not going to be a client or server:
1041 * we don't run Tor itself. */
1045 mark_logs_temp(); /* Close current logs once new logs are open. */
1047 if (options_init_logs(options
, 0)<0) { /* Configure the log(s) */
1048 *msg
= tor_strdup("Failed to init Log options. See logs for details.");
1056 add_callback_log(LOG_ERR
, LOG_ERR
, control_event_logmsg
);
1057 control_adjust_event_log_severity();
1059 SMARTLIST_FOREACH(replaced_listeners
, connection_t
*, conn
,
1061 log_notice(LD_NET
, "Closing old %s on %s:%d",
1062 conn_type_to_string(conn
->type
), conn
->address
, conn
->port
);
1063 connection_close_immediate(conn
);
1064 connection_mark_for_close(conn
);
1073 rollback_log_changes();
1074 control_adjust_event_log_severity();
1077 if (set_conn_limit
&& old_options
)
1078 set_max_file_descriptors((unsigned)old_options
->ConnLimit
,
1079 &options
->_ConnLimit
);
1081 SMARTLIST_FOREACH(new_listeners
, connection_t
*, conn
,
1083 log_notice(LD_NET
, "Closing partially-constructed listener %s on %s:%d",
1084 conn_type_to_string(conn
->type
), conn
->address
, conn
->port
);
1085 connection_close_immediate(conn
);
1086 connection_mark_for_close(conn
);
1090 smartlist_free(new_listeners
);
1091 smartlist_free(replaced_listeners
);
1095 /** Fetch the active option list, and take actions based on it. All of the
1096 * things we do should survive being done repeatedly. If present,
1097 * <b>old_options</b> contains the previous value of the options.
1099 * Return 0 if all goes well, return -1 if it's time to die.
1101 * Note: We haven't moved all the "act on new configuration" logic
1102 * here yet. Some is still in do_hup() and other places.
1105 options_act(or_options_t
*old_options
)
1110 or_options_t
*options
= get_options();
1111 int running_tor
= options
->command
== CMD_RUN_TOR
;
1114 if (consider_adding_dir_authorities(options
, old_options
) < 0)
1117 if (options
->Bridges
) {
1118 clear_bridge_list();
1119 for (cl
= options
->Bridges
; cl
; cl
= cl
->next
) {
1120 if (parse_bridge_line(cl
->value
, 0)<0) {
1122 "Previously validated Bridge line could not be added!");
1128 if (running_tor
&& rend_config_services(options
, 0)<0) {
1130 "Previously validated hidden services line could not be added!");
1134 if (running_tor
&& directory_caches_v2_dir_info(options
)) {
1135 len
= strlen(options
->DataDirectory
)+32;
1136 fn
= tor_malloc(len
);
1137 tor_snprintf(fn
, len
, "%s"PATH_SEPARATOR
"cached-status",
1138 options
->DataDirectory
);
1139 if (check_private_dir(fn
, CPD_CREATE
) != 0) {
1141 "Couldn't access/create private data directory \"%s\"", fn
);
1149 if (! global_state
&& options
->command
== CMD_RUN_TOR
) {
1150 if (or_state_load())
1152 rep_hist_load_mtbf_data(time(NULL
));
1155 /* Bail out at this point if we're not going to be a client or server:
1156 * we want to not fork, and to log stuff to stderr. */
1161 smartlist_t
*sl
= smartlist_create();
1162 char *errmsg
= NULL
;
1163 for (cl
= options
->RedirectExit
; cl
; cl
= cl
->next
) {
1164 if (parse_redirect_line(sl
, cl
, &errmsg
)<0) {
1165 log_warn(LD_CONFIG
, "%s", errmsg
);
1167 SMARTLIST_FOREACH(sl
, exit_redirect_t
*, er
, tor_free(er
));
1172 set_exit_redirects(sl
);
1175 /* Finish backgrounding the process */
1176 if (running_tor
&& options
->RunAsDaemon
) {
1177 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
1178 finish_daemon(options
->DataDirectory
);
1181 /* Write our pid to the pid file. If we do not have write permissions we
1182 * will log a warning */
1183 if (running_tor
&& options
->PidFile
)
1184 write_pidfile(options
->PidFile
);
1186 /* Register addressmap directives */
1187 config_register_addressmaps(options
);
1188 parse_virtual_addr_network(options
->VirtualAddrNetwork
, 0, &msg
);
1190 /* Update address policies. */
1191 if (policies_parse_from_options(options
) < 0) {
1192 /* This should be impossible, but let's be sure. */
1193 log_warn(LD_BUG
,"Error parsing already-validated policy options.");
1197 if (init_cookie_authentication(options
->CookieAuthentication
) < 0) {
1198 log_warn(LD_CONFIG
,"Error creating cookie authentication file.");
1202 /* reload keys as needed for rendezvous services. */
1203 if (rend_service_load_keys()<0) {
1204 log_warn(LD_GENERAL
,"Error loading rendezvous service keys");
1208 /* Set up accounting */
1209 if (accounting_parse_options(options
, 0)<0) {
1210 log_warn(LD_CONFIG
,"Error in accounting options");
1213 if (accounting_is_enabled(options
))
1214 configure_accounting(time(NULL
));
1216 /* Check for transitions that need action. */
1218 if (options
->UseEntryGuards
&& !old_options
->UseEntryGuards
) {
1220 "Switching to entry guards; abandoning previous circuits");
1221 circuit_mark_all_unused_circs();
1222 circuit_expire_all_dirty_circs();
1225 if (options_transition_affects_workers(old_options
, options
)) {
1226 log_info(LD_GENERAL
,
1227 "Worker-related options changed. Rotating workers.");
1228 if (server_mode(options
) && !server_mode(old_options
)) {
1229 if (init_keys() < 0) {
1230 log_warn(LD_BUG
,"Error initializing keys; exiting");
1233 ip_address_changed(0);
1234 if (has_completed_circuit
|| !any_predicted_circuits(time(NULL
)))
1235 inform_testing_reachability();
1237 cpuworkers_rotate();
1245 if (options
->V3AuthoritativeDir
&& !old_options
->V3AuthoritativeDir
)
1249 /* Maybe load geoip file */
1250 if (options
->GeoIPFile
&&
1251 ((!old_options
|| !opt_streq(old_options
->GeoIPFile
, options
->GeoIPFile
))
1252 || !geoip_is_loaded())) {
1253 geoip_load_file(options
->GeoIPFile
);
1255 /* Check if we need to parse and add the EntryNodes config option. */
1256 if (options
->EntryNodes
&&
1258 !opt_streq(old_options
->EntryNodes
, options
->EntryNodes
)))
1259 entry_nodes_should_be_added();
1261 /* Since our options changed, we might need to regenerate and upload our
1262 * server descriptor.
1265 options_transition_affects_descriptor(old_options
, options
))
1266 mark_my_descriptor_dirty();
1268 /* We may need to reschedule some directory stuff if our status changed. */
1270 if (authdir_mode_v3(options
) && !authdir_mode_v3(old_options
))
1271 dirvote_recalculate_timing(options
, time(NULL
));
1272 if (!bool_eq(directory_fetches_dir_info_early(options
),
1273 directory_fetches_dir_info_early(old_options
)) ||
1274 !bool_eq(directory_fetches_dir_info_later(options
),
1275 directory_fetches_dir_info_later(old_options
))) {
1276 /* Make sure update_router_have_min_dir_info gets called. */
1277 router_dir_info_changed();
1278 /* We might need to download a new consensus status later or sooner than
1279 * we had expected. */
1280 update_consensus_networkstatus_fetch_time(time(NULL
));
1288 * Functions to parse config options
1291 /** If <b>option</b> is an official abbreviation for a longer option,
1292 * return the longer option. Otherwise return <b>option</b>.
1293 * If <b>command_line</b> is set, apply all abbreviations. Otherwise, only
1294 * apply abbreviations that work for the config file and the command line.
1295 * If <b>warn_obsolete</b> is set, warn about deprecated names. */
1297 expand_abbrev(config_format_t
*fmt
, const char *option
, int command_line
,
1303 for (i
=0; fmt
->abbrevs
[i
].abbreviated
; ++i
) {
1304 /* Abbreviations are casei. */
1305 if (!strcasecmp(option
,fmt
->abbrevs
[i
].abbreviated
) &&
1306 (command_line
|| !fmt
->abbrevs
[i
].commandline_only
)) {
1307 if (warn_obsolete
&& fmt
->abbrevs
[i
].warn
) {
1309 "The configuration option '%s' is deprecated; "
1310 "use '%s' instead.",
1311 fmt
->abbrevs
[i
].abbreviated
,
1312 fmt
->abbrevs
[i
].full
);
1314 return fmt
->abbrevs
[i
].full
;
1320 /** Helper: Read a list of configuration options from the command line.
1321 * If successful, put them in *<b>result</b> and return 0, and return
1322 * -1 and leave *<b>result</b> alone. */
1324 config_get_commandlines(int argc
, char **argv
, config_line_t
**result
)
1326 config_line_t
*front
= NULL
;
1327 config_line_t
**new = &front
;
1332 if (!strcmp(argv
[i
],"-f") ||
1333 !strcmp(argv
[i
],"--hash-password")) {
1334 i
+= 2; /* command-line option with argument. ignore them. */
1336 } else if (!strcmp(argv
[i
],"--list-fingerprint") ||
1337 !strcmp(argv
[i
],"--verify-config") ||
1338 !strcmp(argv
[i
],"--ignore-missing-torrc") ||
1339 !strcmp(argv
[i
],"--quiet")) {
1340 i
+= 1; /* command-line option. ignore it. */
1342 } else if (!strcmp(argv
[i
],"--nt-service") ||
1343 !strcmp(argv
[i
],"-nt-service")) {
1349 log_warn(LD_CONFIG
,"Command-line option '%s' with no value. Failing.",
1351 config_free_lines(front
);
1355 *new = tor_malloc_zero(sizeof(config_line_t
));
1361 (*new)->key
= tor_strdup(expand_abbrev(&options_format
, s
, 1, 1));
1362 (*new)->value
= tor_strdup(argv
[i
+1]);
1363 (*new)->next
= NULL
;
1364 log(LOG_DEBUG
, LD_CONFIG
, "Commandline: parsed keyword '%s', value '%s'",
1365 (*new)->key
, (*new)->value
);
1367 new = &((*new)->next
);
1374 /** Helper: allocate a new configuration option mapping 'key' to 'val',
1375 * append it to *<b>lst</b>. */
1377 config_line_append(config_line_t
**lst
,
1381 config_line_t
*newline
;
1383 newline
= tor_malloc(sizeof(config_line_t
));
1384 newline
->key
= tor_strdup(key
);
1385 newline
->value
= tor_strdup(val
);
1386 newline
->next
= NULL
;
1388 lst
= &((*lst
)->next
);
1393 /** Helper: parse the config string and strdup into key/value
1394 * strings. Set *result to the list, or NULL if parsing the string
1395 * failed. Return 0 on success, -1 on failure. Warn and ignore any
1396 * misformatted lines. */
1398 config_get_lines(const char *string
, config_line_t
**result
)
1400 config_line_t
*list
= NULL
, **next
;
1405 string
= parse_config_line_from_str(string
, &k
, &v
);
1407 config_free_lines(list
);
1411 /* This list can get long, so we keep a pointer to the end of it
1412 * rather than using config_line_append over and over and getting
1413 * n^2 performance. */
1414 *next
= tor_malloc(sizeof(config_line_t
));
1417 (*next
)->next
= NULL
;
1418 next
= &((*next
)->next
);
1430 * Free all the configuration lines on the linked list <b>front</b>.
1433 config_free_lines(config_line_t
*front
)
1442 tor_free(tmp
->value
);
1447 /** Return the description for a given configuration variable, or NULL if no
1448 * description exists. */
1450 config_find_description(config_format_t
*fmt
, const char *name
)
1453 for (i
=0; fmt
->descriptions
[i
].name
; ++i
) {
1454 if (!strcasecmp(name
, fmt
->descriptions
[i
].name
))
1455 return fmt
->descriptions
[i
].description
;
1460 /** If <b>key</b> is a configuration option, return the corresponding
1461 * config_var_t. Otherwise, if <b>key</b> is a non-standard abbreviation,
1462 * warn, and return the corresponding config_var_t. Otherwise return NULL.
1464 static config_var_t
*
1465 config_find_option(config_format_t
*fmt
, const char *key
)
1468 size_t keylen
= strlen(key
);
1470 return NULL
; /* if they say "--" on the commandline, it's not an option */
1471 /* First, check for an exact (case-insensitive) match */
1472 for (i
=0; fmt
->vars
[i
].name
; ++i
) {
1473 if (!strcasecmp(key
, fmt
->vars
[i
].name
)) {
1474 return &fmt
->vars
[i
];
1477 /* If none, check for an abbreviated match */
1478 for (i
=0; fmt
->vars
[i
].name
; ++i
) {
1479 if (!strncasecmp(key
, fmt
->vars
[i
].name
, keylen
)) {
1480 log_warn(LD_CONFIG
, "The abbreviation '%s' is deprecated. "
1481 "Please use '%s' instead",
1482 key
, fmt
->vars
[i
].name
);
1483 return &fmt
->vars
[i
];
1486 /* Okay, unrecognized option */
1491 * Functions to assign config options.
1494 /** <b>c</b>-\>key is known to be a real key. Update <b>options</b>
1495 * with <b>c</b>-\>value and return 0, or return -1 if bad value.
1497 * Called from config_assign_line() and option_reset().
1500 config_assign_value(config_format_t
*fmt
, or_options_t
*options
,
1501 config_line_t
*c
, char **msg
)
1508 CHECK(fmt
, options
);
1510 var
= config_find_option(fmt
, c
->key
);
1513 lvalue
= STRUCT_VAR_P(options
, var
->var_offset
);
1515 switch (var
->type
) {
1517 case CONFIG_TYPE_UINT
:
1518 i
= (int)tor_parse_long(c
->value
, 10, 0, INT_MAX
, &ok
, NULL
);
1520 r
= tor_snprintf(buf
, sizeof(buf
),
1521 "Int keyword '%s %s' is malformed or out of bounds.",
1523 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
1529 case CONFIG_TYPE_INTERVAL
: {
1530 i
= config_parse_interval(c
->value
, &ok
);
1532 r
= tor_snprintf(buf
, sizeof(buf
),
1533 "Interval '%s %s' is malformed or out of bounds.",
1535 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
1542 case CONFIG_TYPE_MEMUNIT
: {
1543 uint64_t u64
= config_parse_memunit(c
->value
, &ok
);
1545 r
= tor_snprintf(buf
, sizeof(buf
),
1546 "Value '%s %s' is malformed or out of bounds.",
1548 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
1551 *(uint64_t *)lvalue
= u64
;
1555 case CONFIG_TYPE_BOOL
:
1556 i
= (int)tor_parse_long(c
->value
, 10, 0, 1, &ok
, NULL
);
1558 r
= tor_snprintf(buf
, sizeof(buf
),
1559 "Boolean '%s %s' expects 0 or 1.",
1561 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
1567 case CONFIG_TYPE_STRING
:
1568 tor_free(*(char **)lvalue
);
1569 *(char **)lvalue
= tor_strdup(c
->value
);
1572 case CONFIG_TYPE_DOUBLE
:
1573 *(double *)lvalue
= atof(c
->value
);
1576 case CONFIG_TYPE_ISOTIME
:
1577 if (parse_iso_time(c
->value
, (time_t *)lvalue
)) {
1578 r
= tor_snprintf(buf
, sizeof(buf
),
1579 "Invalid time '%s' for keyword '%s'", c
->value
, c
->key
);
1580 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
1585 case CONFIG_TYPE_CSV
:
1586 if (*(smartlist_t
**)lvalue
) {
1587 SMARTLIST_FOREACH(*(smartlist_t
**)lvalue
, char *, cp
, tor_free(cp
));
1588 smartlist_clear(*(smartlist_t
**)lvalue
);
1590 *(smartlist_t
**)lvalue
= smartlist_create();
1593 smartlist_split_string(*(smartlist_t
**)lvalue
, c
->value
, ",",
1594 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1597 case CONFIG_TYPE_LINELIST
:
1598 case CONFIG_TYPE_LINELIST_S
:
1599 config_line_append((config_line_t
**)lvalue
, c
->key
, c
->value
);
1602 case CONFIG_TYPE_OBSOLETE
:
1603 log_warn(LD_CONFIG
, "Skipping obsolete configuration option '%s'", c
->key
);
1605 case CONFIG_TYPE_LINELIST_V
:
1606 r
= tor_snprintf(buf
, sizeof(buf
),
1607 "You may not provide a value for virtual option '%s'", c
->key
);
1608 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
1617 /** If <b>c</b> is a syntactically valid configuration line, update
1618 * <b>options</b> with its value and return 0. Otherwise return -1 for bad
1619 * key, -2 for bad value.
1621 * If <b>clear_first</b> is set, clear the value first. Then if
1622 * <b>use_defaults</b> is set, set the value to the default.
1624 * Called from config_assign().
1627 config_assign_line(config_format_t
*fmt
, or_options_t
*options
,
1628 config_line_t
*c
, int use_defaults
,
1629 int clear_first
, char **msg
)
1633 CHECK(fmt
, options
);
1635 var
= config_find_option(fmt
, c
->key
);
1638 void *lvalue
= STRUCT_VAR_P(options
, fmt
->extra
->var_offset
);
1640 "Found unrecognized option '%s'; saving it.", c
->key
);
1641 config_line_append((config_line_t
**)lvalue
, c
->key
, c
->value
);
1645 int tmp
= tor_snprintf(buf
, sizeof(buf
),
1646 "Unknown option '%s'. Failing.", c
->key
);
1647 *msg
= tor_strdup(tmp
>= 0 ? buf
: "internal error");
1651 /* Put keyword into canonical case. */
1652 if (strcmp(var
->name
, c
->key
)) {
1654 c
->key
= tor_strdup(var
->name
);
1657 if (!strlen(c
->value
)) {
1658 /* reset or clear it, then return */
1660 if (var
->type
== CONFIG_TYPE_LINELIST
||
1661 var
->type
== CONFIG_TYPE_LINELIST_S
) {
1662 /* We got an empty linelist from the torrc or commandline.
1663 As a special case, call this an error. Warn and ignore. */
1665 "Linelist option '%s' has no value. Skipping.", c
->key
);
1666 } else { /* not already cleared */
1667 option_reset(fmt
, options
, var
, use_defaults
);
1673 if (config_assign_value(fmt
, options
, c
, msg
) < 0)
1678 /** Restore the option named <b>key</b> in options to its default value.
1679 * Called from config_assign(). */
1681 config_reset_line(config_format_t
*fmt
, or_options_t
*options
,
1682 const char *key
, int use_defaults
)
1686 CHECK(fmt
, options
);
1688 var
= config_find_option(fmt
, key
);
1690 return; /* give error on next pass. */
1692 option_reset(fmt
, options
, var
, use_defaults
);
1695 /** Return true iff key is a valid configuration option. */
1697 option_is_recognized(const char *key
)
1699 config_var_t
*var
= config_find_option(&options_format
, key
);
1700 return (var
!= NULL
);
1703 /** Return the canonical name of a configuration option, or NULL
1704 * if no such option exists. */
1706 option_get_canonical_name(const char *key
)
1708 config_var_t
*var
= config_find_option(&options_format
, key
);
1709 return var
? var
->name
: NULL
;
1712 /** Return a canonicalized list of the options assigned for key.
1715 option_get_assignment(or_options_t
*options
, const char *key
)
1717 return get_assigned_option(&options_format
, options
, key
, 1);
1720 /** Return true iff value needs to be quoted and escaped to be used in
1721 * a configuration file. */
1723 config_value_needs_escape(const char *value
)
1733 /* Note: quotes and backspaces need special handling when we are using
1734 * quotes, not otherwise, so they don't trigger escaping on their
1738 if (!TOR_ISPRINT(*value
))
1746 /** Return a newly allocated deep copy of the lines in <b>inp</b>. */
1747 static config_line_t
*
1748 config_lines_dup(const config_line_t
*inp
)
1750 config_line_t
*result
= NULL
;
1751 config_line_t
**next_out
= &result
;
1753 *next_out
= tor_malloc(sizeof(config_line_t
));
1754 (*next_out
)->key
= tor_strdup(inp
->key
);
1755 (*next_out
)->value
= tor_strdup(inp
->value
);
1757 next_out
= &((*next_out
)->next
);
1763 /** Return newly allocated line or lines corresponding to <b>key</b> in the
1764 * configuration <b>options</b>. If <b>escape_val</b> is true and a
1765 * value needs to be quoted before it's put in a config file, quote and
1766 * escape that value. Return NULL if no such key exists. */
1767 static config_line_t
*
1768 get_assigned_option(config_format_t
*fmt
, or_options_t
*options
,
1769 const char *key
, int escape_val
)
1770 /* XXXX argument is options, but fmt is provided. Inconsistent. */
1775 config_line_t
*result
;
1776 tor_assert(options
&& key
);
1778 CHECK(fmt
, options
);
1780 var
= config_find_option(fmt
, key
);
1782 log_warn(LD_CONFIG
, "Unknown option '%s'. Failing.", key
);
1785 value
= STRUCT_VAR_P(options
, var
->var_offset
);
1787 result
= tor_malloc_zero(sizeof(config_line_t
));
1788 result
->key
= tor_strdup(var
->name
);
1791 case CONFIG_TYPE_STRING
:
1792 if (*(char**)value
) {
1793 result
->value
= tor_strdup(*(char**)value
);
1795 tor_free(result
->key
);
1800 case CONFIG_TYPE_ISOTIME
:
1801 if (*(time_t*)value
) {
1802 result
->value
= tor_malloc(ISO_TIME_LEN
+1);
1803 format_iso_time(result
->value
, *(time_t*)value
);
1805 tor_free(result
->key
);
1808 escape_val
= 0; /* Can't need escape. */
1810 case CONFIG_TYPE_INTERVAL
:
1811 case CONFIG_TYPE_UINT
:
1812 /* This means every or_options_t uint or bool element
1813 * needs to be an int. Not, say, a uint16_t or char. */
1814 tor_snprintf(buf
, sizeof(buf
), "%d", *(int*)value
);
1815 result
->value
= tor_strdup(buf
);
1816 escape_val
= 0; /* Can't need escape. */
1818 case CONFIG_TYPE_MEMUNIT
:
1819 tor_snprintf(buf
, sizeof(buf
), U64_FORMAT
,
1820 U64_PRINTF_ARG(*(uint64_t*)value
));
1821 result
->value
= tor_strdup(buf
);
1822 escape_val
= 0; /* Can't need escape. */
1824 case CONFIG_TYPE_DOUBLE
:
1825 tor_snprintf(buf
, sizeof(buf
), "%f", *(double*)value
);
1826 result
->value
= tor_strdup(buf
);
1827 escape_val
= 0; /* Can't need escape. */
1829 case CONFIG_TYPE_BOOL
:
1830 result
->value
= tor_strdup(*(int*)value
? "1" : "0");
1831 escape_val
= 0; /* Can't need escape. */
1833 case CONFIG_TYPE_CSV
:
1834 if (*(smartlist_t
**)value
)
1836 smartlist_join_strings(*(smartlist_t
**)value
, ",", 0, NULL
);
1838 result
->value
= tor_strdup("");
1840 case CONFIG_TYPE_OBSOLETE
:
1842 "You asked me for the value of an obsolete config option '%s'.",
1844 tor_free(result
->key
);
1847 case CONFIG_TYPE_LINELIST_S
:
1849 "Can't return context-sensitive '%s' on its own", key
);
1850 tor_free(result
->key
);
1853 case CONFIG_TYPE_LINELIST
:
1854 case CONFIG_TYPE_LINELIST_V
:
1855 tor_free(result
->key
);
1857 result
= config_lines_dup(*(const config_line_t
**)value
);
1860 tor_free(result
->key
);
1862 log_warn(LD_BUG
,"Unknown type %d for known key '%s'",
1868 config_line_t
*line
;
1869 for (line
= result
; line
; line
= line
->next
) {
1870 if (line
->value
&& config_value_needs_escape(line
->value
)) {
1871 char *newval
= esc_for_log(line
->value
);
1872 tor_free(line
->value
);
1873 line
->value
= newval
;
1881 /** Iterate through the linked list of requested options <b>list</b>.
1882 * For each item, convert as appropriate and assign to <b>options</b>.
1883 * If an item is unrecognized, set *msg and return -1 immediately,
1884 * else return 0 for success.
1886 * If <b>clear_first</b>, interpret config options as replacing (not
1887 * extending) their previous values. If <b>clear_first</b> is set,
1888 * then <b>use_defaults</b> to decide if you set to defaults after
1889 * clearing, or make the value 0 or NULL.
1891 * Here are the use cases:
1892 * 1. A non-empty AllowInvalid line in your torrc. Appends to current
1893 * if linelist, replaces current if csv.
1894 * 2. An empty AllowInvalid line in your torrc. Should clear it.
1895 * 3. "RESETCONF AllowInvalid" sets it to default.
1896 * 4. "SETCONF AllowInvalid" makes it NULL.
1897 * 5. "SETCONF AllowInvalid=foo" clears it and sets it to "foo".
1899 * Use_defaults Clear_first
1901 * 1 0 undefined, don't use
1902 * 0 1 "set to null first"
1903 * 1 1 "set to defaults first"
1904 * Return 0 on success, -1 on bad key, -2 on bad value.
1906 * As an additional special case, if a LINELIST config option has
1907 * no value and clear_first is 0, then warn and ignore it.
1911 There are three call cases for config_assign() currently.
1913 Case one: Torrc entry
1914 options_init_from_torrc() calls config_assign(0, 0)
1915 calls config_assign_line(0, 0).
1916 if value is empty, calls option_reset(0) and returns.
1917 calls config_assign_value(), appends.
1920 options_trial_assign() calls config_assign(0, 1)
1921 calls config_reset_line(0)
1922 calls option_reset(0)
1923 calls option_clear().
1924 calls config_assign_line(0, 1).
1925 if value is empty, returns.
1926 calls config_assign_value(), appends.
1928 Case three: resetconf
1929 options_trial_assign() calls config_assign(1, 1)
1930 calls config_reset_line(1)
1931 calls option_reset(1)
1932 calls option_clear().
1933 calls config_assign_value(default)
1934 calls config_assign_line(1, 1).
1938 config_assign(config_format_t
*fmt
, void *options
, config_line_t
*list
,
1939 int use_defaults
, int clear_first
, char **msg
)
1943 CHECK(fmt
, options
);
1945 /* pass 1: normalize keys */
1946 for (p
= list
; p
; p
= p
->next
) {
1947 const char *full
= expand_abbrev(fmt
, p
->key
, 0, 1);
1948 if (strcmp(full
,p
->key
)) {
1950 p
->key
= tor_strdup(full
);
1954 /* pass 2: if we're reading from a resetting source, clear all
1955 * mentioned config options, and maybe set to their defaults. */
1957 for (p
= list
; p
; p
= p
->next
)
1958 config_reset_line(fmt
, options
, p
->key
, use_defaults
);
1961 /* pass 3: assign. */
1964 if ((r
=config_assign_line(fmt
, options
, list
, use_defaults
,
1972 /** Try assigning <b>list</b> to the global options. You do this by duping
1973 * options, assigning list to the new one, then validating it. If it's
1974 * ok, then throw out the old one and stick with the new one. Else,
1975 * revert to old and return failure. Return 0 on success, -1 on bad
1976 * keys, -2 on bad values, -3 on bad transition, and -4 on failed-to-set.
1978 * If not success, point *<b>msg</b> to a newly allocated string describing
1982 options_trial_assign(config_line_t
*list
, int use_defaults
,
1983 int clear_first
, char **msg
)
1986 or_options_t
*trial_options
= options_dup(&options_format
, get_options());
1988 if ((r
=config_assign(&options_format
, trial_options
,
1989 list
, use_defaults
, clear_first
, msg
)) < 0) {
1990 config_free(&options_format
, trial_options
);
1994 if (options_validate(get_options(), trial_options
, 1, msg
) < 0) {
1995 config_free(&options_format
, trial_options
);
1999 if (options_transition_allowed(get_options(), trial_options
, msg
) < 0) {
2000 config_free(&options_format
, trial_options
);
2004 if (set_options(trial_options
, msg
)<0) {
2005 config_free(&options_format
, trial_options
);
2009 /* we liked it. put it in place. */
2013 /** Reset config option <b>var</b> to 0, 0.0, NULL, or the equivalent.
2014 * Called from option_reset() and config_free(). */
2016 option_clear(config_format_t
*fmt
, or_options_t
*options
, config_var_t
*var
)
2018 void *lvalue
= STRUCT_VAR_P(options
, var
->var_offset
);
2019 (void)fmt
; /* unused */
2020 switch (var
->type
) {
2021 case CONFIG_TYPE_STRING
:
2022 tor_free(*(char**)lvalue
);
2024 case CONFIG_TYPE_DOUBLE
:
2025 *(double*)lvalue
= 0.0;
2027 case CONFIG_TYPE_ISOTIME
:
2028 *(time_t*)lvalue
= 0;
2029 case CONFIG_TYPE_INTERVAL
:
2030 case CONFIG_TYPE_UINT
:
2031 case CONFIG_TYPE_BOOL
:
2034 case CONFIG_TYPE_MEMUNIT
:
2035 *(uint64_t*)lvalue
= 0;
2037 case CONFIG_TYPE_CSV
:
2038 if (*(smartlist_t
**)lvalue
) {
2039 SMARTLIST_FOREACH(*(smartlist_t
**)lvalue
, char *, cp
, tor_free(cp
));
2040 smartlist_free(*(smartlist_t
**)lvalue
);
2041 *(smartlist_t
**)lvalue
= NULL
;
2044 case CONFIG_TYPE_LINELIST
:
2045 case CONFIG_TYPE_LINELIST_S
:
2046 config_free_lines(*(config_line_t
**)lvalue
);
2047 *(config_line_t
**)lvalue
= NULL
;
2049 case CONFIG_TYPE_LINELIST_V
:
2050 /* handled by linelist_s. */
2052 case CONFIG_TYPE_OBSOLETE
:
2057 /** Clear the option indexed by <b>var</b> in <b>options</b>. Then if
2058 * <b>use_defaults</b>, set it to its default value.
2059 * Called by config_init() and option_reset_line() and option_assign_line(). */
2061 option_reset(config_format_t
*fmt
, or_options_t
*options
,
2062 config_var_t
*var
, int use_defaults
)
2066 CHECK(fmt
, options
);
2067 option_clear(fmt
, options
, var
); /* clear it first */
2069 return; /* all done */
2070 if (var
->initvalue
) {
2071 c
= tor_malloc_zero(sizeof(config_line_t
));
2072 c
->key
= tor_strdup(var
->name
);
2073 c
->value
= tor_strdup(var
->initvalue
);
2074 if (config_assign_value(fmt
, options
, c
, &msg
) < 0) {
2075 log_warn(LD_BUG
, "Failed to assign default: %s", msg
);
2076 tor_free(msg
); /* if this happens it's a bug */
2078 config_free_lines(c
);
2082 /** Print a usage message for tor. */
2087 "Copyright (c) 2001-2004, Roger Dingledine\n"
2088 "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
2089 "Copyright (c) 2007-2008, The Tor Project, Inc.\n\n"
2090 "tor -f <torrc> [args]\n"
2091 "See man page for options, or https://www.torproject.org/ for "
2092 "documentation.\n");
2095 /** Print all non-obsolete torrc options. */
2097 list_torrc_options(void)
2100 smartlist_t
*lines
= smartlist_create();
2101 for (i
= 0; _option_vars
[i
].name
; ++i
) {
2102 config_var_t
*var
= &_option_vars
[i
];
2104 if (var
->type
== CONFIG_TYPE_OBSOLETE
||
2105 var
->type
== CONFIG_TYPE_LINELIST_V
)
2107 desc
= config_find_description(&options_format
, var
->name
);
2108 printf("%s\n", var
->name
);
2110 wrap_string(lines
, desc
, 76, " ", " ");
2111 SMARTLIST_FOREACH(lines
, char *, cp
, {
2115 smartlist_clear(lines
);
2118 smartlist_free(lines
);
2121 /** Last value actually set by resolve_my_address. */
2122 static uint32_t last_resolved_addr
= 0;
2124 * Based on <b>options-\>Address</b>, guess our public IP address and put it
2125 * (in host order) into *<b>addr_out</b>. If <b>hostname_out</b> is provided,
2126 * set *<b>hostname_out</b> to a new string holding the hostname we used to
2127 * get the address. Return 0 if all is well, or -1 if we can't find a suitable
2128 * public IP address.
2131 resolve_my_address(int warn_severity
, or_options_t
*options
,
2132 uint32_t *addr_out
, char **hostname_out
)
2135 struct hostent
*rent
;
2138 int explicit_hostname
=1;
2139 int from_interface
=0;
2140 char tmpbuf
[INET_NTOA_BUF_LEN
];
2141 const char *address
= options
->Address
;
2142 int notice_severity
= warn_severity
<= LOG_NOTICE
?
2143 LOG_NOTICE
: warn_severity
;
2145 tor_assert(addr_out
);
2147 if (address
&& *address
) {
2148 strlcpy(hostname
, address
, sizeof(hostname
));
2149 } else { /* then we need to guess our address */
2150 explicit_ip
= 0; /* it's implicit */
2151 explicit_hostname
= 0; /* it's implicit */
2153 if (gethostname(hostname
, sizeof(hostname
)) < 0) {
2154 log_fn(warn_severity
, LD_NET
,"Error obtaining local hostname");
2157 log_debug(LD_CONFIG
,"Guessed local host name as '%s'",hostname
);
2160 /* now we know hostname. resolve it and keep only the IP address */
2162 if (tor_inet_aton(hostname
, &in
) == 0) {
2163 /* then we have to resolve it */
2165 rent
= (struct hostent
*)gethostbyname(hostname
);
2167 uint32_t interface_ip
;
2169 if (explicit_hostname
) {
2170 log_fn(warn_severity
, LD_CONFIG
,
2171 "Could not resolve local Address '%s'. Failing.", hostname
);
2174 log_fn(notice_severity
, LD_CONFIG
,
2175 "Could not resolve guessed local hostname '%s'. "
2176 "Trying something else.", hostname
);
2177 if (get_interface_address(warn_severity
, &interface_ip
)) {
2178 log_fn(warn_severity
, LD_CONFIG
,
2179 "Could not get local interface IP address. Failing.");
2183 in
.s_addr
= htonl(interface_ip
);
2184 tor_inet_ntoa(&in
,tmpbuf
,sizeof(tmpbuf
));
2185 log_fn(notice_severity
, LD_CONFIG
, "Learned IP address '%s' for "
2186 "local interface. Using that.", tmpbuf
);
2187 strlcpy(hostname
, "<guessed from interfaces>", sizeof(hostname
));
2189 tor_assert(rent
->h_length
== 4);
2190 memcpy(&in
.s_addr
, rent
->h_addr
, rent
->h_length
);
2192 if (!explicit_hostname
&&
2193 is_internal_IP(ntohl(in
.s_addr
), 0)) {
2194 uint32_t interface_ip
;
2196 tor_inet_ntoa(&in
,tmpbuf
,sizeof(tmpbuf
));
2197 log_fn(notice_severity
, LD_CONFIG
, "Guessed local hostname '%s' "
2198 "resolves to a private IP address (%s). Trying something "
2199 "else.", hostname
, tmpbuf
);
2201 if (get_interface_address(warn_severity
, &interface_ip
)) {
2202 log_fn(warn_severity
, LD_CONFIG
,
2203 "Could not get local interface IP address. Too bad.");
2204 } else if (is_internal_IP(interface_ip
, 0)) {
2206 in2
.s_addr
= htonl(interface_ip
);
2207 tor_inet_ntoa(&in2
,tmpbuf
,sizeof(tmpbuf
));
2208 log_fn(notice_severity
, LD_CONFIG
,
2209 "Interface IP address '%s' is a private address too. "
2210 "Ignoring.", tmpbuf
);
2213 in
.s_addr
= htonl(interface_ip
);
2214 tor_inet_ntoa(&in
,tmpbuf
,sizeof(tmpbuf
));
2215 log_fn(notice_severity
, LD_CONFIG
,
2216 "Learned IP address '%s' for local interface."
2217 " Using that.", tmpbuf
);
2218 strlcpy(hostname
, "<guessed from interfaces>", sizeof(hostname
));
2224 tor_inet_ntoa(&in
,tmpbuf
,sizeof(tmpbuf
));
2225 if (is_internal_IP(ntohl(in
.s_addr
), 0) &&
2226 options
->_PublishServerDescriptor
) {
2227 /* make sure we're ok with publishing an internal IP */
2228 if (!options
->DirServers
&& !options
->AlternateDirAuthority
) {
2229 /* if they are using the default dirservers, disallow internal IPs
2231 log_fn(warn_severity
, LD_CONFIG
,
2232 "Address '%s' resolves to private IP address '%s'. "
2233 "Tor servers that use the default DirServers must have public "
2234 "IP addresses.", hostname
, tmpbuf
);
2238 /* even if they've set their own dirservers, require an explicit IP if
2239 * they're using an internal address. */
2240 log_fn(warn_severity
, LD_CONFIG
, "Address '%s' resolves to private "
2241 "IP address '%s'. Please set the Address config option to be "
2242 "the IP address you want to use.", hostname
, tmpbuf
);
2247 log_debug(LD_CONFIG
, "Resolved Address to '%s'.", tmpbuf
);
2248 *addr_out
= ntohl(in
.s_addr
);
2249 if (last_resolved_addr
&& last_resolved_addr
!= *addr_out
) {
2250 /* Leave this as a notice, regardless of the requested severity,
2251 * at least until dynamic IP address support becomes bulletproof. */
2253 "Your IP address seems to have changed to %s. Updating.",
2255 ip_address_changed(0);
2257 if (last_resolved_addr
!= *addr_out
) {
2259 const char *h
= hostname
;
2261 method
= "CONFIGURED";
2263 } else if (explicit_hostname
) {
2264 method
= "RESOLVED";
2265 } else if (from_interface
) {
2266 method
= "INTERFACE";
2269 method
= "GETHOSTNAME";
2271 control_event_server_status(LOG_NOTICE
,
2272 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s %s%s",
2273 tmpbuf
, method
, h
?"HOSTNAME=":"", h
);
2275 last_resolved_addr
= *addr_out
;
2277 *hostname_out
= tor_strdup(hostname
);
2281 /** Return true iff <b>ip</b> (in host order) is judged to be on the
2282 * same network as us, or on a private network.
2285 is_local_IP(uint32_t ip
)
2287 if (is_internal_IP(ip
, 0))
2289 /* Check whether ip is on the same /24 as we are. */
2290 if (get_options()->EnforceDistinctSubnets
== 0)
2292 /* It's possible that this next check will hit before the first time
2293 * resolve_my_address actually succeeds. (For clients, it is likely that
2294 * resolve_my_address will never be called at all). In those cases,
2295 * last_resolved_addr will be 0, and so checking to see whether ip is on the
2296 * same /24 as last_resolved_addr will be the same as checking whether it
2297 * was on net 0, which is already done by is_internal_IP.
2299 if ((last_resolved_addr
& 0xffffff00ul
) == (ip
& 0xffffff00ul
))
2304 /** Called when we don't have a nickname set. Try to guess a good nickname
2305 * based on the hostname, and return it in a newly allocated string. If we
2306 * can't, return NULL and let the caller warn if it wants to. */
2308 get_default_nickname(void)
2310 static const char * const bad_default_nicknames
[] = {
2314 char localhostname
[256];
2315 char *cp
, *out
, *outp
;
2318 if (gethostname(localhostname
, sizeof(localhostname
)) < 0)
2321 /* Put it in lowercase; stop at the first dot. */
2322 if ((cp
= strchr(localhostname
, '.')))
2324 tor_strlower(localhostname
);
2326 /* Strip invalid characters. */
2328 out
= outp
= tor_malloc(strlen(localhostname
) + 1);
2330 if (strchr(LEGAL_NICKNAME_CHARACTERS
, *cp
))
2337 /* Enforce length. */
2338 if (strlen(out
) > MAX_NICKNAME_LEN
)
2339 out
[MAX_NICKNAME_LEN
]='\0';
2341 /* Check for dumb names. */
2342 for (i
= 0; bad_default_nicknames
[i
]; ++i
) {
2343 if (!strcmp(out
, bad_default_nicknames
[i
])) {
2352 /** Release storage held by <b>options</b>. */
2354 config_free(config_format_t
*fmt
, void *options
)
2358 tor_assert(options
);
2360 for (i
=0; fmt
->vars
[i
].name
; ++i
)
2361 option_clear(fmt
, options
, &(fmt
->vars
[i
]));
2363 config_line_t
**linep
= STRUCT_VAR_P(options
, fmt
->extra
->var_offset
);
2364 config_free_lines(*linep
);
2370 /** Return true iff a and b contain identical keys and values in identical
2373 config_lines_eq(config_line_t
*a
, config_line_t
*b
)
2376 if (strcasecmp(a
->key
, b
->key
) || strcmp(a
->value
, b
->value
))
2386 /** Return true iff the option <b>name</b> has the same value in <b>o1</b>
2387 * and <b>o2</b>. Must not be called for LINELIST_S or OBSOLETE options.
2390 option_is_same(config_format_t
*fmt
,
2391 or_options_t
*o1
, or_options_t
*o2
, const char *name
)
2393 config_line_t
*c1
, *c2
;
2398 c1
= get_assigned_option(fmt
, o1
, name
, 0);
2399 c2
= get_assigned_option(fmt
, o2
, name
, 0);
2400 r
= config_lines_eq(c1
, c2
);
2401 config_free_lines(c1
);
2402 config_free_lines(c2
);
2406 /** Copy storage held by <b>old</b> into a new or_options_t and return it. */
2407 static or_options_t
*
2408 options_dup(config_format_t
*fmt
, or_options_t
*old
)
2410 or_options_t
*newopts
;
2412 config_line_t
*line
;
2414 newopts
= config_alloc(fmt
);
2415 for (i
=0; fmt
->vars
[i
].name
; ++i
) {
2416 if (fmt
->vars
[i
].type
== CONFIG_TYPE_LINELIST_S
)
2418 if (fmt
->vars
[i
].type
== CONFIG_TYPE_OBSOLETE
)
2420 line
= get_assigned_option(fmt
, old
, fmt
->vars
[i
].name
, 0);
2423 if (config_assign(fmt
, newopts
, line
, 0, 0, &msg
) < 0) {
2424 log_err(LD_BUG
, "Config_get_assigned_option() generated "
2425 "something we couldn't config_assign(): %s", msg
);
2430 config_free_lines(line
);
2435 /** Return a new empty or_options_t. Used for testing. */
2439 return config_alloc(&options_format
);
2442 /** Set <b>options</b> to hold reasonable defaults for most options.
2443 * Each option defaults to zero. */
2445 options_init(or_options_t
*options
)
2447 config_init(&options_format
, options
);
2450 /** Set all vars in the configuration object <b>options</b> to their default
2453 config_init(config_format_t
*fmt
, void *options
)
2457 CHECK(fmt
, options
);
2459 for (i
=0; fmt
->vars
[i
].name
; ++i
) {
2460 var
= &fmt
->vars
[i
];
2461 if (!var
->initvalue
)
2462 continue; /* defaults to NULL or 0 */
2463 option_reset(fmt
, options
, var
, 1);
2467 /** Allocate and return a new string holding the written-out values of the vars
2468 * in 'options'. If 'minimal', do not write out any default-valued vars.
2469 * Else, if comment_defaults, write default values as comments.
2472 config_dump(config_format_t
*fmt
, void *options
, int minimal
,
2473 int comment_defaults
)
2475 smartlist_t
*elements
;
2476 or_options_t
*defaults
;
2477 config_line_t
*line
, *assigned
;
2483 defaults
= config_alloc(fmt
);
2484 config_init(fmt
, defaults
);
2486 /* XXX use a 1 here so we don't add a new log line while dumping */
2487 if (fmt
->validate_fn(NULL
,defaults
, 1, &msg
) < 0) {
2488 log_err(LD_BUG
, "Failed to validate default config.");
2493 elements
= smartlist_create();
2494 for (i
=0; fmt
->vars
[i
].name
; ++i
) {
2495 int comment_option
= 0;
2496 if (fmt
->vars
[i
].type
== CONFIG_TYPE_OBSOLETE
||
2497 fmt
->vars
[i
].type
== CONFIG_TYPE_LINELIST_S
)
2499 /* Don't save 'hidden' control variables. */
2500 if (!strcmpstart(fmt
->vars
[i
].name
, "__"))
2502 if (minimal
&& option_is_same(fmt
, options
, defaults
, fmt
->vars
[i
].name
))
2504 else if (comment_defaults
&&
2505 option_is_same(fmt
, options
, defaults
, fmt
->vars
[i
].name
))
2508 desc
= config_find_description(fmt
, fmt
->vars
[i
].name
);
2509 line
= assigned
= get_assigned_option(fmt
, options
, fmt
->vars
[i
].name
, 1);
2512 /* Only dump the description if there's something to describe. */
2513 wrap_string(elements
, desc
, 78, "# ", "# ");
2516 for (; line
; line
= line
->next
) {
2517 size_t len
= strlen(line
->key
) + strlen(line
->value
) + 5;
2519 tmp
= tor_malloc(len
);
2520 if (tor_snprintf(tmp
, len
, "%s%s %s\n",
2521 comment_option
? "# " : "",
2522 line
->key
, line
->value
)<0) {
2523 log_err(LD_BUG
,"Internal error writing option value");
2526 smartlist_add(elements
, tmp
);
2528 config_free_lines(assigned
);
2532 line
= *(config_line_t
**)STRUCT_VAR_P(options
, fmt
->extra
->var_offset
);
2533 for (; line
; line
= line
->next
) {
2534 size_t len
= strlen(line
->key
) + strlen(line
->value
) + 3;
2536 tmp
= tor_malloc(len
);
2537 if (tor_snprintf(tmp
, len
, "%s %s\n", line
->key
, line
->value
)<0) {
2538 log_err(LD_BUG
,"Internal error writing option value");
2541 smartlist_add(elements
, tmp
);
2545 result
= smartlist_join_strings(elements
, "", 0, NULL
);
2546 SMARTLIST_FOREACH(elements
, char *, cp
, tor_free(cp
));
2547 smartlist_free(elements
);
2548 config_free(fmt
, defaults
);
2552 /** Return a string containing a possible configuration file that would give
2553 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
2554 * include options that are the same as Tor's defaults.
2557 options_dump(or_options_t
*options
, int minimal
)
2559 return config_dump(&options_format
, options
, minimal
, 0);
2562 /** Return 0 if every element of sl is a string holding a decimal
2563 * representation of a port number, or if sl is NULL.
2564 * Otherwise set *msg and return -1. */
2566 validate_ports_csv(smartlist_t
*sl
, const char *name
, char **msg
)
2575 SMARTLIST_FOREACH(sl
, const char *, cp
,
2578 if (i
< 1 || i
> 65535) {
2579 int r
= tor_snprintf(buf
, sizeof(buf
),
2580 "Port '%s' out of range in %s", cp
, name
);
2581 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
2588 /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
2589 * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
2593 ensure_bandwidth_cap(uint64_t *value
, const char *desc
, char **msg
)
2597 if (*value
> ROUTER_MAX_DECLARED_BANDWIDTH
) {
2598 /* This handles an understandable special case where somebody says "2gb"
2599 * whereas our actual maximum is 2gb-1 (INT_MAX) */
2602 if (*value
> ROUTER_MAX_DECLARED_BANDWIDTH
) {
2603 r
= tor_snprintf(buf
, sizeof(buf
), "%s ("U64_FORMAT
") must be at most %d",
2604 desc
, U64_PRINTF_ARG(*value
),
2605 ROUTER_MAX_DECLARED_BANDWIDTH
);
2606 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
2612 /** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
2613 * and write it to <b>options</b>-\>_PublishServerDescriptor. Treat "1"
2614 * as "v2,v3" unless BridgeRelay is 1, in which case treat it as "bridge".
2616 * Return 0 on success or -1 if not a recognized authority type (in which
2617 * case the value of _PublishServerDescriptor is undefined). */
2619 compute_publishserverdescriptor(or_options_t
*options
)
2621 smartlist_t
*list
= options
->PublishServerDescriptor
;
2622 authority_type_t
*auth
= &options
->_PublishServerDescriptor
;
2623 *auth
= NO_AUTHORITY
;
2624 if (!list
) /* empty list, answer is none */
2626 SMARTLIST_FOREACH(list
, const char *, string
, {
2627 if (!strcasecmp(string
, "v1"))
2628 *auth
|= V1_AUTHORITY
;
2629 else if (!strcmp(string
, "1"))
2630 if (options
->BridgeRelay
)
2631 *auth
|= BRIDGE_AUTHORITY
;
2633 *auth
|= V2_AUTHORITY
| V3_AUTHORITY
;
2634 else if (!strcasecmp(string
, "v2"))
2635 *auth
|= V2_AUTHORITY
;
2636 else if (!strcasecmp(string
, "v3"))
2637 *auth
|= V3_AUTHORITY
;
2638 else if (!strcasecmp(string
, "bridge"))
2639 *auth
|= BRIDGE_AUTHORITY
;
2640 else if (!strcasecmp(string
, "hidserv"))
2641 *auth
|= HIDSERV_AUTHORITY
;
2642 else if (!strcasecmp(string
, "") || !strcmp(string
, "0"))
2650 /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
2651 * services can overload the directory system. */
2652 #define MIN_REND_POST_PERIOD (10*60)
2654 /** Highest allowable value for RendPostPeriod. */
2655 #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
2657 /** Return 0 if every setting in <b>options</b> is reasonable, and a
2658 * permissible transition from <b>old_options</b>. Else return -1.
2659 * Should have no side effects, except for normalizing the contents of
2662 * On error, tor_strdup an error explanation into *<b>msg</b>.
2665 * If <b>from_setconf</b>, we were called by the controller, and our
2666 * Log line should stay empty. If it's 0, then give us a default log
2667 * if there are no logs defined.
2670 options_validate(or_options_t
*old_options
, or_options_t
*options
,
2671 int from_setconf
, char **msg
)
2675 const char *uname
= get_uname();
2677 #define REJECT(arg) \
2678 STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
2679 #define COMPLAIN(arg) STMT_BEGIN log(LOG_WARN, LD_CONFIG, arg); STMT_END
2684 if (options
->ORPort
< 0 || options
->ORPort
> 65535)
2685 REJECT("ORPort option out of bounds.");
2687 if (server_mode(options
) &&
2688 (!strcmpstart(uname
, "Windows 95") ||
2689 !strcmpstart(uname
, "Windows 98") ||
2690 !strcmpstart(uname
, "Windows Me"))) {
2691 log(LOG_WARN
, LD_CONFIG
, "Tor is running as a server, but you are "
2692 "running %s; this probably won't work. See "
2693 "http://wiki.noreply.org/noreply/TheOnionRouter/TorFAQ#ServerOS "
2694 "for details.", uname
);
2697 if (options
->ORPort
== 0 && options
->ORListenAddress
!= NULL
)
2698 REJECT("ORPort must be defined if ORListenAddress is defined.");
2700 if (options
->DirPort
== 0 && options
->DirListenAddress
!= NULL
)
2701 REJECT("DirPort must be defined if DirListenAddress is defined.");
2703 if (options
->DNSPort
== 0 && options
->DNSListenAddress
!= NULL
)
2704 REJECT("DNSPort must be defined if DNSListenAddress is defined.");
2706 if (options
->ControlPort
== 0 && options
->ControlListenAddress
!= NULL
)
2707 REJECT("ControlPort must be defined if ControlListenAddress is defined.");
2709 if (options
->TransPort
== 0 && options
->TransListenAddress
!= NULL
)
2710 REJECT("TransPort must be defined if TransListenAddress is defined.");
2712 if (options
->NatdPort
== 0 && options
->NatdListenAddress
!= NULL
)
2713 REJECT("NatdPort must be defined if NatdListenAddress is defined.");
2715 /* Don't gripe about SocksPort 0 with SocksListenAddress set; a standard
2716 * configuration does this. */
2718 for (i
= 0; i
< 3; ++i
) {
2719 int is_socks
= i
==0;
2720 int is_trans
= i
==1;
2721 config_line_t
*line
, *opt
, *old
;
2724 opt
= options
->SocksListenAddress
;
2725 old
= old_options
? old_options
->SocksListenAddress
: NULL
;
2727 } else if (is_trans
) {
2728 opt
= options
->TransListenAddress
;
2729 old
= old_options
? old_options
->TransListenAddress
: NULL
;
2730 tp
= "transparent proxy";
2732 opt
= options
->NatdListenAddress
;
2733 old
= old_options
? old_options
->NatdListenAddress
: NULL
;
2737 for (line
= opt
; line
; line
= line
->next
) {
2738 char *address
= NULL
;
2741 if (parse_addr_port(LOG_WARN
, line
->value
, &address
, &addr
, &port
)<0)
2742 continue; /* We'll warn about this later. */
2743 if (!is_internal_IP(addr
, 1) &&
2744 (!old_options
|| !config_lines_eq(old
, opt
))) {
2746 "You specified a public address '%s' for a %s. Other "
2747 "people on the Internet might find your computer and use it as "
2748 "an open %s. Please don't allow this unless you have "
2749 "a good reason.", address
, tp
, tp
);
2755 if (validate_data_directory(options
)<0)
2756 REJECT("Invalid DataDirectory");
2758 if (options
->Nickname
== NULL
) {
2759 if (server_mode(options
)) {
2760 if (!(options
->Nickname
= get_default_nickname())) {
2761 log_notice(LD_CONFIG
, "Couldn't pick a nickname based on "
2762 "our hostname; using %s instead.", UNNAMED_ROUTER_NICKNAME
);
2763 options
->Nickname
= tor_strdup(UNNAMED_ROUTER_NICKNAME
);
2765 log_notice(LD_CONFIG
, "Choosing default nickname '%s'",
2770 if (!is_legal_nickname(options
->Nickname
)) {
2771 r
= tor_snprintf(buf
, sizeof(buf
),
2772 "Nickname '%s' is wrong length or contains illegal characters.",
2774 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
2779 if (server_mode(options
) && !options
->ContactInfo
)
2780 log(LOG_NOTICE
, LD_CONFIG
, "Your ContactInfo config option is not set. "
2781 "Please consider setting it, so we can contact you if your server is "
2782 "misconfigured or something else goes wrong.");
2784 /* Special case on first boot if no Log options are given. */
2785 if (!options
->Logs
&& !options
->RunAsDaemon
&& !from_setconf
)
2786 config_line_append(&options
->Logs
, "Log", "notice stdout");
2788 if (options_init_logs(options
, 1)<0) /* Validate the log(s) */
2789 REJECT("Failed to validate Log options. See logs for details.");
2791 if (options
->NoPublish
) {
2792 log(LOG_WARN
, LD_CONFIG
,
2793 "NoPublish is obsolete. Use PublishServerDescriptor instead.");
2794 SMARTLIST_FOREACH(options
->PublishServerDescriptor
, char *, s
,
2796 smartlist_clear(options
->PublishServerDescriptor
);
2799 if (authdir_mode(options
)) {
2800 /* confirm that our address isn't broken, so we can complain now */
2802 if (resolve_my_address(LOG_WARN
, options
, &tmp
, NULL
) < 0)
2803 REJECT("Failed to resolve/guess local address. See logs for details.");
2807 if (options
->RunAsDaemon
&& torrc_fname
&& path_is_relative(torrc_fname
))
2808 REJECT("Can't use a relative path to torrc when RunAsDaemon is set.");
2811 if (options
->SocksPort
< 0 || options
->SocksPort
> 65535)
2812 REJECT("SocksPort option out of bounds.");
2814 if (options
->DNSPort
< 0 || options
->DNSPort
> 65535)
2815 REJECT("DNSPort option out of bounds.");
2817 if (options
->TransPort
< 0 || options
->TransPort
> 65535)
2818 REJECT("TransPort option out of bounds.");
2820 if (options
->NatdPort
< 0 || options
->NatdPort
> 65535)
2821 REJECT("NatdPort option out of bounds.");
2823 if (options
->SocksPort
== 0 && options
->TransPort
== 0 &&
2824 options
->NatdPort
== 0 && options
->ORPort
== 0 &&
2825 options
->DNSPort
== 0 && !options
->RendConfigLines
)
2826 log(LOG_WARN
, LD_CONFIG
,
2827 "SocksPort, TransPort, NatdPort, DNSPort, and ORPort are all "
2828 "undefined, and there aren't any hidden services configured. "
2829 "Tor will still run, but probably won't do anything.");
2831 if (options
->ControlPort
< 0 || options
->ControlPort
> 65535)
2832 REJECT("ControlPort option out of bounds.");
2834 if (options
->DirPort
< 0 || options
->DirPort
> 65535)
2835 REJECT("DirPort option out of bounds.");
2837 #ifndef USE_TRANSPARENT
2838 if (options
->TransPort
|| options
->TransListenAddress
)
2839 REJECT("TransPort and TransListenAddress are disabled in this build.");
2842 if (options
->StrictExitNodes
&&
2843 (!options
->ExitNodes
|| !strlen(options
->ExitNodes
)) &&
2845 (old_options
->StrictExitNodes
!= options
->StrictExitNodes
) ||
2846 (!opt_streq(old_options
->ExitNodes
, options
->ExitNodes
))))
2847 COMPLAIN("StrictExitNodes set, but no ExitNodes listed.");
2849 if (options
->StrictEntryNodes
&&
2850 (!options
->EntryNodes
|| !strlen(options
->EntryNodes
)) &&
2852 (old_options
->StrictEntryNodes
!= options
->StrictEntryNodes
) ||
2853 (!opt_streq(old_options
->EntryNodes
, options
->EntryNodes
))))
2854 COMPLAIN("StrictEntryNodes set, but no EntryNodes listed.");
2856 if (options
->AuthoritativeDir
) {
2857 if (!options
->ContactInfo
)
2858 REJECT("Authoritative directory servers must set ContactInfo");
2859 if (options
->V1AuthoritativeDir
&& !options
->RecommendedVersions
)
2860 REJECT("V1 auth dir servers must set RecommendedVersions.");
2861 if (!options
->RecommendedClientVersions
)
2862 options
->RecommendedClientVersions
=
2863 config_lines_dup(options
->RecommendedVersions
);
2864 if (!options
->RecommendedServerVersions
)
2865 options
->RecommendedServerVersions
=
2866 config_lines_dup(options
->RecommendedVersions
);
2867 if (options
->VersioningAuthoritativeDir
&&
2868 (!options
->RecommendedClientVersions
||
2869 !options
->RecommendedServerVersions
))
2870 REJECT("Versioning auth dir servers must set Recommended*Versions.");
2871 if (options
->UseEntryGuards
) {
2872 log_info(LD_CONFIG
, "Authoritative directory servers can't set "
2873 "UseEntryGuards. Disabling.");
2874 options
->UseEntryGuards
= 0;
2876 if (!options
->DownloadExtraInfo
&& authdir_mode_any_main(options
)) {
2877 log_info(LD_CONFIG
, "Authoritative directories always try to download "
2878 "extra-info documents. Setting DownloadExtraInfo.");
2879 options
->DownloadExtraInfo
= 1;
2881 if (!(options
->BridgeAuthoritativeDir
|| options
->HSAuthoritativeDir
||
2882 options
->V1AuthoritativeDir
|| options
->V2AuthoritativeDir
||
2883 options
->V3AuthoritativeDir
))
2884 REJECT("AuthoritativeDir is set, but none of "
2885 "(Bridge/HS/V1/V2/V3)AuthoritativeDir is set.");
2888 if (options
->AuthoritativeDir
&& !options
->DirPort
)
2889 REJECT("Running as authoritative directory, but no DirPort set.");
2891 if (options
->AuthoritativeDir
&& !options
->ORPort
)
2892 REJECT("Running as authoritative directory, but no ORPort set.");
2894 if (options
->AuthoritativeDir
&& options
->ClientOnly
)
2895 REJECT("Running as authoritative directory, but ClientOnly also set.");
2897 if (options
->HSAuthorityRecordStats
&& !options
->HSAuthoritativeDir
)
2898 REJECT("HSAuthorityRecordStats is set but we're not running as "
2899 "a hidden service authority.");
2901 if (options
->HidServDirectoryV2
&& !options
->DirPort
)
2902 REJECT("Running as hidden service directory, but no DirPort set.");
2904 if (options
->ConnLimit
<= 0) {
2905 r
= tor_snprintf(buf
, sizeof(buf
),
2906 "ConnLimit must be greater than 0, but was set to %d",
2907 options
->ConnLimit
);
2908 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
2912 if (validate_ports_csv(options
->FirewallPorts
, "FirewallPorts", msg
) < 0)
2915 if (validate_ports_csv(options
->LongLivedPorts
, "LongLivedPorts", msg
) < 0)
2918 if (validate_ports_csv(options
->RejectPlaintextPorts
,
2919 "RejectPlaintextPorts", msg
) < 0)
2922 if (validate_ports_csv(options
->WarnPlaintextPorts
,
2923 "WarnPlaintextPorts", msg
) < 0)
2926 if (options
->FascistFirewall
&& !options
->ReachableAddresses
) {
2927 if (options
->FirewallPorts
&& smartlist_len(options
->FirewallPorts
)) {
2928 /* We already have firewall ports set, so migrate them to
2929 * ReachableAddresses, which will set ReachableORAddresses and
2930 * ReachableDirAddresses if they aren't set explicitly. */
2931 smartlist_t
*instead
= smartlist_create();
2932 config_line_t
*new_line
= tor_malloc_zero(sizeof(config_line_t
));
2933 new_line
->key
= tor_strdup("ReachableAddresses");
2934 /* If we're configured with the old format, we need to prepend some
2936 SMARTLIST_FOREACH(options
->FirewallPorts
, const char *, portno
,
2938 int p
= atoi(portno
);
2942 tor_snprintf(s
, 16, "*:%d", p
);
2943 smartlist_add(instead
, s
);
2945 new_line
->value
= smartlist_join_strings(instead
,",",0,NULL
);
2946 /* These have been deprecated since 0.1.1.5-alpha-cvs */
2947 log(LOG_NOTICE
, LD_CONFIG
,
2948 "Converting FascistFirewall and FirewallPorts "
2949 "config options to new format: \"ReachableAddresses %s\"",
2951 options
->ReachableAddresses
= new_line
;
2952 SMARTLIST_FOREACH(instead
, char *, cp
, tor_free(cp
));
2953 smartlist_free(instead
);
2955 /* We do not have FirewallPorts set, so add 80 to
2956 * ReachableDirAddresses, and 443 to ReachableORAddresses. */
2957 if (!options
->ReachableDirAddresses
) {
2958 config_line_t
*new_line
= tor_malloc_zero(sizeof(config_line_t
));
2959 new_line
->key
= tor_strdup("ReachableDirAddresses");
2960 new_line
->value
= tor_strdup("*:80");
2961 options
->ReachableDirAddresses
= new_line
;
2962 log(LOG_NOTICE
, LD_CONFIG
, "Converting FascistFirewall config option "
2963 "to new format: \"ReachableDirAddresses *:80\"");
2965 if (!options
->ReachableORAddresses
) {
2966 config_line_t
*new_line
= tor_malloc_zero(sizeof(config_line_t
));
2967 new_line
->key
= tor_strdup("ReachableORAddresses");
2968 new_line
->value
= tor_strdup("*:443");
2969 options
->ReachableORAddresses
= new_line
;
2970 log(LOG_NOTICE
, LD_CONFIG
, "Converting FascistFirewall config option "
2971 "to new format: \"ReachableORAddresses *:443\"");
2976 for (i
=0; i
<3; i
++) {
2977 config_line_t
**linep
=
2978 (i
==0) ? &options
->ReachableAddresses
:
2979 (i
==1) ? &options
->ReachableORAddresses
:
2980 &options
->ReachableDirAddresses
;
2983 /* We need to end with a reject *:*, not an implicit accept *:* */
2985 if (!strcmp((*linep
)->value
, "reject *:*")) /* already there */
2987 linep
= &((*linep
)->next
);
2989 *linep
= tor_malloc_zero(sizeof(config_line_t
));
2990 (*linep
)->key
= tor_strdup(
2991 (i
==0) ? "ReachableAddresses" :
2992 (i
==1) ? "ReachableORAddresses" :
2993 "ReachableDirAddresses");
2994 (*linep
)->value
= tor_strdup("reject *:*");
3000 if ((options
->ReachableAddresses
||
3001 options
->ReachableORAddresses
||
3002 options
->ReachableDirAddresses
) &&
3003 server_mode(options
))
3004 REJECT("Servers must be able to freely connect to the rest "
3005 "of the Internet, so they must not set Reachable*Addresses "
3006 "or FascistFirewall.");
3008 if (options
->UseBridges
&&
3009 server_mode(options
))
3010 REJECT("Servers must be able to freely connect to the rest "
3011 "of the Internet, so they must not set UseBridges.");
3013 options
->_AllowInvalid
= 0;
3014 if (options
->AllowInvalidNodes
) {
3015 SMARTLIST_FOREACH(options
->AllowInvalidNodes
, const char *, cp
, {
3016 if (!strcasecmp(cp
, "entry"))
3017 options
->_AllowInvalid
|= ALLOW_INVALID_ENTRY
;
3018 else if (!strcasecmp(cp
, "exit"))
3019 options
->_AllowInvalid
|= ALLOW_INVALID_EXIT
;
3020 else if (!strcasecmp(cp
, "middle"))
3021 options
->_AllowInvalid
|= ALLOW_INVALID_MIDDLE
;
3022 else if (!strcasecmp(cp
, "introduction"))
3023 options
->_AllowInvalid
|= ALLOW_INVALID_INTRODUCTION
;
3024 else if (!strcasecmp(cp
, "rendezvous"))
3025 options
->_AllowInvalid
|= ALLOW_INVALID_RENDEZVOUS
;
3027 r
= tor_snprintf(buf
, sizeof(buf
),
3028 "Unrecognized value '%s' in AllowInvalidNodes", cp
);
3029 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
3035 if (compute_publishserverdescriptor(options
) < 0) {
3036 r
= tor_snprintf(buf
, sizeof(buf
),
3037 "Unrecognized value in PublishServerDescriptor");
3038 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
3042 if (options
->MinUptimeHidServDirectoryV2
< 0) {
3043 log_warn(LD_CONFIG
, "MinUptimeHidServDirectoryV2 option must be at "
3044 "least 0 seconds. Changing to 0.");
3045 options
->MinUptimeHidServDirectoryV2
= 0;
3048 if (options
->RendPostPeriod
< MIN_REND_POST_PERIOD
) {
3049 log(LOG_WARN
,LD_CONFIG
,"RendPostPeriod option must be at least %d seconds."
3050 " Clipping.", MIN_REND_POST_PERIOD
);
3051 options
->RendPostPeriod
= MIN_REND_POST_PERIOD
;
3054 if (options
->RendPostPeriod
> MAX_DIR_PERIOD
) {
3055 log(LOG_WARN
, LD_CONFIG
, "RendPostPeriod is too large; clipping to %ds.",
3057 options
->RendPostPeriod
= MAX_DIR_PERIOD
;
3060 if (options
->KeepalivePeriod
< 1)
3061 REJECT("KeepalivePeriod option must be positive.");
3063 if (ensure_bandwidth_cap(&options
->BandwidthRate
,
3064 "BandwidthRate", msg
) < 0)
3066 if (ensure_bandwidth_cap(&options
->BandwidthBurst
,
3067 "BandwidthBurst", msg
) < 0)
3069 if (ensure_bandwidth_cap(&options
->MaxAdvertisedBandwidth
,
3070 "MaxAdvertisedBandwidth", msg
) < 0)
3072 if (ensure_bandwidth_cap(&options
->RelayBandwidthRate
,
3073 "RelayBandwidthRate", msg
) < 0)
3075 if (ensure_bandwidth_cap(&options
->RelayBandwidthBurst
,
3076 "RelayBandwidthBurst", msg
) < 0)
3079 if (server_mode(options
)) {
3080 if (options
->BandwidthRate
< ROUTER_REQUIRED_MIN_BANDWIDTH
*2) {
3081 r
= tor_snprintf(buf
, sizeof(buf
),
3082 "BandwidthRate is set to %d bytes/second. "
3083 "For servers, it must be at least %d.",
3084 (int)options
->BandwidthRate
,
3085 ROUTER_REQUIRED_MIN_BANDWIDTH
*2);
3086 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
3088 } else if (options
->MaxAdvertisedBandwidth
<
3089 ROUTER_REQUIRED_MIN_BANDWIDTH
) {
3090 r
= tor_snprintf(buf
, sizeof(buf
),
3091 "MaxAdvertisedBandwidth is set to %d bytes/second. "
3092 "For servers, it must be at least %d.",
3093 (int)options
->MaxAdvertisedBandwidth
,
3094 ROUTER_REQUIRED_MIN_BANDWIDTH
);
3095 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
3098 if (options
->RelayBandwidthRate
&&
3099 options
->RelayBandwidthRate
< ROUTER_REQUIRED_MIN_BANDWIDTH
) {
3100 r
= tor_snprintf(buf
, sizeof(buf
),
3101 "RelayBandwidthRate is set to %d bytes/second. "
3102 "For servers, it must be at least %d.",
3103 (int)options
->RelayBandwidthRate
,
3104 ROUTER_REQUIRED_MIN_BANDWIDTH
);
3105 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
3110 if (options
->RelayBandwidthRate
&& !options
->RelayBandwidthBurst
)
3111 options
->RelayBandwidthBurst
= options
->RelayBandwidthRate
;
3113 if (options
->RelayBandwidthRate
> options
->RelayBandwidthBurst
)
3114 REJECT("RelayBandwidthBurst must be at least equal "
3115 "to RelayBandwidthRate.");
3117 if (options
->BandwidthRate
> options
->BandwidthBurst
)
3118 REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
3120 if (accounting_parse_options(options
, 1)<0)
3121 REJECT("Failed to parse accounting options. See logs for details.");
3123 if (options
->HttpProxy
) { /* parse it now */
3124 if (parse_addr_port(LOG_WARN
, options
->HttpProxy
, NULL
,
3125 &options
->HttpProxyAddr
, &options
->HttpProxyPort
) < 0)
3126 REJECT("HttpProxy failed to parse or resolve. Please fix.");
3127 if (options
->HttpProxyPort
== 0) { /* give it a default */
3128 options
->HttpProxyPort
= 80;
3132 if (options
->HttpProxyAuthenticator
) {
3133 if (strlen(options
->HttpProxyAuthenticator
) >= 48)
3134 REJECT("HttpProxyAuthenticator is too long (>= 48 chars).");
3137 if (options
->HttpsProxy
) { /* parse it now */
3138 if (parse_addr_port(LOG_WARN
, options
->HttpsProxy
, NULL
,
3139 &options
->HttpsProxyAddr
, &options
->HttpsProxyPort
) <0)
3140 REJECT("HttpsProxy failed to parse or resolve. Please fix.");
3141 if (options
->HttpsProxyPort
== 0) { /* give it a default */
3142 options
->HttpsProxyPort
= 443;
3146 if (options
->HttpsProxyAuthenticator
) {
3147 if (strlen(options
->HttpsProxyAuthenticator
) >= 48)
3148 REJECT("HttpsProxyAuthenticator is too long (>= 48 chars).");
3151 if (options
->HashedControlPassword
) {
3152 smartlist_t
*sl
= decode_hashed_passwords(options
->HashedControlPassword
);
3154 REJECT("Bad HashedControlPassword: wrong length or bad encoding");
3156 SMARTLIST_FOREACH(sl
, char*, cp
, tor_free(cp
));
3161 if (options
->HashedControlSessionPassword
) {
3162 smartlist_t
*sl
= decode_hashed_passwords(
3163 options
->HashedControlSessionPassword
);
3165 REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
3167 SMARTLIST_FOREACH(sl
, char*, cp
, tor_free(cp
));
3172 if (options
->ControlListenAddress
) {
3173 int all_are_local
= 1;
3175 for (ln
= options
->ControlListenAddress
; ln
; ln
= ln
->next
) {
3176 if (strcmpstart(ln
->value
, "127."))
3179 if (!all_are_local
) {
3180 if (!options
->HashedControlPassword
&&
3181 !options
->HashedControlSessionPassword
&&
3182 !options
->CookieAuthentication
) {
3183 log_warn(LD_CONFIG
, "You have a ControlListenAddress set to accept "
3184 "connections from a non-local address. This means that "
3185 "any program on the internet can reconfigure your Tor. "
3186 "That's so bad that I'm closing your ControlPort for you.");
3187 options
->ControlPort
= 0;
3189 log_warn(LD_CONFIG
, "You have a ControlListenAddress set to accept "
3190 "connections from a non-local address. This means that "
3191 "programs not running on your computer can reconfigure your "
3192 "Tor. That's pretty bad!");
3197 if (options
->ControlPort
&& !options
->HashedControlPassword
&&
3198 !options
->HashedControlSessionPassword
&&
3199 !options
->CookieAuthentication
) {
3200 log_warn(LD_CONFIG
, "ControlPort is open, but no authentication method "
3201 "has been configured. This means that any program on your "
3202 "computer can reconfigure your Tor. That's bad! You should "
3203 "upgrade your Tor controller as soon as possible.");
3206 if (options
->UseEntryGuards
&& ! options
->NumEntryGuards
)
3207 REJECT("Cannot enable UseEntryGuards with NumEntryGuards set to 0");
3209 if (check_nickname_list(options
->ExitNodes
, "ExitNodes", msg
))
3211 if (check_nickname_list(options
->EntryNodes
, "EntryNodes", msg
))
3213 if (check_nickname_list(options
->ExcludeNodes
, "ExcludeNodes", msg
))
3215 if (check_nickname_list(options
->RendNodes
, "RendNodes", msg
))
3217 if (check_nickname_list(options
->RendNodes
, "RendExcludeNodes", msg
))
3219 if (check_nickname_list(options
->TestVia
, "TestVia", msg
))
3221 if (check_nickname_list(options
->MyFamily
, "MyFamily", msg
))
3223 for (cl
= options
->NodeFamilies
; cl
; cl
= cl
->next
) {
3224 if (check_nickname_list(cl
->value
, "NodeFamily", msg
))
3228 if (validate_addr_policies(options
, msg
) < 0)
3231 for (cl
= options
->RedirectExit
; cl
; cl
= cl
->next
) {
3232 if (parse_redirect_line(NULL
, cl
, msg
)<0)
3236 if (validate_dir_authorities(options
, old_options
) < 0)
3237 REJECT("Directory authority line did not parse. See logs for details.");
3239 if (options
->UseBridges
&& !options
->Bridges
)
3240 REJECT("If you set UseBridges, you must specify at least one bridge.");
3241 if (options
->UseBridges
&& !options
->TunnelDirConns
)
3242 REJECT("If you set UseBridges, you must set TunnelDirConns.");
3243 if (options
->Bridges
) {
3244 for (cl
= options
->Bridges
; cl
; cl
= cl
->next
) {
3245 if (parse_bridge_line(cl
->value
, 1)<0)
3246 REJECT("Bridge line did not parse. See logs for details.");
3250 if (options
->ConstrainedSockets
) {
3251 /* If the user wants to constrain socket buffer use, make sure the desired
3252 * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
3253 if (options
->ConstrainedSockSize
< MIN_CONSTRAINED_TCP_BUFFER
||
3254 options
->ConstrainedSockSize
> MAX_CONSTRAINED_TCP_BUFFER
||
3255 options
->ConstrainedSockSize
% 1024) {
3256 r
= tor_snprintf(buf
, sizeof(buf
),
3257 "ConstrainedSockSize is invalid. Must be a value between %d and %d "
3258 "in 1024 byte increments.",
3259 MIN_CONSTRAINED_TCP_BUFFER
, MAX_CONSTRAINED_TCP_BUFFER
);
3260 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
3263 if (options
->DirPort
) {
3264 /* Providing cached directory entries while system TCP buffers are scarce
3265 * will exacerbate the socket errors. Suggest that this be disabled. */
3266 COMPLAIN("You have requested constrained socket buffers while also "
3267 "serving directory entries via DirPort. It is strongly "
3268 "suggested that you disable serving directory requests when "
3269 "system TCP buffer resources are scarce.");
3273 if (options
->V3AuthVoteDelay
+ options
->V3AuthDistDelay
>=
3274 options
->V3AuthVotingInterval
/2) {
3275 REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
3276 "V3AuthVotingInterval");
3278 if (options
->V3AuthVoteDelay
< MIN_VOTE_SECONDS
)
3279 REJECT("V3AuthVoteDelay is way too low.");
3280 if (options
->V3AuthDistDelay
< MIN_DIST_SECONDS
)
3281 REJECT("V3AuthDistDelay is way too low.");
3283 if (options
->V3AuthNIntervalsValid
< 2)
3284 REJECT("V3AuthNIntervalsValid must be at least 2.");
3286 if (options
->V3AuthVotingInterval
< MIN_VOTE_INTERVAL
) {
3287 REJECT("V3AuthVotingInterval is insanely low.");
3288 } else if (options
->V3AuthVotingInterval
> 24*60*60) {
3289 REJECT("V3AuthVotingInterval is insanely high.");
3290 } else if (((24*60*60) % options
->V3AuthVotingInterval
) != 0) {
3291 COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
3294 if (rend_config_services(options
, 1) < 0)
3295 REJECT("Failed to configure rendezvous options. See logs for details.");
3297 if (parse_virtual_addr_network(options
->VirtualAddrNetwork
, 1, NULL
)<0)
3300 if (options
->PreferTunneledDirConns
&& !options
->TunnelDirConns
)
3301 REJECT("Must set TunnelDirConns if PreferTunneledDirConns is set.");
3303 if (options
->AutomapHostsSuffixes
) {
3304 SMARTLIST_FOREACH(options
->AutomapHostsSuffixes
, char *, suf
,
3306 size_t len
= strlen(suf
);
3307 if (len
&& suf
[len
-1] == '.')
3317 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
3320 opt_streq(const char *s1
, const char *s2
)
3324 else if (s1
&& s2
&& !strcmp(s1
,s2
))
3330 /** Check if any of the previous options have changed but aren't allowed to. */
3332 options_transition_allowed(or_options_t
*old
, or_options_t
*new_val
,
3338 if (!opt_streq(old
->PidFile
, new_val
->PidFile
)) {
3339 *msg
= tor_strdup("PidFile is not allowed to change.");
3343 if (old
->RunAsDaemon
!= new_val
->RunAsDaemon
) {
3344 *msg
= tor_strdup("While Tor is running, changing RunAsDaemon "
3349 if (strcmp(old
->DataDirectory
,new_val
->DataDirectory
)!=0) {
3351 int r
= tor_snprintf(buf
, sizeof(buf
),
3352 "While Tor is running, changing DataDirectory "
3353 "(\"%s\"->\"%s\") is not allowed.",
3354 old
->DataDirectory
, new_val
->DataDirectory
);
3355 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
3359 if (!opt_streq(old
->User
, new_val
->User
)) {
3360 *msg
= tor_strdup("While Tor is running, changing User is not allowed.");
3364 if (!opt_streq(old
->Group
, new_val
->Group
)) {
3365 *msg
= tor_strdup("While Tor is running, changing Group is not allowed.");
3369 if (old
->HardwareAccel
!= new_val
->HardwareAccel
) {
3370 *msg
= tor_strdup("While Tor is running, changing HardwareAccel is "
3378 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3379 * will require us to rotate the cpu and dns workers; else return 0. */
3381 options_transition_affects_workers(or_options_t
*old_options
,
3382 or_options_t
*new_options
)
3384 if (!opt_streq(old_options
->DataDirectory
, new_options
->DataDirectory
) ||
3385 old_options
->NumCpus
!= new_options
->NumCpus
||
3386 old_options
->ORPort
!= new_options
->ORPort
||
3387 old_options
->ServerDNSSearchDomains
!=
3388 new_options
->ServerDNSSearchDomains
||
3389 old_options
->SafeLogging
!= new_options
->SafeLogging
||
3390 old_options
->ClientOnly
!= new_options
->ClientOnly
||
3391 !config_lines_eq(old_options
->Logs
, new_options
->Logs
))
3394 /* Check whether log options match. */
3396 /* Nothing that changed matters. */
3400 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3401 * will require us to generate a new descriptor; else return 0. */
3403 options_transition_affects_descriptor(or_options_t
*old_options
,
3404 or_options_t
*new_options
)
3406 if (!opt_streq(old_options
->DataDirectory
, new_options
->DataDirectory
) ||
3407 !opt_streq(old_options
->Nickname
,new_options
->Nickname
) ||
3408 !opt_streq(old_options
->Address
,new_options
->Address
) ||
3409 !config_lines_eq(old_options
->ExitPolicy
,new_options
->ExitPolicy
) ||
3410 old_options
->ExitPolicyRejectPrivate
!=
3411 new_options
->ExitPolicyRejectPrivate
||
3412 old_options
->ORPort
!= new_options
->ORPort
||
3413 old_options
->DirPort
!= new_options
->DirPort
||
3414 old_options
->ClientOnly
!= new_options
->ClientOnly
||
3415 old_options
->NoPublish
!= new_options
->NoPublish
||
3416 old_options
->_PublishServerDescriptor
!=
3417 new_options
->_PublishServerDescriptor
||
3418 old_options
->BandwidthRate
!= new_options
->BandwidthRate
||
3419 old_options
->BandwidthBurst
!= new_options
->BandwidthBurst
||
3420 !opt_streq(old_options
->ContactInfo
, new_options
->ContactInfo
) ||
3421 !opt_streq(old_options
->MyFamily
, new_options
->MyFamily
) ||
3422 !opt_streq(old_options
->AccountingStart
, new_options
->AccountingStart
) ||
3423 old_options
->AccountingMax
!= new_options
->AccountingMax
)
3430 /** Return the directory on windows where we expect to find our application
3433 get_windows_conf_root(void)
3435 static int is_set
= 0;
3436 static char path
[MAX_PATH
+1];
3445 /* Find X:\documents and settings\username\application data\ .
3446 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
3448 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL
, CSIDL_APPDATA
,
3450 GetCurrentDirectory(MAX_PATH
, path
);
3453 "I couldn't find your application data folder: are you "
3454 "running an ancient version of Windows 95? Defaulting to \"%s\"",
3458 /* Convert the path from an "ID List" (whatever that is!) to a path. */
3459 result
= SHGetPathFromIDList(idl
, path
);
3460 /* Now we need to free the */
3463 m
->lpVtbl
->Free(m
, idl
);
3464 m
->lpVtbl
->Release(m
);
3466 if (!SUCCEEDED(result
)) {
3469 strlcat(path
,"\\tor",MAX_PATH
);
3475 /** Return the default location for our torrc file. */
3477 get_default_conf_file(void)
3480 static char path
[MAX_PATH
+1];
3481 strlcpy(path
, get_windows_conf_root(), MAX_PATH
);
3482 strlcat(path
,"\\torrc",MAX_PATH
);
3485 return (CONFDIR
"/torrc");
3489 /** Verify whether lst is a string containing valid-looking space-separated
3490 * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
3493 check_nickname_list(const char *lst
, const char *name
, char **msg
)
3500 sl
= smartlist_create();
3501 smartlist_split_string(sl
, lst
, ",", SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
3502 SMARTLIST_FOREACH(sl
, const char *, s
,
3504 if (!is_legal_nickname_or_hexdigest(s
)) {
3506 int tmp
= tor_snprintf(buf
, sizeof(buf
),
3507 "Invalid nickname '%s' in %s line", s
, name
);
3508 *msg
= tor_strdup(tmp
>= 0 ? buf
: "internal error");
3513 SMARTLIST_FOREACH(sl
, char *, s
, tor_free(s
));
3518 /** Read a configuration file into <b>options</b>, finding the configuration
3519 * file location based on the command line. After loading the options,
3520 * validate them for consistency, then take actions based on them.
3521 * Return 0 if success, -1 if failure. */
3523 options_init_from_torrc(int argc
, char **argv
)
3525 or_options_t
*oldoptions
, *newoptions
;
3527 char *cf
=NULL
, *fname
=NULL
, *errmsg
=NULL
;
3529 int using_default_torrc
;
3530 int ignore_missing_torrc
;
3531 static char **backup_argv
;
3532 static int backup_argc
;
3534 if (argv
) { /* first time we're called. save commandline args */
3538 } else { /* we're reloading. need to clean up old options first. */
3541 oldoptions
= get_options();
3543 if (argc
> 1 && (!strcmp(argv
[1], "-h") || !strcmp(argv
[1],"--help"))) {
3547 if (argc
> 1 && !strcmp(argv
[1], "--list-torrc-options")) {
3548 /* For documenting validating whether we've documented everything. */
3549 list_torrc_options();
3553 if (argc
> 1 && (!strcmp(argv
[1],"--version"))) {
3554 printf("Tor version %s.\n",get_version());
3555 if (argc
> 2 && (!strcmp(argv
[2],"--version"))) {
3556 print_svn_version();
3561 newoptions
= tor_malloc_zero(sizeof(or_options_t
));
3562 newoptions
->_magic
= OR_OPTIONS_MAGIC
;
3563 options_init(newoptions
);
3565 /* learn config file name */
3567 using_default_torrc
= 1;
3568 ignore_missing_torrc
= 0;
3569 newoptions
->command
= CMD_RUN_TOR
;
3570 for (i
= 1; i
< argc
; ++i
) {
3571 if (i
< argc
-1 && !strcmp(argv
[i
],"-f")) {
3573 log(LOG_WARN
, LD_CONFIG
, "Duplicate -f options on command line.");
3577 /* XXX one day we might want to extend expand_filename to work
3578 * under Windows as well. */
3579 fname
= tor_strdup(argv
[i
+1]);
3581 fname
= expand_filename(argv
[i
+1]);
3583 using_default_torrc
= 0;
3585 } else if (!strcmp(argv
[i
],"--ignore-missing-torrc")) {
3586 ignore_missing_torrc
= 1;
3587 } else if (!strcmp(argv
[i
],"--list-fingerprint")) {
3588 newoptions
->command
= CMD_LIST_FINGERPRINT
;
3589 } else if (!strcmp(argv
[i
],"--hash-password")) {
3590 newoptions
->command
= CMD_HASH_PASSWORD
;
3591 newoptions
->command_arg
= tor_strdup( (i
< argc
-1) ? argv
[i
+1] : "");
3593 } else if (!strcmp(argv
[i
],"--verify-config")) {
3594 newoptions
->command
= CMD_VERIFY_CONFIG
;
3597 if (using_default_torrc
) {
3598 /* didn't find one, try CONFDIR */
3599 const char *dflt
= get_default_conf_file();
3600 if (dflt
&& file_status(dflt
) == FN_FILE
) {
3601 fname
= tor_strdup(dflt
);
3605 fn
= expand_filename("~/.torrc");
3606 if (fn
&& file_status(fn
) == FN_FILE
) {
3610 fname
= tor_strdup(dflt
);
3613 fname
= tor_strdup(dflt
);
3618 log(LOG_DEBUG
, LD_CONFIG
, "Opening config file \"%s\"", fname
);
3620 tor_free(torrc_fname
);
3621 torrc_fname
= fname
;
3623 /* get config lines, assign them */
3624 if (file_status(fname
) != FN_FILE
||
3625 !(cf
= read_file_to_str(fname
,0,NULL
))) {
3626 if (using_default_torrc
== 1 || ignore_missing_torrc
) {
3627 log(LOG_NOTICE
, LD_CONFIG
, "Configuration file \"%s\" not present, "
3628 "using reasonable defaults.", fname
);
3629 tor_free(fname
); /* sets fname to NULL */
3632 log(LOG_WARN
, LD_CONFIG
,
3633 "Unable to open configuration file \"%s\".", fname
);
3636 } else { /* it opened successfully. use it. */
3637 retval
= config_get_lines(cf
, &cl
);
3641 retval
= config_assign(&options_format
, newoptions
, cl
, 0, 0, &errmsg
);
3642 config_free_lines(cl
);
3647 /* Go through command-line variables too */
3648 if (config_get_commandlines(argc
, argv
, &cl
) < 0)
3650 retval
= config_assign(&options_format
, newoptions
, cl
, 0, 0, &errmsg
);
3651 config_free_lines(cl
);
3655 /* Validate newoptions */
3656 if (options_validate(oldoptions
, newoptions
, 0, &errmsg
) < 0)
3659 if (options_transition_allowed(oldoptions
, newoptions
, &errmsg
) < 0)
3662 if (set_options(newoptions
, &errmsg
))
3663 goto err
; /* frees and replaces old options */
3669 config_free(&options_format
, newoptions
);
3671 log(LOG_WARN
,LD_CONFIG
,"Failed to parse/validate config: %s", errmsg
);
3677 /** Return the location for our configuration file.
3680 get_torrc_fname(void)
3685 return get_default_conf_file();
3688 /** Adjust the address map mased on the MapAddress elements in the
3689 * configuration <b>options</b>
3692 config_register_addressmaps(or_options_t
*options
)
3698 addressmap_clear_configured();
3699 elts
= smartlist_create();
3700 for (opt
= options
->AddressMap
; opt
; opt
= opt
->next
) {
3701 smartlist_split_string(elts
, opt
->value
, NULL
,
3702 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 2);
3703 if (smartlist_len(elts
) >= 2) {
3704 from
= smartlist_get(elts
,0);
3705 to
= smartlist_get(elts
,1);
3706 if (address_is_invalid_destination(to
, 1)) {
3708 "Skipping invalid argument '%s' to MapAddress", to
);
3710 addressmap_register(from
, tor_strdup(to
), 0, ADDRMAPSRC_TORRC
);
3711 if (smartlist_len(elts
)>2) {
3712 log_warn(LD_CONFIG
,"Ignoring extra arguments to MapAddress.");
3716 log_warn(LD_CONFIG
,"MapAddress '%s' has too few arguments. Ignoring.",
3719 SMARTLIST_FOREACH(elts
, char*, cp
, tor_free(cp
));
3720 smartlist_clear(elts
);
3722 smartlist_free(elts
);
3725 /** If <b>range</b> is of the form MIN-MAX, for MIN and MAX both
3726 * recognized log severity levels, set *<b>min_out</b> to MIN and
3727 * *<b>max_out</b> to MAX and return 0. Else, if <b>range</b> is of
3728 * the form MIN, act as if MIN-err had been specified. Else, warn and
3732 parse_log_severity_range(const char *range
, int *min_out
, int *max_out
)
3734 int levelMin
, levelMax
;
3736 cp
= strchr(range
, '-');
3739 levelMin
= LOG_DEBUG
;
3741 char *tmp_sev
= tor_strndup(range
, cp
- range
);
3742 levelMin
= parse_log_level(tmp_sev
);
3744 log_warn(LD_CONFIG
, "Unrecognized minimum log severity '%s': must be "
3745 "one of err|warn|notice|info|debug", tmp_sev
);
3754 levelMax
= parse_log_level(cp
+1);
3756 log_warn(LD_CONFIG
, "Unrecognized maximum log severity '%s': must be "
3757 "one of err|warn|notice|info|debug", cp
+1);
3762 levelMin
= parse_log_level(range
);
3764 log_warn(LD_CONFIG
, "Unrecognized log severity '%s': must be one of "
3765 "err|warn|notice|info|debug", range
);
3771 *min_out
= levelMin
;
3772 *max_out
= levelMax
;
3778 * Initialize the logs based on the configuration file.
3781 options_init_logs(or_options_t
*options
, int validate_only
)
3790 options
->RunAsDaemon
;
3794 elts
= smartlist_create();
3796 for (opt
= options
->Logs
; opt
; opt
= opt
->next
) {
3797 int levelMin
=LOG_DEBUG
, levelMax
=LOG_ERR
;
3798 smartlist_split_string(elts
, opt
->value
, NULL
,
3799 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 3);
3800 if (smartlist_len(elts
) == 0) {
3801 log_warn(LD_CONFIG
, "No arguments to Log option 'Log %s'", opt
->value
);
3802 ok
= 0; goto cleanup
;
3804 if (parse_log_severity_range(smartlist_get(elts
,0), &levelMin
,
3806 ok
= 0; goto cleanup
;
3808 if (smartlist_len(elts
) < 2) { /* only loglevels were provided */
3809 if (!validate_only
) {
3812 "Can't log to stdout with RunAsDaemon set; skipping stdout");
3814 add_stream_log(levelMin
, levelMax
, "<stdout>", stdout
);
3819 if (!strcasecmp(smartlist_get(elts
,1), "file")) {
3820 if (smartlist_len(elts
) != 3) {
3821 log_warn(LD_CONFIG
, "Bad syntax on file Log option 'Log %s'",
3823 ok
= 0; goto cleanup
;
3825 if (!validate_only
) {
3826 if (add_file_log(levelMin
, levelMax
, smartlist_get(elts
, 2)) < 0) {
3827 log_warn(LD_CONFIG
, "Couldn't open file for 'Log %s'", opt
->value
);
3833 if (smartlist_len(elts
) != 2) {
3834 log_warn(LD_CONFIG
, "Wrong number of arguments on Log option 'Log %s'",
3836 ok
= 0; goto cleanup
;
3838 if (!strcasecmp(smartlist_get(elts
,1), "stdout")) {
3840 log_warn(LD_CONFIG
, "Can't log to stdout with RunAsDaemon set.");
3841 ok
= 0; goto cleanup
;
3843 if (!validate_only
) {
3844 add_stream_log(levelMin
, levelMax
, "<stdout>", stdout
);
3846 } else if (!strcasecmp(smartlist_get(elts
,1), "stderr")) {
3848 log_warn(LD_CONFIG
, "Can't log to stderr with RunAsDaemon set.");
3849 ok
= 0; goto cleanup
;
3851 if (!validate_only
) {
3852 add_stream_log(levelMin
, levelMax
, "<stderr>", stderr
);
3854 } else if (!strcasecmp(smartlist_get(elts
,1), "syslog")) {
3855 #ifdef HAVE_SYSLOG_H
3857 add_syslog_log(levelMin
, levelMax
);
3859 log_warn(LD_CONFIG
, "Syslog is not supported on this system. Sorry.");
3862 log_warn(LD_CONFIG
, "Unrecognized log type %s",
3863 (const char*)smartlist_get(elts
,1));
3864 if (strchr(smartlist_get(elts
,1), '/') ||
3865 strchr(smartlist_get(elts
,1), '\\')) {
3866 log_warn(LD_CONFIG
, "Did you mean to say 'Log %s file %s' ?",
3867 (const char *)smartlist_get(elts
,0),
3868 (const char *)smartlist_get(elts
,1));
3870 ok
= 0; goto cleanup
;
3873 SMARTLIST_FOREACH(elts
, char*, cp
, tor_free(cp
));
3874 smartlist_clear(elts
);
3876 smartlist_free(elts
);
3881 /** Parse a single RedirectExit line's contents from <b>line</b>. If
3882 * they are valid, and <b>result</b> is not NULL, add an element to
3883 * <b>result</b> and return 0. Else if they are valid, return 0.
3884 * Else set *msg and return -1. */
3886 parse_redirect_line(smartlist_t
*result
, config_line_t
*line
, char **msg
)
3888 smartlist_t
*elements
= NULL
;
3893 r
= tor_malloc_zero(sizeof(exit_redirect_t
));
3894 elements
= smartlist_create();
3895 smartlist_split_string(elements
, line
->value
, NULL
,
3896 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
3897 if (smartlist_len(elements
) != 2) {
3898 *msg
= tor_strdup("Wrong number of elements in RedirectExit line");
3901 if (parse_addr_and_port_range(smartlist_get(elements
,0),&r
->addr
,
3902 &r
->maskbits
,&r
->port_min
,&r
->port_max
)) {
3903 *msg
= tor_strdup("Error parsing source address in RedirectExit line");
3906 if (0==strcasecmp(smartlist_get(elements
,1), "pass")) {
3909 if (parse_addr_port(LOG_WARN
, smartlist_get(elements
,1),NULL
,
3910 &r
->addr_dest
, &r
->port_dest
)) {
3911 *msg
= tor_strdup("Error parsing dest address in RedirectExit line");
3921 SMARTLIST_FOREACH(elements
, char *, cp
, tor_free(cp
));
3922 smartlist_free(elements
);
3925 smartlist_add(result
, r
);
3935 /** Read the contents of a Bridge line from <b>line</b>. Return 0
3936 * if the line is well-formed, and -1 if it isn't. If
3937 * <b>validate_only</b> is 0, and the line is well-formed, then add
3938 * the bridge described in the line to our internal bridge list. */
3940 parse_bridge_line(const char *line
, int validate_only
)
3942 smartlist_t
*items
= NULL
;
3944 char *addrport
=NULL
, *address
=NULL
, *fingerprint
=NULL
;
3947 char digest
[DIGEST_LEN
];
3949 items
= smartlist_create();
3950 smartlist_split_string(items
, line
, NULL
,
3951 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, -1);
3952 if (smartlist_len(items
) < 1) {
3953 log_warn(LD_CONFIG
, "Too few arguments to Bridge line.");
3956 addrport
= smartlist_get(items
, 0);
3957 smartlist_del_keeporder(items
, 0);
3958 if (parse_addr_port(LOG_WARN
, addrport
, &address
, &addr
, &port
)<0) {
3959 log_warn(LD_CONFIG
, "Error parsing Bridge address '%s'", addrport
);
3963 log_warn(LD_CONFIG
, "Missing port in Bridge address '%s'",addrport
);
3967 if (smartlist_len(items
)) {
3968 fingerprint
= smartlist_join_strings(items
, "", 0, NULL
);
3969 if (strlen(fingerprint
) != HEX_DIGEST_LEN
) {
3970 log_warn(LD_CONFIG
, "Key digest for Bridge is wrong length.");
3973 if (base16_decode(digest
, DIGEST_LEN
, fingerprint
, HEX_DIGEST_LEN
)<0) {
3974 log_warn(LD_CONFIG
, "Unable to decode Bridge key digest.");
3979 if (!validate_only
) {
3980 log_debug(LD_DIR
, "Bridge at %s:%d (%s)", address
,
3982 fingerprint
? fingerprint
: "no key listed");
3983 bridge_add_from_config(addr
, port
, fingerprint
? digest
: NULL
);
3993 SMARTLIST_FOREACH(items
, char*, s
, tor_free(s
));
3994 smartlist_free(items
);
3997 tor_free(fingerprint
);
4001 /** Read the contents of a DirServer line from <b>line</b>. If
4002 * <b>validate_only</b> is 0, and the line is well-formed, and it
4003 * shares any bits with <b>required_type</b> or <b>required_type</b>
4004 * is 0, then add the dirserver described in the line (minus whatever
4005 * bits it's missing) as a valid authority. Return 0 on success,
4006 * or -1 if the line isn't well-formed or if we can't add it. */
4008 parse_dir_server_line(const char *line
, authority_type_t required_type
,
4011 smartlist_t
*items
= NULL
;
4013 char *addrport
=NULL
, *address
=NULL
, *nickname
=NULL
, *fingerprint
=NULL
;
4014 uint16_t dir_port
= 0, or_port
= 0;
4015 char digest
[DIGEST_LEN
];
4016 char v3_digest
[DIGEST_LEN
];
4017 authority_type_t type
= V2_AUTHORITY
;
4018 int is_not_hidserv_authority
= 0, is_not_v2_authority
= 0;
4020 items
= smartlist_create();
4021 smartlist_split_string(items
, line
, NULL
,
4022 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, -1);
4023 if (smartlist_len(items
) < 1) {
4024 log_warn(LD_CONFIG
, "No arguments on DirServer line.");
4028 if (is_legal_nickname(smartlist_get(items
, 0))) {
4029 nickname
= smartlist_get(items
, 0);
4030 smartlist_del_keeporder(items
, 0);
4033 while (smartlist_len(items
)) {
4034 char *flag
= smartlist_get(items
, 0);
4035 if (TOR_ISDIGIT(flag
[0]))
4037 if (!strcasecmp(flag
, "v1")) {
4038 type
|= (V1_AUTHORITY
| HIDSERV_AUTHORITY
);
4039 } else if (!strcasecmp(flag
, "hs")) {
4040 type
|= HIDSERV_AUTHORITY
;
4041 } else if (!strcasecmp(flag
, "no-hs")) {
4042 is_not_hidserv_authority
= 1;
4043 } else if (!strcasecmp(flag
, "bridge")) {
4044 type
|= BRIDGE_AUTHORITY
;
4045 } else if (!strcasecmp(flag
, "no-v2")) {
4046 is_not_v2_authority
= 1;
4047 } else if (!strcasecmpstart(flag
, "orport=")) {
4049 char *portstring
= flag
+ strlen("orport=");
4050 or_port
= (uint16_t) tor_parse_long(portstring
, 10, 1, 65535, &ok
, NULL
);
4052 log_warn(LD_CONFIG
, "Invalid orport '%s' on DirServer line.",
4054 } else if (!strcasecmpstart(flag
, "v3ident=")) {
4055 char *idstr
= flag
+ strlen("v3ident=");
4056 if (strlen(idstr
) != HEX_DIGEST_LEN
||
4057 base16_decode(v3_digest
, DIGEST_LEN
, idstr
, HEX_DIGEST_LEN
)<0) {
4058 log_warn(LD_CONFIG
, "Bad v3 identity digest '%s' on DirServer line",
4061 type
|= V3_AUTHORITY
;
4064 log_warn(LD_CONFIG
, "Unrecognized flag '%s' on DirServer line",
4068 smartlist_del_keeporder(items
, 0);
4070 if (is_not_hidserv_authority
)
4071 type
&= ~HIDSERV_AUTHORITY
;
4072 if (is_not_v2_authority
)
4073 type
&= ~V2_AUTHORITY
;
4075 if (smartlist_len(items
) < 2) {
4076 log_warn(LD_CONFIG
, "Too few arguments to DirServer line.");
4079 addrport
= smartlist_get(items
, 0);
4080 smartlist_del_keeporder(items
, 0);
4081 if (parse_addr_port(LOG_WARN
, addrport
, &address
, NULL
, &dir_port
)<0) {
4082 log_warn(LD_CONFIG
, "Error parsing DirServer address '%s'", addrport
);
4086 log_warn(LD_CONFIG
, "Missing port in DirServer address '%s'",addrport
);
4090 fingerprint
= smartlist_join_strings(items
, "", 0, NULL
);
4091 if (strlen(fingerprint
) != HEX_DIGEST_LEN
) {
4092 log_warn(LD_CONFIG
, "Key digest for DirServer is wrong length %d.",
4093 (int)strlen(fingerprint
));
4096 if (!strcmp(fingerprint
, "E623F7625FBE0C87820F11EC5F6D5377ED816294")) {
4097 /* a known bad fingerprint. refuse to use it. We can remove this
4098 * clause once Tor 0.1.2.17 is obsolete. */
4099 log_warn(LD_CONFIG
, "Dangerous dirserver line. To correct, erase your "
4100 "torrc file (%s), or reinstall Tor and use the default torrc.",
4104 if (base16_decode(digest
, DIGEST_LEN
, fingerprint
, HEX_DIGEST_LEN
)<0) {
4105 log_warn(LD_CONFIG
, "Unable to decode DirServer key digest.");
4109 if (!validate_only
&& (!required_type
|| required_type
& type
)) {
4111 type
&= required_type
; /* pare down what we think of them as an
4113 log_debug(LD_DIR
, "Trusted %d dirserver at %s:%d (%s)", (int)type
,
4114 address
, (int)dir_port
, (char*)smartlist_get(items
,0));
4115 if (!add_trusted_dir_server(nickname
, address
, dir_port
, or_port
,
4116 digest
, v3_digest
, type
))
4127 SMARTLIST_FOREACH(items
, char*, s
, tor_free(s
));
4128 smartlist_free(items
);
4132 tor_free(fingerprint
);
4136 /** Adjust the value of options->DataDirectory, or fill it in if it's
4137 * absent. Return 0 on success, -1 on failure. */
4139 normalize_data_directory(or_options_t
*options
)
4143 if (options
->DataDirectory
)
4144 return 0; /* all set */
4145 p
= tor_malloc(MAX_PATH
);
4146 strlcpy(p
,get_windows_conf_root(),MAX_PATH
);
4147 options
->DataDirectory
= p
;
4150 const char *d
= options
->DataDirectory
;
4154 if (strncmp(d
,"~/",2) == 0) {
4155 char *fn
= expand_filename(d
);
4157 log_warn(LD_CONFIG
,"Failed to expand filename \"%s\".", d
);
4160 if (!options
->DataDirectory
&& !strcmp(fn
,"/.tor")) {
4161 /* If our homedir is /, we probably don't want to use it. */
4162 /* Default to LOCALSTATEDIR/tor which is probably closer to what we
4165 "Default DataDirectory is \"~/.tor\". This expands to "
4166 "\"%s\", which is probably not what you want. Using "
4167 "\"%s"PATH_SEPARATOR
"tor\" instead
", fn, LOCALSTATEDIR);
4169 fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor
");
4171 tor_free(options->DataDirectory);
4172 options->DataDirectory = fn;
4178 /** Check and normalize the value of options->DataDirectory; return 0 if it
4179 * sane, -1 otherwise. */
4181 validate_data_directory(or_options_t *options)
4183 if (normalize_data_directory(options) < 0)
4185 tor_assert(options->DataDirectory);
4186 if (strlen(options->DataDirectory) > (512-128)) {
4187 log_warn(LD_CONFIG, "DataDirectory is too
long.");
4193 /** This string must remain the same forevermore. It is how we
4194 * recognize that the torrc file doesn't need to be backed up. */
4195 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
4196 "if you edit it, comments will not be preserved"
4197 /** This string can change; it tries to give the reader an idea
4198 * that editing this file by hand is not a good plan. */
4199 #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
4200 "to torrc.orig.1 or similar, and Tor will ignore it"
4202 /** Save a configuration file for the configuration in <b>options</b>
4203 * into the file <b>fname</b>. If the file already exists, and
4204 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
4205 * replace it. Return 0 on success, -1 on failure. */
4207 write_configuration_file(const char *fname, or_options_t *options)
4209 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
4210 int rename_old = 0, r;
4214 switch (file_status(fname)) {
4216 old_val = read_file_to_str(fname, 0, NULL);
4217 if (strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
4228 "Config file \"%s\" is not a file? Failing.", fname);
4233 if (!(new_conf = options_dump(options, 1))) {
4234 log_warn(LD_BUG, "Couldn't get configuration string");
4238 len = strlen(new_conf)+256;
4239 new_val = tor_malloc(len);
4240 tor_snprintf(new_val, len, "%s\n%s\n\n%s",
4241 GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
4245 size_t fn_tmp_len = strlen(fname)+32;
4247 tor_assert(fn_tmp_len > strlen(fname)); /*check for overflow*/
4248 fn_tmp = tor_malloc(fn_tmp_len);
4250 if (tor_snprintf(fn_tmp, fn_tmp_len, "%s.orig.%d", fname, i)<0) {
4251 log_warn(LD_BUG, "tor_snprintf failed inexplicably");
4255 if (file_status(fn_tmp) == FN_NOENT)
4259 log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
4260 if (rename(fname, fn_tmp) < 0) {
4262 "Couldn't rename configuration file \"%s\" to \"%s\": %s",
4263 fname, fn_tmp, strerror(errno));
4270 if (write_str_to_file(fname, new_val, 0) < 0)
4284 * Save the current configuration file value to disk. Return 0 on
4285 * success, -1 on failure.
4288 options_save_current(void)
4291 /* This fails if we can't write to our configuration file.
4293 * If we try falling back to datadirectory or something, we have a better
4294 * chance of saving the configuration, but a better chance of doing
4295 * something the user never expected. Let's just warn instead. */
4296 return write_configuration_file(torrc_fname, get_options());
4298 return write_configuration_file(get_default_conf_file(), get_options());
4301 /** Mapping from a unit name to a multiplier for converting that unit into a
4303 struct unit_table_t {
4305 uint64_t multiplier;
4308 static struct unit_table_t memory_units[] = {
4315 { "kbytes", 1<<10 },
4316 { "kilobyte", 1<<10 },
4317 { "kilobytes", 1<<10 },
4321 { "mbytes", 1<<20 },
4322 { "megabyte", 1<<20 },
4323 { "megabytes", 1<<20 },
4326 { "gbytes", 1<<30 },
4327 { "gigabyte", 1<<30 },
4328 { "gigabytes", 1<<30 },
4329 { "tb", U64_LITERAL(1)<<40 },
4330 { "terabyte", U64_LITERAL(1)<<40 },
4331 { "terabytes", U64_LITERAL(1)<<40 },
4335 static struct unit_table_t time_units[] = {
4343 { "day", 24*60*60 },
4344 { "days", 24*60*60 },
4345 { "week", 7*24*60*60 },
4346 { "weeks", 7*24*60*60 },
4350 /** Parse a string <b>val</b> containing a number, zero or more
4351 * spaces, and an optional unit string. If the unit appears in the
4352 * table <b>u</b>, then multiply the number by the unit multiplier.
4353 * On success, set *<b>ok</b> to 1 and return this product.
4354 * Otherwise, set *<b>ok</b> to 0.
4357 config_parse_units(const char *val, struct unit_table_t *u, int *ok)
4364 v = tor_parse_uint64(val, 10, 0, UINT64_MAX, ok, &cp);
4371 while (TOR_ISSPACE(*cp))
4373 for ( ;u->unit;++u) {
4374 if (!strcasecmp(u->unit, cp)) {
4380 log_warn(LD_CONFIG, "Unknown unit '%s'.", cp);
4385 /** Parse a string in the format "number unit", where unit is a unit of
4386 * information (byte, KB, M, etc). On success, set *<b>ok</b> to true
4387 * and return the number of bytes specified. Otherwise, set
4388 * *<b>ok</b> to false and return 0. */
4390 config_parse_memunit(const char *s, int *ok)
4392 return config_parse_units(s, memory_units, ok);
4395 /** Parse a string in the format "number unit", where unit is a unit of time.
4396 * On success, set *<b>ok</b> to true and return the number of seconds in
4397 * the provided interval. Otherwise, set *<b>ok</b> to 0 and return -1.
4400 config_parse_interval(const char *s, int *ok)
4403 r = config_parse_units(s, time_units, ok);
4407 log_warn(LD_CONFIG, "Interval '%s' is too long", s);
4415 * Initialize the libevent library.
4420 configure_libevent_logging();
4421 /* If the kernel complains that some method (say, epoll) doesn't
4422 * exist, we don't care about it, since libevent will cope.
4424 suppress_libevent_log_msg("Function not implemented");
4426 if (decode_libevent_version() < LE_11B) {
4427 setenv("EVENT_NOKQUEUE","1",1);
4431 suppress_libevent_log_msg(NULL);
4432 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
4433 /* Making this a NOTICE for now so we can link bugs to a libevent versions
4434 * or methods better. */
4435 log(LOG_NOTICE, LD_GENERAL,
4436 "Initialized libevent version %s using method %s. Good.",
4437 event_get_version(), event_get_method());
4438 check_libevent_version(event_get_method(), get_options()->ORPort != 0);
4440 log(LOG_NOTICE, LD_GENERAL,
4441 "Initialized old libevent (version 1.0b or earlier).");
4442 log(LOG_WARN, LD_GENERAL,
4443 "You have a *VERY* old version of libevent. It is likely to be buggy; "
4444 "please build Tor with a more recent version.");
4448 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
4449 /** Table mapping return value of event_get_version() to le_version_t. */
4450 static const struct {
4451 const char *name; le_version_t version;
4452 } le_version_table[] = {
4453 /* earlier versions don't have get_version. */
4470 /** Return the le_version_t for the current version of libevent. If the
4471 * version is very new, return LE_OTHER. If the version is so old that it
4472 * doesn't support event_get_version(), return LE_OLD. */
4474 decode_libevent_version(void)
4476 const char *v = event_get_version();
4478 for (i=0; le_version_table[i].name; ++i) {
4479 if (!strcmp(le_version_table[i].name, v)) {
4480 return le_version_table[i].version;
4487 * Compare the given libevent method and version to a list of versions
4488 * which are known not to work. Warn the user as appropriate.
4491 check_libevent_version(const char *m, int server)
4493 int buggy = 0, iffy = 0, slow = 0, thread_unsafe = 0;
4494 le_version_t version;
4495 const char *v = event_get_version();
4496 const char *badness = NULL;
4497 const char *sad_os = "";
4499 version = decode_libevent_version();
4501 /* XXX Would it be worthwhile disabling the methods that we know
4502 * are buggy, rather than just warning about them and then proceeding
4503 * to use them? If so, we should probably not wrap this whole thing
4504 * in HAVE_EVENT_GET_VERSION and HAVE_EVENT_GET_METHOD. -RD */
4505 /* XXXX The problem is that it's not trivial to get libevent to change it's
4506 * method once it's initialized, and it's not trivial to tell what method it
4507 * will use without initializing it. I guess we could preemptively disable
4508 * buggy libevent modes based on the version _before_ initializing it,
4509 * though, but then there's no good way (afaict) to warn "I would have used
4510 * kqueue
, but instead I
'm using select." -NM */
4511 if (!strcmp(m, "kqueue")) {
4512 if (version < LE_11B)
4514 } else if (!strcmp(m, "epoll")) {
4515 if (version < LE_11)
4517 } else if (!strcmp(m, "poll")) {
4518 if (version < LE_10E)
4520 else if (version < LE_11)
4522 } else if (!strcmp(m, "select")) {
4523 if (version < LE_11)
4525 } else if (!strcmp(m, "win32")) {
4526 if (version < LE_11B)
4530 /* Libevent versions before 1.3b do very badly on operating systems with
4531 * user-space threading implementations. */
4532 #if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__)
4533 if (server && version < LE_13B) {
4535 sad_os = "BSD variants";
4537 #elif defined(__APPLE__) || defined(__darwin__)
4538 if (server && version < LE_13B) {
4540 sad_os = "Mac OS X";
4544 if (thread_unsafe) {
4545 log(LOG_WARN, LD_GENERAL,
4546 "Libevent version %s often crashes when running a Tor server with %s. "
4547 "Please use the latest version of libevent (1.3b or later)",v,sad_os);
4550 log(LOG_WARN, LD_GENERAL,
4551 "There are serious bugs in using %s with libevent %s. "
4552 "Please use the latest version of libevent.", m, v);
4555 log(LOG_WARN, LD_GENERAL,
4556 "There are minor bugs in using %s with libevent %s. "
4557 "You may want to use the latest version of libevent.", m, v);
4559 } else if (slow && server) {
4560 log(LOG_WARN, LD_GENERAL,
4561 "libevent %s can be very slow with %s. "
4562 "When running a server, please use the latest version of libevent.",
4567 control_event_general_status(LOG_WARN,
4568 "BAD_LIBEVENT VERSION=%s METHOD=%s BADNESS=%s RECOVERED=NO",
4575 decode_libevent_version(void)
4581 /** Return the persistent state struct for this Tor. */
4585 tor_assert(global_state);
4586 return global_state;
4589 /** Return a newly allocated string holding a filename relative to the data
4590 * directory. If <b>sub1</b> is present, it is the first path component after
4591 * the data directory. If <b>sub2</b> is also present, it is the second path
4592 * component after the data directory. If <b>suffix</b> is present, it
4593 * is appended to the filename.
4596 * get_datadir_fname2_suffix("a", NULL, NULL) -> $DATADIR/a
4597 * get_datadir_fname2_suffix("a", NULL, ".tmp") -> $DATADIR/a.tmp
4598 * get_datadir_fname2_suffix("a", "b", ".tmp") -> $DATADIR/a/b/.tmp
4599 * get_datadir_fname2_suffix("a", "b", NULL) -> $DATADIR/a/b
4601 * Note: Consider using the get_datadir_fname* macros in or.h.
4604 get_datadir_fname2_suffix(const char *sub1, const char *sub2,
4607 or_options_t *options = get_options();
4610 tor_assert(options);
4611 tor_assert(options->DataDirectory);
4612 tor_assert(sub1 || !sub2); /* If sub2 is present, sub1 must be present. */
4613 len = strlen(options->DataDirectory);
4615 len += strlen(sub1)+1;
4617 len += strlen(sub2)+1;
4620 len += strlen(suffix);
4622 fname = tor_malloc(len);
4625 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s",
4626 options->DataDirectory, sub1, sub2);
4628 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s",
4629 options->DataDirectory, sub1);
4632 strlcpy(fname, options->DataDirectory, len);
4635 strlcat(fname, suffix, len);
4639 /** Return 0 if every setting in <b>state</b> is reasonable, and a
4640 * permissible transition from <b>old_state</b>. Else warn and return -1.
4641 * Should have no side effects, except for normalizing the contents of
4644 /* XXX from_setconf is here because of bug 238 */
4646 or_state_validate(or_state_t *old_state, or_state_t *state,
4647 int from_setconf, char **msg)
4649 /* We don't use these
; only options
do. Still
, we need to match that
4651 (void) from_setconf
;
4654 if (entry_guards_parse_state(state
, 0, msg
)<0)
4660 /** Replace the current persistent state with <b>new_state</b> */
4662 or_state_set(or_state_t
*new_state
)
4665 tor_assert(new_state
);
4667 config_free(&state_format
, global_state
);
4668 global_state
= new_state
;
4669 if (entry_guards_parse_state(global_state
, 1, &err
)<0) {
4670 log_warn(LD_GENERAL
,"%s",err
);
4673 if (rep_hist_load_state(global_state
, &err
)<0) {
4674 log_warn(LD_GENERAL
,"Unparseable bandwidth history state: %s",err
);
4679 /** Reload the persistent state from disk, generating a new state as needed.
4680 * Return 0 on success, less than 0 on failure.
4685 or_state_t
*new_state
= NULL
;
4686 char *contents
= NULL
, *fname
;
4687 char *errmsg
= NULL
;
4688 int r
= -1, badstate
= 0;
4690 fname
= get_datadir_fname("state");
4691 switch (file_status(fname
)) {
4693 if (!(contents
= read_file_to_str(fname
, 0, NULL
))) {
4694 log_warn(LD_FS
, "Unable to read state file \"%s\"", fname
);
4703 log_warn(LD_GENERAL
,"State file \"%s\" is not a file? Failing.", fname
);
4706 new_state
= tor_malloc_zero(sizeof(or_state_t
));
4707 new_state
->_magic
= OR_STATE_MAGIC
;
4708 config_init(&state_format
, new_state
);
4710 config_line_t
*lines
=NULL
;
4712 if (config_get_lines(contents
, &lines
)<0)
4714 assign_retval
= config_assign(&state_format
, new_state
,
4715 lines
, 0, 0, &errmsg
);
4716 config_free_lines(lines
);
4717 if (assign_retval
<0)
4720 log_warn(LD_GENERAL
, "%s", errmsg
);
4725 if (!badstate
&& or_state_validate(NULL
, new_state
, 1, &errmsg
) < 0)
4729 log_warn(LD_GENERAL
, "%s", errmsg
);
4733 if (badstate
&& !contents
) {
4734 log_warn(LD_BUG
, "Uh oh. We couldn't even validate our own default state."
4735 " This is a bug in Tor.");
4737 } else if (badstate
&& contents
) {
4739 file_status_t status
;
4740 size_t len
= strlen(fname
)+16;
4741 char *fname2
= tor_malloc(len
);
4742 for (i
= 0; i
< 100; ++i
) {
4743 tor_snprintf(fname2
, len
, "%s.%d", fname
, i
);
4744 status
= file_status(fname2
);
4745 if (status
== FN_NOENT
)
4749 log_warn(LD_BUG
, "Unable to parse state in \"%s\"; too many saved bad "
4750 "state files to move aside. Discarding the old state file.",
4754 log_warn(LD_BUG
, "Unable to parse state in \"%s\". Moving it aside "
4755 "to \"%s\". This could be a bug in Tor; please tell "
4756 "the developers.", fname
, fname2
);
4757 if (rename(fname
, fname2
) < 0) {
4758 log_warn(LD_BUG
, "Weirdly, I couldn't even move the state aside. The "
4759 "OS gave an error of %s", strerror(errno
));
4764 config_free(&state_format
, new_state
);
4766 new_state
= tor_malloc_zero(sizeof(or_state_t
));
4767 new_state
->_magic
= OR_STATE_MAGIC
;
4768 config_init(&state_format
, new_state
);
4769 } else if (contents
) {
4770 log_info(LD_GENERAL
, "Loaded state from \"%s\"", fname
);
4772 log_info(LD_GENERAL
, "Initialized state");
4774 or_state_set(new_state
);
4777 global_state
->next_write
= 0;
4778 or_state_save(time(NULL
));
4786 config_free(&state_format
, new_state
);
4791 /** Write the persistent state to disk. Return 0 for success, <0 on failure. */
4793 or_state_save(time_t now
)
4795 char *state
, *contents
;
4796 char tbuf
[ISO_TIME_LEN
+1];
4800 tor_assert(global_state
);
4802 if (global_state
->next_write
> now
)
4805 /* Call everything else that might dirty the state even more, in order
4806 * to avoid redundant writes. */
4807 entry_guards_update_state(global_state
);
4808 rep_hist_update_state(global_state
);
4809 if (accounting_is_enabled(get_options()))
4810 accounting_run_housekeeping(now
);
4812 global_state
->LastWritten
= time(NULL
);
4813 tor_free(global_state
->TorVersion
);
4814 len
= strlen(get_version())+8;
4815 global_state
->TorVersion
= tor_malloc(len
);
4816 tor_snprintf(global_state
->TorVersion
, len
, "Tor %s", get_version());
4818 state
= config_dump(&state_format
, global_state
, 1, 0);
4819 len
= strlen(state
)+256;
4820 contents
= tor_malloc(len
);
4821 format_local_iso_time(tbuf
, time(NULL
));
4822 tor_snprintf(contents
, len
,
4823 "# Tor state file last generated on %s local time\n"
4824 "# Other times below are in GMT\n"
4825 "# You *do not* need to edit this file.\n\n%s",
4828 fname
= get_datadir_fname("state");
4829 if (write_str_to_file(fname
, contents
, 0)<0) {
4830 log_warn(LD_FS
, "Unable to write state to file \"%s\"", fname
);
4835 log_info(LD_GENERAL
, "Saved state to \"%s\"", fname
);
4839 global_state
->next_write
= TIME_MAX
;
4843 /** Given a file name check to see whether the file exists but has not been
4844 * modified for a very long time. If so, remove it. */
4846 remove_file_if_very_old(const char *fname
, time_t now
)
4848 #define VERY_OLD_FILE_AGE (28*24*60*60)
4851 if (stat(fname
, &st
)==0 && st
.st_mtime
< now
-VERY_OLD_FILE_AGE
) {
4852 char buf
[ISO_TIME_LEN
+1];
4853 format_local_iso_time(buf
, st
.st_mtime
);
4854 log_notice(LD_GENERAL
, "Obsolete file %s hasn't been modified since %s. "
4855 "Removing it.", fname
, buf
);
4860 /** Helper to implement GETINFO functions about configuration variables (not
4861 * their values). Given a "config/names" question, set *<b>answer</b> to a
4862 * new string describing the supported configuration variables and their
4865 getinfo_helper_config(control_connection_t
*conn
,
4866 const char *question
, char **answer
)
4869 if (!strcmp(question
, "config/names")) {
4870 smartlist_t
*sl
= smartlist_create();
4872 for (i
= 0; _option_vars
[i
].name
; ++i
) {
4873 config_var_t
*var
= &_option_vars
[i
];
4874 const char *type
, *desc
;
4877 desc
= config_find_description(&options_format
, var
->name
);
4878 switch (var
->type
) {
4879 case CONFIG_TYPE_STRING
: type
= "String"; break;
4880 case CONFIG_TYPE_UINT
: type
= "Integer"; break;
4881 case CONFIG_TYPE_INTERVAL
: type
= "TimeInterval"; break;
4882 case CONFIG_TYPE_MEMUNIT
: type
= "DataSize"; break;
4883 case CONFIG_TYPE_DOUBLE
: type
= "Float"; break;
4884 case CONFIG_TYPE_BOOL
: type
= "Boolean"; break;
4885 case CONFIG_TYPE_ISOTIME
: type
= "Time"; break;
4886 case CONFIG_TYPE_CSV
: type
= "CommaList"; break;
4887 case CONFIG_TYPE_LINELIST
: type
= "LineList"; break;
4888 case CONFIG_TYPE_LINELIST_S
: type
= "Dependant"; break;
4889 case CONFIG_TYPE_LINELIST_V
: type
= "Virtual"; break;
4891 case CONFIG_TYPE_OBSOLETE
:
4896 len
= strlen(var
->name
)+strlen(type
)+16;
4898 len
+= strlen(desc
);
4899 line
= tor_malloc(len
);
4901 tor_snprintf(line
, len
, "%s %s %s\n",var
->name
,type
,desc
);
4903 tor_snprintf(line
, len
, "%s %s\n",var
->name
,type
);
4904 smartlist_add(sl
, line
);
4906 *answer
= smartlist_join_strings(sl
, "", 0, NULL
);
4907 SMARTLIST_FOREACH(sl
, char *, c
, tor_free(c
));
4917 extern const char aes_c_id
[];
4918 extern const char compat_c_id
[];
4919 extern const char container_c_id
[];
4920 extern const char crypto_c_id
[];
4921 extern const char log_c_id
[];
4922 extern const char torgzip_c_id
[];
4923 extern const char tortls_c_id
[];
4924 extern const char util_c_id
[];
4926 extern const char buffers_c_id
[];
4927 extern const char circuitbuild_c_id
[];
4928 extern const char circuitlist_c_id
[];
4929 extern const char circuituse_c_id
[];
4930 extern const char command_c_id
[];
4931 // extern const char config_c_id[];
4932 extern const char connection_c_id
[];
4933 extern const char connection_edge_c_id
[];
4934 extern const char connection_or_c_id
[];
4935 extern const char control_c_id
[];
4936 extern const char cpuworker_c_id
[];
4937 extern const char directory_c_id
[];
4938 extern const char dirserv_c_id
[];
4939 extern const char dns_c_id
[];
4940 extern const char hibernate_c_id
[];
4941 extern const char main_c_id
[];
4943 extern const char ntmain_c_id
[];
4945 extern const char onion_c_id
[];
4946 extern const char policies_c_id
[];
4947 extern const char relay_c_id
[];
4948 extern const char rendclient_c_id
[];
4949 extern const char rendcommon_c_id
[];
4950 extern const char rendmid_c_id
[];
4951 extern const char rendservice_c_id
[];
4952 extern const char rephist_c_id
[];
4953 extern const char router_c_id
[];
4954 extern const char routerlist_c_id
[];
4955 extern const char routerparse_c_id
[];
4957 /** Dump the version of every file to the log. */
4959 print_svn_version(void)
4963 puts(CONTAINER_H_ID
);
4974 puts(container_c_id
);
4983 puts(circuitbuild_c_id
);
4984 puts(circuitlist_c_id
);
4985 puts(circuituse_c_id
);
4988 puts(connection_c_id
);
4989 puts(connection_edge_c_id
);
4990 puts(connection_or_c_id
);
4992 puts(cpuworker_c_id
);
4993 puts(directory_c_id
);
4996 puts(hibernate_c_id
);
5002 puts(policies_c_id
);
5004 puts(rendclient_c_id
);
5005 puts(rendcommon_c_id
);
5007 puts(rendservice_c_id
);
5010 puts(routerlist_c_id
);
5011 puts(routerparse_c_id
);