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},
89 /* A list of state-file abbreviations, for compatibility. */
90 static config_abbrev_t _state_abbrevs
[] = {
91 { "AccountingBytesReadInterval", "AccountingBytesReadInInterval", 0, 0 },
92 { "HelperNode", "EntryGuard", 0, 0 },
93 { "HelperNodeDownSince", "EntryGuardDownSince", 0, 0 },
94 { "HelperNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
95 { "EntryNode", "EntryGuard", 0, 0 },
96 { "EntryNodeDownSince", "EntryGuardDownSince", 0, 0 },
97 { "EntryNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
102 /** A variable allowed in the configuration file or on the command line. */
103 typedef struct config_var_t
{
104 const char *name
; /**< The full keyword (case insensitive). */
105 config_type_t type
; /**< How to interpret the type and turn it into a
107 off_t var_offset
; /**< Offset of the corresponding member of or_options_t. */
108 const char *initvalue
; /**< String (or null) describing initial value. */
111 /** An entry for config_vars: "The option <b>name</b> has type
112 * CONFIG_TYPE_<b>conftype</b>, and corresponds to
113 * or_options_t.<b>member</b>"
115 #define VAR(name,conftype,member,initvalue) \
116 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_options_t, member), \
118 /** As VAR, but the option name and member name are the same. */
119 #define V(member,conftype,initvalue) \
120 VAR(#member, conftype, member, initvalue)
121 /** An entry for config_vars: "The option <b>name</b> is obsolete." */
122 #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL }
124 /** Array of configuration options. Until we disallow nonstandard
125 * abbreviations, order is significant, since the first matching option will
128 static config_var_t _option_vars
[] = {
129 OBSOLETE("AccountingMaxKB"),
130 V(AccountingMax
, MEMUNIT
, "0 bytes"),
131 V(AccountingStart
, STRING
, NULL
),
132 V(Address
, STRING
, NULL
),
133 V(AllowInvalidNodes
, CSV
, "middle,rendezvous"),
134 V(AllowNonRFC953Hostnames
, BOOL
, "0"),
135 V(AlternateBridgeAuthority
, LINELIST
, NULL
),
136 V(AlternateDirAuthority
, LINELIST
, NULL
),
137 V(AlternateHSAuthority
, LINELIST
, NULL
),
138 V(AssumeReachable
, BOOL
, "0"),
139 V(AuthDirBadDir
, LINELIST
, NULL
),
140 V(AuthDirBadExit
, LINELIST
, NULL
),
141 V(AuthDirInvalid
, LINELIST
, NULL
),
142 V(AuthDirReject
, LINELIST
, NULL
),
143 V(AuthDirRejectUnlisted
, BOOL
, "0"),
144 V(AuthDirListBadDirs
, BOOL
, "0"),
145 V(AuthDirListBadExits
, BOOL
, "0"),
146 V(AuthDirMaxServersPerAddr
, UINT
, "2"),
147 V(AuthDirMaxServersPerAuthAddr
,UINT
, "5"),
148 VAR("AuthoritativeDirectory", BOOL
, AuthoritativeDir
, "0"),
149 V(AutomapHostsOnResolve
, BOOL
, "0"),
150 V(AutomapHostsSuffixes
, CSV
, ".onion,.exit"),
151 V(AvoidDiskWrites
, BOOL
, "0"),
152 V(BandwidthBurst
, MEMUNIT
, "10 MB"),
153 V(BandwidthRate
, MEMUNIT
, "5 MB"),
154 V(BridgeAuthoritativeDir
, BOOL
, "0"),
155 VAR("Bridge", LINELIST
, Bridges
, NULL
),
156 V(BridgePassword
, STRING
, NULL
),
157 V(BridgeRecordUsageByCountry
, BOOL
, "1"),
158 V(BridgeRelay
, BOOL
, "0"),
159 V(CircuitBuildTimeout
, INTERVAL
, "1 minute"),
160 V(CircuitIdleTimeout
, INTERVAL
, "1 hour"),
161 V(ClientDNSRejectInternalAddresses
, BOOL
,"1"),
162 V(ClientOnly
, BOOL
, "0"),
163 V(ConnLimit
, UINT
, "1000"),
164 V(ConstrainedSockets
, BOOL
, "0"),
165 V(ConstrainedSockSize
, MEMUNIT
, "8192"),
166 V(ContactInfo
, STRING
, NULL
),
167 V(ControlListenAddress
, LINELIST
, NULL
),
168 V(ControlPort
, UINT
, "0"),
169 V(ControlSocket
, LINELIST
, NULL
),
170 V(CookieAuthentication
, BOOL
, "0"),
171 V(CookieAuthFileGroupReadable
, BOOL
, "0"),
172 V(CookieAuthFile
, STRING
, NULL
),
173 V(DataDirectory
, STRING
, NULL
),
174 OBSOLETE("DebugLogFile"),
175 V(DirAllowPrivateAddresses
, BOOL
, NULL
),
176 V(DirListenAddress
, LINELIST
, NULL
),
177 OBSOLETE("DirFetchPeriod"),
178 V(DirPolicy
, LINELIST
, NULL
),
179 V(DirPort
, UINT
, "0"),
180 OBSOLETE("DirPostPeriod"),
181 VAR("DirServer", LINELIST
, DirServers
, NULL
),
182 V(DNSPort
, UINT
, "0"),
183 V(DNSListenAddress
, LINELIST
, NULL
),
184 V(DownloadExtraInfo
, BOOL
, "0"),
185 V(EnforceDistinctSubnets
, BOOL
, "1"),
186 V(EntryNodes
, STRING
, NULL
),
187 V(ExcludeNodes
, STRING
, NULL
),
188 V(ExitNodes
, STRING
, NULL
),
189 V(ExitPolicy
, LINELIST
, NULL
),
190 V(ExitPolicyRejectPrivate
, BOOL
, "1"),
191 V(FallbackNetworkstatusFile
, STRING
,
192 SHARE_DATADIR PATH_SEPARATOR
"tor" PATH_SEPARATOR
"fallback-consensus"),
193 V(FascistFirewall
, BOOL
, "0"),
194 V(FirewallPorts
, CSV
, ""),
195 V(FastFirstHopPK
, BOOL
, "1"),
196 V(FetchDirInfoEarly
, BOOL
, "0"),
197 V(FetchServerDescriptors
, BOOL
, "1"),
198 V(FetchHidServDescriptors
, BOOL
, "1"),
199 V(FetchUselessDescriptors
, BOOL
, "0"),
200 V(GeoIPFile
, STRING
, NULL
),
201 V(Group
, STRING
, NULL
),
202 V(HardwareAccel
, BOOL
, "0"),
203 V(HashedControlPassword
, LINELIST
, NULL
),
204 V(HidServDirectoryV2
, BOOL
, "0"),
205 VAR("HiddenServiceDir", LINELIST_S
, RendConfigLines
, NULL
),
206 VAR("HiddenServiceExcludeNodes", LINELIST_S
, RendConfigLines
, NULL
),
207 VAR("HiddenServiceNodes", LINELIST_S
, RendConfigLines
, NULL
),
208 VAR("HiddenServiceOptions",LINELIST_V
, RendConfigLines
, NULL
),
209 VAR("HiddenServicePort", LINELIST_S
, RendConfigLines
, NULL
),
210 VAR("HiddenServiceVersion",LINELIST_S
, RendConfigLines
, NULL
),
211 V(HSAuthoritativeDir
, BOOL
, "0"),
212 V(HSAuthorityRecordStats
, BOOL
, "0"),
213 V(HttpProxy
, STRING
, NULL
),
214 V(HttpProxyAuthenticator
, STRING
, NULL
),
215 V(HttpsProxy
, STRING
, NULL
),
216 V(HttpsProxyAuthenticator
, STRING
, NULL
),
217 OBSOLETE("IgnoreVersion"),
218 V(KeepalivePeriod
, INTERVAL
, "5 minutes"),
219 VAR("Log", LINELIST
, Logs
, NULL
),
220 OBSOLETE("LinkPadding"),
221 OBSOLETE("LogLevel"),
223 V(LongLivedPorts
, CSV
,
224 "21,22,706,1863,5050,5190,5222,5223,6667,6697,8300"),
225 VAR("MapAddress", LINELIST
, AddressMap
, NULL
),
226 V(MaxAdvertisedBandwidth
, MEMUNIT
, "1 GB"),
227 V(MaxCircuitDirtiness
, INTERVAL
, "10 minutes"),
228 V(MaxOnionsPending
, UINT
, "100"),
229 OBSOLETE("MonthlyAccountingStart"),
230 V(MyFamily
, STRING
, NULL
),
231 V(NewCircuitPeriod
, INTERVAL
, "30 seconds"),
232 VAR("NamingAuthoritativeDirectory",BOOL
, NamingAuthoritativeDir
, "0"),
233 V(NatdListenAddress
, LINELIST
, NULL
),
234 V(NatdPort
, UINT
, "0"),
235 V(Nickname
, STRING
, NULL
),
236 V(NoPublish
, BOOL
, "0"),
237 VAR("NodeFamily", LINELIST
, NodeFamilies
, NULL
),
238 V(NumCpus
, UINT
, "1"),
239 V(NumEntryGuards
, UINT
, "3"),
240 V(ORListenAddress
, LINELIST
, NULL
),
241 V(ORPort
, UINT
, "0"),
242 V(OutboundBindAddress
, STRING
, NULL
),
243 OBSOLETE("PathlenCoinWeight"),
244 V(PidFile
, STRING
, NULL
),
245 V(PreferTunneledDirConns
, BOOL
, "0"),
246 V(ProtocolWarnings
, BOOL
, "0"),
247 V(PublishServerDescriptor
, CSV
, "1"),
248 V(PublishHidServDescriptors
, BOOL
, "1"),
249 V(ReachableAddresses
, LINELIST
, NULL
),
250 V(ReachableDirAddresses
, LINELIST
, NULL
),
251 V(ReachableORAddresses
, LINELIST
, NULL
),
252 V(RecommendedVersions
, LINELIST
, NULL
),
253 V(RecommendedClientVersions
, LINELIST
, NULL
),
254 V(RecommendedServerVersions
, LINELIST
, NULL
),
255 V(RedirectExit
, LINELIST
, NULL
),
256 V(RejectPlaintextPorts
, CSV
, ""),
257 V(RelayBandwidthBurst
, MEMUNIT
, "0"),
258 V(RelayBandwidthRate
, MEMUNIT
, "0"),
259 V(RendExcludeNodes
, STRING
, NULL
),
260 V(RendNodes
, STRING
, NULL
),
261 V(RendPostPeriod
, INTERVAL
, "1 hour"),
262 V(RephistTrackTime
, INTERVAL
, "24 hours"),
263 OBSOLETE("RouterFile"),
264 V(RunAsDaemon
, BOOL
, "0"),
265 V(RunTesting
, BOOL
, "0"),
266 V(SafeLogging
, BOOL
, "1"),
267 V(SafeSocks
, BOOL
, "0"),
268 V(ServerDNSAllowNonRFC953Hostnames
, BOOL
,"0"),
269 V(ServerDNSDetectHijacking
, BOOL
, "1"),
270 V(ServerDNSResolvConfFile
, STRING
, NULL
),
271 V(ServerDNSSearchDomains
, BOOL
, "0"),
272 V(ServerDNSTestAddresses
, CSV
,
273 "www.google.com,www.mit.edu,www.yahoo.com,www.slashdot.org"),
274 V(ShutdownWaitLength
, INTERVAL
, "30 seconds"),
275 V(SocksListenAddress
, LINELIST
, NULL
),
276 V(SocksPolicy
, LINELIST
, NULL
),
277 V(SocksPort
, UINT
, "9050"),
278 V(SocksTimeout
, INTERVAL
, "2 minutes"),
279 OBSOLETE("StatusFetchPeriod"),
280 V(StrictEntryNodes
, BOOL
, "0"),
281 V(StrictExitNodes
, BOOL
, "0"),
283 V(TestSocks
, BOOL
, "0"),
284 V(TestVia
, STRING
, NULL
),
285 V(TrackHostExits
, CSV
, NULL
),
286 V(TrackHostExitsExpire
, INTERVAL
, "30 minutes"),
287 OBSOLETE("TrafficShaping"),
288 V(TransListenAddress
, LINELIST
, NULL
),
289 V(TransPort
, UINT
, "0"),
290 V(TunnelDirConns
, BOOL
, "0"),
291 V(UpdateBridgesFromAuthority
, BOOL
, "0"),
292 V(UseBridges
, BOOL
, "0"),
293 V(UseEntryGuards
, BOOL
, "1"),
294 V(User
, STRING
, NULL
),
295 VAR("V1AuthoritativeDirectory",BOOL
, V1AuthoritativeDir
, "0"),
296 VAR("V2AuthoritativeDirectory",BOOL
, V2AuthoritativeDir
, "0"),
297 VAR("V3AuthoritativeDirectory",BOOL
, V3AuthoritativeDir
, "0"),
298 V(V3AuthVotingInterval
, INTERVAL
, "1 hour"),
299 V(V3AuthVoteDelay
, INTERVAL
, "5 minutes"),
300 V(V3AuthDistDelay
, INTERVAL
, "5 minutes"),
301 V(V3AuthNIntervalsValid
, UINT
, "3"),
302 VAR("VersioningAuthoritativeDirectory",BOOL
,VersioningAuthoritativeDir
, "0"),
303 V(VirtualAddrNetwork
, STRING
, "127.192.0.0/10"),
304 V(WarnPlaintextPorts
, CSV
, "23,109,110,143"),
305 VAR("__AllDirActionsPrivate", BOOL
, AllDirActionsPrivate
, "0"),
306 VAR("__DisablePredictedCircuits",BOOL
,DisablePredictedCircuits
, "0"),
307 VAR("__LeaveStreamsUnattached",BOOL
, LeaveStreamsUnattached
, "0"),
308 V(MinUptimeHidServDirectoryV2
, INTERVAL
, "24 hours"),
309 { NULL
, CONFIG_TYPE_OBSOLETE
, 0, NULL
}
313 #define VAR(name,conftype,member,initvalue) \
314 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_state_t, member), \
316 static config_var_t _state_vars
[] = {
317 V(AccountingBytesReadInInterval
, MEMUNIT
, NULL
),
318 V(AccountingBytesWrittenInInterval
, MEMUNIT
, NULL
),
319 V(AccountingExpectedUsage
, MEMUNIT
, NULL
),
320 V(AccountingIntervalStart
, ISOTIME
, NULL
),
321 V(AccountingSecondsActive
, INTERVAL
, NULL
),
323 VAR("EntryGuard", LINELIST_S
, EntryGuards
, NULL
),
324 VAR("EntryGuardDownSince", LINELIST_S
, EntryGuards
, NULL
),
325 VAR("EntryGuardUnlistedSince", LINELIST_S
, EntryGuards
, NULL
),
326 VAR("EntryGuardAddedBy", LINELIST_S
, EntryGuards
, NULL
),
327 V(EntryGuards
, LINELIST_V
, NULL
),
329 V(BWHistoryReadEnds
, ISOTIME
, NULL
),
330 V(BWHistoryReadInterval
, UINT
, "900"),
331 V(BWHistoryReadValues
, CSV
, ""),
332 V(BWHistoryWriteEnds
, ISOTIME
, NULL
),
333 V(BWHistoryWriteInterval
, UINT
, "900"),
334 V(BWHistoryWriteValues
, CSV
, ""),
336 V(TorVersion
, STRING
, NULL
),
338 V(LastRotatedOnionKey
, ISOTIME
, NULL
),
339 V(LastWritten
, ISOTIME
, NULL
),
341 { NULL
, CONFIG_TYPE_OBSOLETE
, 0, NULL
}
348 /** Represents an English description of a configuration variable; used when
349 * generating configuration file comments. */
350 typedef struct config_var_description_t
{
352 const char *description
;
353 } config_var_description_t
;
355 static config_var_description_t options_description
[] = {
356 /* ==== general options */
357 { "AvoidDiskWrites", "If non-zero, try to write to disk less frequently than"
358 " we would otherwise." },
359 { "BandwidthRate", "A token bucket limits the average incoming bandwidth on "
360 "this node to the specified number of bytes per second." },
361 { "BandwidthBurst", "Limit the maximum token buffer size (also known as "
362 "burst) to the given number of bytes." },
363 { "ConnLimit", "Maximum number of simultaneous sockets allowed." },
364 { "ConstrainedSockets", "Shrink tx and rx buffers for sockets to avoid "
365 "system limits on vservers and related environments. See man page for "
366 "more information regarding this option." },
367 { "ConstrainedSockSize", "Limit socket buffers to this size when "
368 "ConstrainedSockets is enabled." },
369 /* ControlListenAddress */
370 { "ControlPort", "If set, Tor will accept connections from the same machine "
371 "(localhost only) on this port, and allow those connections to control "
372 "the Tor process using the Tor Control Protocol (described in"
373 "control-spec.txt).", },
374 { "CookieAuthentication", "If this option is set to 1, don't allow any "
375 "connections to the control port except when the connecting process "
376 "can read a file that Tor creates in its data directory." },
377 { "DataDirectory", "Store working data, state, keys, and caches here." },
378 { "DirServer", "Tor only trusts directories signed with one of these "
379 "servers' keys. Used to override the standard list of directory "
381 /* { "FastFirstHopPK", "" }, */
382 /* FetchServerDescriptors, FetchHidServDescriptors,
383 * FetchUselessDescriptors */
384 { "Group", "On startup, setgid to this group." },
385 { "HardwareAccel", "If set, Tor tries to use hardware crypto accelerators "
387 /* HashedControlPassword */
388 { "HTTPProxy", "Force Tor to make all HTTP directory requests through this "
389 "host:port (or host:80 if port is not set)." },
390 { "HTTPProxyAuthenticator", "A username:password pair to be used with "
392 { "HTTPSProxy", "Force Tor to make all TLS (SSL) connectinos through this "
393 "host:port (or host:80 if port is not set)." },
394 { "HTTPSProxyAuthenticator", "A username:password pair to be used with "
396 { "KeepalivePeriod", "Send a padding cell every N seconds to keep firewalls "
397 "from closing our connections while Tor is not in use." },
398 { "Log", "Where to send logging messages. Format is "
399 "minSeverity[-maxSeverity] (stderr|stdout|syslog|file FILENAME)." },
400 { "OutboundBindAddress", "Make all outbound connections originate from the "
401 "provided IP address (only useful for multiple network interfaces)." },
402 { "PIDFile", "On startup, write our PID to this file. On clean shutdown, "
403 "remove the file." },
404 { "PreferTunneledDirConns", "If non-zero, avoid directory servers that "
405 "don't support tunneled connections." },
406 /* PreferTunneledDirConns */
407 /* ProtocolWarnings */
408 /* RephistTrackTime */
409 { "RunAsDaemon", "If set, Tor forks and daemonizes to the background when "
410 "started. Unix only." },
411 { "SafeLogging", "If set to 0, Tor logs potentially sensitive strings "
412 "rather than replacing them with the string [scrubbed]." },
413 { "TunnelDirConns", "If non-zero, when a directory server we contact "
414 "supports it, we will build a one-hop circuit and make an encrypted "
415 "connection via its ORPort." },
416 { "User", "On startup, setuid to this user" },
418 /* ==== client options */
419 { "AllowInvalidNodes", "Where on our circuits should Tor allow servers "
420 "that the directory authorities haven't called \"valid\"?" },
421 { "AllowNonRFC953Hostnames", "If set to 1, we don't automatically reject "
422 "hostnames for having invalid characters." },
423 /* CircuitBuildTimeout, CircuitIdleTimeout */
424 { "ClientOnly", "If set to 1, Tor will under no circumstances run as a "
425 "server, even if ORPort is enabled." },
426 { "EntryNodes", "A list of preferred entry nodes to use for the first hop "
427 "in circuits, when possible." },
428 /* { "EnforceDistinctSubnets" , "" }, */
429 { "ExitNodes", "A list of preferred nodes to use for the last hop in "
430 "circuits, when possible." },
431 { "ExcludeNodes", "A list of nodes never to use when building a circuit." },
432 { "FascistFirewall", "If set, Tor will only create outgoing connections to "
433 "servers running on the ports listed in FirewallPorts." },
434 { "FirewallPorts", "A list of ports that we can connect to. Only used "
435 "when FascistFirewall is set." },
436 { "LongLivedPorts", "A list of ports for services that tend to require "
437 "high-uptime connections." },
438 { "MapAddress", "Force Tor to treat all requests for one address as if "
439 "they were for another." },
440 { "NewCircuitPeriod", "Force Tor to consider whether to build a new circuit "
441 "every NUM seconds." },
442 { "MaxCircuitDirtiness", "Do not attach new streams to a circuit that has "
443 "been used more than this many seconds ago." },
444 /* NatdPort, NatdListenAddress */
445 { "NodeFamily", "A list of servers that constitute a 'family' and should "
446 "never be used in the same circuit." },
447 { "NumEntryGuards", "How many entry guards should we keep at a time?" },
448 /* PathlenCoinWeight */
449 { "ReachableAddresses", "Addresses we can connect to, as IP/bits:port-port. "
450 "By default, we assume all addresses are reachable." },
451 /* reachablediraddresses, reachableoraddresses. */
452 { "RendNodes", "A list of preferred nodes to use for a rendezvous point, "
454 { "RendExcludenodes", "A list of nodes never to use as rendezvous points." },
456 { "SOCKSPort", "The port where we listen for SOCKS connections from "
458 { "SOCKSListenAddress", "Bind to this address to listen to connections from "
459 "SOCKS-speaking applications." },
460 { "SOCKSPolicy", "Set an entry policy to limit which addresses can connect "
461 "to the SOCKSPort." },
463 { "StrictExitNodes", "If set, Tor will fail to operate when none of the "
464 "configured ExitNodes can be used." },
465 { "StrictEntryNodes", "If set, Tor will fail to operate when none of the "
466 "configured EntryNodes can be used." },
468 { "TrackHostsExit", "Hosts and domains which should, if possible, be "
469 "accessed from the same exit node each time we connect to them." },
470 { "TrackHostsExitExpire", "Time after which we forget which exit we were "
471 "using to connect to hosts in TrackHostsExit." },
472 /* "TransPort", "TransListenAddress */
473 { "UseEntryGuards", "Set to 0 if we want to pick from the whole set of "
474 "servers for the first position in each circuit, rather than picking a "
475 "set of 'Guards' to prevent profiling attacks." },
477 /* === server options */
478 { "Address", "The advertised (external) address we should use." },
479 /* Accounting* options. */
480 /* AssumeReachable */
481 { "ContactInfo", "Administrative contact information to advertise for this "
483 { "ExitPolicy", "Address/port ranges for which to accept or reject outgoing "
484 "connections on behalf of Tor users." },
485 /* { "ExitPolicyRejectPrivate, "" }, */
486 { "MaxAdvertisedBandwidth", "If set, we will not advertise more than this "
487 "amount of bandwidth for our bandwidth rate, regardless of how much "
488 "bandwidth we actually detect." },
489 { "MaxOnionsPending", "Reject new attempts to extend circuits when we "
490 "already have this many pending." },
491 { "MyFamily", "Declare a list of other servers as belonging to the same "
492 "family as this one, so that clients will not use two from the same "
493 "family in the same circuit." },
494 { "Nickname", "Set the server nickname." },
495 { "NoPublish", "{DEPRECATED}" },
496 { "NumCPUs", "How many processes to use at once for public-key crypto." },
497 { "ORPort", "Advertise this port to listen for connections from Tor clients "
499 { "ORListenAddress", "Bind to this address to listen for connections from "
500 "clients and servers, instead of the default 0.0.0.0:ORPort." },
501 { "PublishServerDescriptor", "Set to 0 to keep the server from "
502 "uploading info to the directory authorities." },
503 /*{ "RedirectExit", "When an outgoing connection tries to connect to a "
504 *"given address, redirect it to another address instead." },
506 /* ServerDNS: DetectHijacking, ResolvConfFile, SearchDomains */
507 { "ShutdownWaitLength", "Wait this long for clients to finish when "
508 "shutting down because of a SIGINT." },
511 /* === directory cache options */
512 { "DirPort", "Serve directory information from this port, and act as a "
513 "directory cache." },
514 { "DirListenAddress", "Bind to this address to listen for connections from "
515 "clients and servers, instead of the default 0.0.0.0:DirPort." },
516 { "DirPolicy", "Set a policy to limit who can connect to the directory "
519 /* Authority options: AuthDirBadExit, AuthDirInvalid, AuthDirReject,
520 * AuthDirRejectUnlisted, AuthDirListBadExits, AuthoritativeDirectory,
521 * DirAllowPrivateAddresses, HSAuthoritativeDir,
522 * NamingAuthoritativeDirectory, RecommendedVersions,
523 * RecommendedClientVersions, RecommendedServerVersions, RendPostPeriod,
524 * RunTesting, V1AuthoritativeDirectory, VersioningAuthoritativeDirectory, */
526 /* Hidden service options: HiddenService: dir,excludenodes, nodes,
527 * options, port. PublishHidServDescriptor */
529 /* Nonpersistent options: __LeaveStreamsUnattached, __AllDirActionsPrivate */
533 static config_var_description_t state_description
[] = {
534 { "AccountingBytesReadInInterval",
535 "How many bytes have we read in this accounting period?" },
536 { "AccountingBytesWrittenInInterval",
537 "How many bytes have we written in this accounting period?" },
538 { "AccountingExpectedUsage",
539 "How many bytes did we expect to use per minute? (0 for no estimate.)" },
540 { "AccountingIntervalStart", "When did this accounting period begin?" },
541 { "AccountingSecondsActive", "How long have we been awake in this period?" },
543 { "BWHistoryReadEnds", "When does the last-recorded read-interval end?" },
544 { "BWHistoryReadInterval", "How long is each read-interval (in seconds)?" },
545 { "BWHistoryReadValues", "Number of bytes read in each interval." },
546 { "BWHistoryWriteEnds", "When does the last-recorded write-interval end?" },
547 { "BWHistoryWriteInterval", "How long is each write-interval (in seconds)?"},
548 { "BWHistoryWriteValues", "Number of bytes written in each interval." },
550 { "EntryGuard", "One of the nodes we have chosen as a fixed entry" },
551 { "EntryGuardDownSince",
552 "The last entry guard has been unreachable since this time." },
553 { "EntryGuardUnlistedSince",
554 "The last entry guard has been unusable since this time." },
556 { "LastRotatedOnionKey",
557 "The last time at which we changed the medium-term private key used for "
558 "building circuits." },
559 { "LastWritten", "When was this state file last regenerated?" },
561 { "TorVersion", "Which version of Tor generated this state file?" },
565 /** Type of a callback to validate whether a given configuration is
566 * well-formed and consistent. See options_trial_assign() for documentation
568 typedef int (*validate_fn_t
)(void*,void*,int,char**);
570 /** Information on the keys, value types, key-to-struct-member mappings,
571 * variable descriptions, validation functions, and abbreviations for a
572 * configuration or storage format. */
574 size_t size
; /**< Size of the struct that everything gets parsed into. */
575 uint32_t magic
; /**< Required 'magic value' to make sure we have a struct
576 * of the right type. */
577 off_t magic_offset
; /**< Offset of the magic value within the struct. */
578 config_abbrev_t
*abbrevs
; /**< List of abbreviations that we expand when
579 * parsing this format. */
580 config_var_t
*vars
; /**< List of variables we recognize, their default
581 * values, and where we stick them in the structure. */
582 validate_fn_t validate_fn
; /**< Function to validate config. */
583 /** Documentation for configuration variables. */
584 config_var_description_t
*descriptions
;
585 /** If present, extra is a LINELIST variable for unrecognized
586 * lines. Otherwise, unrecognized lines are an error. */
590 /** Macro: assert that <b>cfg</b> has the right magic field for format
592 #define CHECK(fmt, cfg) STMT_BEGIN \
593 tor_assert(fmt && cfg); \
594 tor_assert((fmt)->magic == \
595 *(uint32_t*)STRUCT_VAR_P(cfg,fmt->magic_offset)); \
598 static void config_line_append(config_line_t
**lst
,
599 const char *key
, const char *val
);
600 static void option_clear(config_format_t
*fmt
, or_options_t
*options
,
602 static void option_reset(config_format_t
*fmt
, or_options_t
*options
,
603 config_var_t
*var
, int use_defaults
);
604 static void config_free(config_format_t
*fmt
, void *options
);
605 static int config_lines_eq(config_line_t
*a
, config_line_t
*b
);
606 static int option_is_same(config_format_t
*fmt
,
607 or_options_t
*o1
, or_options_t
*o2
,
609 static or_options_t
*options_dup(config_format_t
*fmt
, or_options_t
*old
);
610 static int options_validate(or_options_t
*old_options
, or_options_t
*options
,
611 int from_setconf
, char **msg
);
612 static int options_act_reversible(or_options_t
*old_options
, char **msg
);
613 static int options_act(or_options_t
*old_options
);
614 static int options_transition_allowed(or_options_t
*old
, or_options_t
*new,
616 static int options_transition_affects_workers(or_options_t
*old_options
,
617 or_options_t
*new_options
);
618 static int options_transition_affects_descriptor(or_options_t
*old_options
,
619 or_options_t
*new_options
);
620 static int check_nickname_list(const char *lst
, const char *name
, char **msg
);
621 static void config_register_addressmaps(or_options_t
*options
);
623 static int parse_bridge_line(const char *line
, int validate_only
);
624 static int parse_dir_server_line(const char *line
,
625 authority_type_t required_type
,
627 static int parse_redirect_line(smartlist_t
*result
,
628 config_line_t
*line
, char **msg
);
629 static int parse_log_severity_range(const char *range
, int *min_out
,
631 static int validate_data_directory(or_options_t
*options
);
632 static int write_configuration_file(const char *fname
, or_options_t
*options
);
633 static config_line_t
*get_assigned_option(config_format_t
*fmt
,
634 or_options_t
*options
, const char *key
,
636 static void config_init(config_format_t
*fmt
, void *options
);
637 static int or_state_validate(or_state_t
*old_options
, or_state_t
*options
,
638 int from_setconf
, char **msg
);
639 static int or_state_load(void);
640 static int options_init_logs(or_options_t
*options
, int validate_only
);
642 static uint64_t config_parse_memunit(const char *s
, int *ok
);
643 static int config_parse_interval(const char *s
, int *ok
);
644 static void print_svn_version(void);
645 static void init_libevent(void);
646 static int opt_streq(const char *s1
, const char *s2
);
647 /** Versions of libevent. */
649 /* Note: we compare these, so it's important that "old" precede everything,
650 * and that "other" come last. */
651 LE_OLD
=0, LE_10C
, LE_10D
, LE_10E
, LE_11
, LE_11A
, LE_11B
, LE_12
, LE_12A
,
652 LE_13
, LE_13A
, LE_13B
, LE_13C
, LE_13D
,
655 static le_version_t
decode_libevent_version(void);
656 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
657 static void check_libevent_version(const char *m
, int server
);
660 /** Magic value for or_options_t. */
661 #define OR_OPTIONS_MAGIC 9090909
663 /** Configuration format for or_options_t. */
664 static config_format_t options_format
= {
665 sizeof(or_options_t
),
667 STRUCT_OFFSET(or_options_t
, _magic
),
670 (validate_fn_t
)options_validate
,
675 /** Magic value for or_state_t. */
676 #define OR_STATE_MAGIC 0x57A73f57
678 /** "Extra" variable in the state that receives lines we can't parse. This
679 * lets us preserve options from versions of Tor newer than us. */
680 static config_var_t state_extra_var
= {
681 "__extra", CONFIG_TYPE_LINELIST
, STRUCT_OFFSET(or_state_t
, ExtraLines
), NULL
684 /** Configuration format for or_state_t. */
685 static config_format_t state_format
= {
688 STRUCT_OFFSET(or_state_t
, _magic
),
691 (validate_fn_t
)or_state_validate
,
697 * Functions to read and write the global options pointer.
700 /** Command-line and config-file options. */
701 static or_options_t
*global_options
= NULL
;
702 /** Name of most recently read torrc file. */
703 static char *torrc_fname
= NULL
;
704 /** Persistent serialized state. */
705 static or_state_t
*global_state
= NULL
;
707 /** Allocate an empty configuration object of a given format type. */
709 config_alloc(config_format_t
*fmt
)
711 void *opts
= tor_malloc_zero(fmt
->size
);
712 *(uint32_t*)STRUCT_VAR_P(opts
, fmt
->magic_offset
) = fmt
->magic
;
717 /** Return the currently configured options. */
721 tor_assert(global_options
);
722 return global_options
;
725 /** Change the current global options to contain <b>new_val</b> instead of
726 * their current value; take action based on the new value; free the old value
730 set_options(or_options_t
*new_val
, char **msg
)
732 or_options_t
*old_options
= global_options
;
733 global_options
= new_val
;
734 /* Note that we pass the *old* options below, for comparison. It
735 * pulls the new options directly out of global_options. */
736 if (options_act_reversible(old_options
, msg
)<0) {
738 global_options
= old_options
;
741 if (options_act(old_options
) < 0) { /* acting on the options failed. die. */
743 "Acting on config options left us in a broken state. Dying.");
747 config_free(&options_format
, old_options
);
752 extern const char tor_svn_revision
[]; /* from tor_main.c */
754 static char *_version
= NULL
;
756 /** Return the current Tor version, possibly */
760 if (_version
== NULL
) {
761 if (strlen(tor_svn_revision
)) {
762 size_t len
= strlen(VERSION
)+strlen(tor_svn_revision
)+8;
763 _version
= tor_malloc(len
);
764 tor_snprintf(_version
, len
, "%s (r%s)", VERSION
, tor_svn_revision
);
766 _version
= tor_strdup(VERSION
);
772 /** Release all memory and resources held by global configuration structures.
775 config_free_all(void)
777 if (global_options
) {
778 config_free(&options_format
, global_options
);
779 global_options
= NULL
;
782 config_free(&state_format
, global_state
);
785 tor_free(torrc_fname
);
789 /** If options->SafeLogging is on, return a not very useful string,
790 * else return address.
793 safe_str(const char *address
)
796 if (get_options()->SafeLogging
)
802 /** Equivalent to escaped(safe_str(address)). See reentrancy note on
803 * escaped(): don't use this outside the main thread, or twice in the same
806 escaped_safe_str(const char *address
)
808 if (get_options()->SafeLogging
)
811 return escaped(address
);
814 /** Add the default directory authorities directly into the trusted dir list,
815 * but only add them insofar as they share bits with <b>type</b>. */
817 add_default_trusted_dir_authorities(authority_type_t type
)
820 const char *dirservers
[] = {
821 "moria1 v1 orport=9001 v3ident=5420FD8EA46BD4290F1D07A1883C9D85ECC486C4 "
822 "128.31.0.34:9031 FFCB 46DB 1339 DA84 674C 70D7 CB58 6434 C437 0441",
823 "moria2 v1 orport=9002 128.31.0.34:9032 "
824 "719B E45D E224 B607 C537 07D0 E214 3E2D 423E 74CF",
825 "tor26 v1 orport=443 v3ident=A9AC67E64B200BBF2FA26DF194AC0469E2A948C6 "
826 "86.59.21.38:80 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D",
827 "lefkada orport=443 v3ident=0D95B91896E6089AB9A3C6CB56E724CAF898C43F "
828 "140.247.60.64:80 38D4 F5FC F7B1 0232 28B8 95EA 56ED E7D5 CCDC AF32",
829 "dizum 194.109.206.212:80 "
830 "7EA6 EAD6 FD83 083C 538F 4403 8BBF A077 587D D755",
831 "Tonga orport=443 bridge no-v2 82.94.251.206:80 "
832 "4A0C CD2D DC79 9508 3D73 F5D6 6710 0C8A 5831 F16D",
833 "ides orport=9090 no-v2 v3ident=27B6B5996C426270A5C95488AA5BCEB6BCC86956 "
834 "216.224.124.114:9030 F397 038A DC51 3361 35E7 B80B D99C A384 4360 292B",
835 "gabelmoo orport=443 no-v2 "
836 "v3ident=EAA879B5C75032E462CB018630D2D0DF46EBA606 "
837 "88.198.7.215:80 6833 3D07 61BC F397 A587 A0C0 B963 E4A9 E99E C4D3",
838 "dannenberg orport=443 no-v2 "
839 "v3ident=585769C78764D58426B8B52B6651A5A71137189A "
840 "213.73.91.31:80 7BE6 83E6 5D48 1413 21C5 ED92 F075 C553 64AC 7123",
843 for (i
=0; dirservers
[i
]; i
++) {
844 if (parse_dir_server_line(dirservers
[i
], type
, 0)<0) {
845 log_err(LD_BUG
, "Couldn't parse internal dirserver line %s",
851 /** Look at all the config options for using alternate directory
852 * authorities, and make sure none of them are broken. Also, warn the
853 * user if we changed any dangerous ones.
856 validate_dir_authorities(or_options_t
*options
, or_options_t
*old_options
)
860 if (options
->DirServers
&&
861 (options
->AlternateDirAuthority
|| options
->AlternateBridgeAuthority
||
862 options
->AlternateHSAuthority
)) {
864 "You cannot set both DirServers and Alternate*Authority.");
868 /* do we want to complain to the user about being partitionable? */
869 if ((options
->DirServers
&&
871 !config_lines_eq(options
->DirServers
, old_options
->DirServers
))) ||
872 (options
->AlternateDirAuthority
&&
874 !config_lines_eq(options
->AlternateDirAuthority
,
875 old_options
->AlternateDirAuthority
)))) {
877 "You have used DirServer or AlternateDirAuthority to "
878 "specify alternate directory authorities in "
879 "your configuration. This is potentially dangerous: it can "
880 "make you look different from all other Tor users, and hurt "
881 "your anonymity. Even if you've specified the same "
882 "authorities as Tor uses by default, the defaults could "
883 "change in the future. Be sure you know what you're doing.");
886 /* Now go through the four ways you can configure an alternate
887 * set of directory authorities, and make sure none are broken. */
888 for (cl
= options
->DirServers
; cl
; cl
= cl
->next
)
889 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 1)<0)
891 for (cl
= options
->AlternateBridgeAuthority
; cl
; cl
= cl
->next
)
892 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 1)<0)
894 for (cl
= options
->AlternateDirAuthority
; cl
; cl
= cl
->next
)
895 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 1)<0)
897 for (cl
= options
->AlternateHSAuthority
; cl
; cl
= cl
->next
)
898 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 1)<0)
903 /** Look at all the config options and assign new dir authorities
907 consider_adding_dir_authorities(or_options_t
*options
,
908 or_options_t
*old_options
)
912 !smartlist_len(router_get_trusted_dir_servers()) || !old_options
||
913 !config_lines_eq(options
->DirServers
, old_options
->DirServers
) ||
914 !config_lines_eq(options
->AlternateBridgeAuthority
,
915 old_options
->AlternateBridgeAuthority
) ||
916 !config_lines_eq(options
->AlternateDirAuthority
,
917 old_options
->AlternateDirAuthority
) ||
918 !config_lines_eq(options
->AlternateHSAuthority
,
919 old_options
->AlternateHSAuthority
);
922 return 0; /* all done */
924 /* Start from a clean slate. */
925 clear_trusted_dir_servers();
927 if (!options
->DirServers
) {
928 /* then we may want some of the defaults */
929 authority_type_t type
= NO_AUTHORITY
;
930 if (!options
->AlternateBridgeAuthority
)
931 type
|= BRIDGE_AUTHORITY
;
932 if (!options
->AlternateDirAuthority
)
933 type
|= V1_AUTHORITY
| V2_AUTHORITY
| V3_AUTHORITY
;
934 if (!options
->AlternateHSAuthority
)
935 type
|= HIDSERV_AUTHORITY
;
936 add_default_trusted_dir_authorities(type
);
939 for (cl
= options
->DirServers
; cl
; cl
= cl
->next
)
940 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 0)<0)
942 for (cl
= options
->AlternateBridgeAuthority
; cl
; cl
= cl
->next
)
943 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 0)<0)
945 for (cl
= options
->AlternateDirAuthority
; cl
; cl
= cl
->next
)
946 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 0)<0)
948 for (cl
= options
->AlternateHSAuthority
; cl
; cl
= cl
->next
)
949 if (parse_dir_server_line(cl
->value
, NO_AUTHORITY
, 0)<0)
954 /** Fetch the active option list, and take actions based on it. All of the
955 * things we do should survive being done repeatedly. If present,
956 * <b>old_options</b> contains the previous value of the options.
958 * Return 0 if all goes well, return -1 if things went badly.
961 options_act_reversible(or_options_t
*old_options
, char **msg
)
963 smartlist_t
*new_listeners
= smartlist_create();
964 smartlist_t
*replaced_listeners
= smartlist_create();
965 static int libevent_initialized
= 0;
966 or_options_t
*options
= get_options();
967 int running_tor
= options
->command
== CMD_RUN_TOR
;
968 int set_conn_limit
= 0;
972 /* Daemonize _first_, since we only want to open most of this stuff in
973 * the subprocess. Libevent bases can't be reliably inherited across
975 if (running_tor
&& options
->RunAsDaemon
) {
976 /* No need to roll back, since you can't change the value. */
980 #ifndef HAVE_SYS_UN_H
981 if (options
->ControlSocket
) {
982 *msg
= tor_strdup("Unix domain sockets (ControlSocket) not supported"
983 " on this OS/with this build.");
989 /* We need to set the connection limit before we can open the listeners. */
990 options
->_ConnLimit
=
991 set_max_file_descriptors((unsigned)options
->ConnLimit
, MAXCONNECTIONS
);
992 if (options
->_ConnLimit
< 0) {
993 *msg
= tor_strdup("Problem with ConnLimit value. See logs for details.");
998 /* Set up libevent. (We need to do this before we can register the
999 * listeners as listeners.) */
1000 if (running_tor
&& !libevent_initialized
) {
1002 libevent_initialized
= 1;
1005 /* Launch the listeners. (We do this before we setuid, so we can bind to
1006 * ports under 1024.) */
1007 if (retry_all_listeners(replaced_listeners
, new_listeners
) < 0) {
1008 *msg
= tor_strdup("Failed to bind one of the listener ports.");
1013 /* Setuid/setgid as appropriate */
1014 if (options
->User
|| options
->Group
) {
1015 if (switch_id(options
->User
, options
->Group
) != 0) {
1016 /* No need to roll back, since you can't change the value. */
1017 *msg
= tor_strdup("Problem with User or Group value. "
1018 "See logs for details.");
1023 /* Ensure data directory is private; create if possible. */
1024 if (check_private_dir(options
->DataDirectory
,
1025 running_tor
? CPD_CREATE
: CPD_CHECK
)<0) {
1027 int tmp
= tor_snprintf(buf
, sizeof(buf
),
1028 "Couldn't access/create private data directory \"%s\"",
1029 options
->DataDirectory
);
1030 *msg
= tor_strdup(tmp
>= 0 ? buf
: "internal error");
1032 /* No need to roll back, since you can't change the value. */
1035 /* Bail out at this point if we're not going to be a client or server:
1036 * we don't run Tor itself. */
1040 mark_logs_temp(); /* Close current logs once new logs are open. */
1042 if (options_init_logs(options
, 0)<0) { /* Configure the log(s) */
1043 *msg
= tor_strdup("Failed to init Log options. See logs for details.");
1051 add_callback_log(LOG_ERR
, LOG_ERR
, control_event_logmsg
);
1052 control_adjust_event_log_severity();
1054 SMARTLIST_FOREACH(replaced_listeners
, connection_t
*, conn
,
1056 log_notice(LD_NET
, "Closing old %s on %s:%d",
1057 conn_type_to_string(conn
->type
), conn
->address
, conn
->port
);
1058 connection_close_immediate(conn
);
1059 connection_mark_for_close(conn
);
1068 rollback_log_changes();
1069 control_adjust_event_log_severity();
1072 if (set_conn_limit
&& old_options
)
1073 set_max_file_descriptors((unsigned)old_options
->ConnLimit
,MAXCONNECTIONS
);
1075 SMARTLIST_FOREACH(new_listeners
, connection_t
*, conn
,
1077 log_notice(LD_NET
, "Closing partially-constructed listener %s on %s:%d",
1078 conn_type_to_string(conn
->type
), conn
->address
, conn
->port
);
1079 connection_close_immediate(conn
);
1080 connection_mark_for_close(conn
);
1084 smartlist_free(new_listeners
);
1085 smartlist_free(replaced_listeners
);
1089 /** Fetch the active option list, and take actions based on it. All of the
1090 * things we do should survive being done repeatedly. If present,
1091 * <b>old_options</b> contains the previous value of the options.
1093 * Return 0 if all goes well, return -1 if it's time to die.
1095 * Note: We haven't moved all the "act on new configuration" logic
1096 * here yet. Some is still in do_hup() and other places.
1099 options_act(or_options_t
*old_options
)
1104 or_options_t
*options
= get_options();
1105 int running_tor
= options
->command
== CMD_RUN_TOR
;
1108 if (consider_adding_dir_authorities(options
, old_options
) < 0)
1111 if (options
->Bridges
) {
1112 clear_bridge_list();
1113 for (cl
= options
->Bridges
; cl
; cl
= cl
->next
) {
1114 if (parse_bridge_line(cl
->value
, 0)<0) {
1116 "Previously validated Bridge line could not be added!");
1122 if (running_tor
&& rend_config_services(options
, 0)<0) {
1124 "Previously validated hidden services line could not be added!");
1128 if (running_tor
&& directory_caches_v2_dir_info(options
)) {
1129 len
= strlen(options
->DataDirectory
)+32;
1130 fn
= tor_malloc(len
);
1131 tor_snprintf(fn
, len
, "%s"PATH_SEPARATOR
"cached-status",
1132 options
->DataDirectory
);
1133 if (check_private_dir(fn
, CPD_CREATE
) != 0) {
1135 "Couldn't access/create private data directory \"%s\"", fn
);
1143 if (! global_state
&& options
->command
== CMD_RUN_TOR
) {
1144 if (or_state_load())
1146 rep_hist_load_mtbf_data(time(NULL
));
1149 /* Bail out at this point if we're not going to be a client or server:
1150 * we want to not fork, and to log stuff to stderr. */
1155 smartlist_t
*sl
= smartlist_create();
1156 char *errmsg
= NULL
;
1157 for (cl
= options
->RedirectExit
; cl
; cl
= cl
->next
) {
1158 if (parse_redirect_line(sl
, cl
, &errmsg
)<0) {
1159 log_warn(LD_CONFIG
, "%s", errmsg
);
1161 SMARTLIST_FOREACH(sl
, exit_redirect_t
*, er
, tor_free(er
));
1166 set_exit_redirects(sl
);
1169 /* Finish backgrounding the process */
1170 if (running_tor
&& options
->RunAsDaemon
) {
1171 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
1172 finish_daemon(options
->DataDirectory
);
1175 /* Write our pid to the pid file. If we do not have write permissions we
1176 * will log a warning */
1177 if (running_tor
&& options
->PidFile
)
1178 write_pidfile(options
->PidFile
);
1180 /* Register addressmap directives */
1181 config_register_addressmaps(options
);
1182 parse_virtual_addr_network(options
->VirtualAddrNetwork
, 0, &msg
);
1184 /* Update address policies. */
1185 policies_parse_from_options(options
);
1187 if (init_cookie_authentication(options
->CookieAuthentication
) < 0) {
1188 log_warn(LD_CONFIG
,"Error creating cookie authentication file.");
1192 /* reload keys as needed for rendezvous services. */
1193 if (rend_service_load_keys()<0) {
1194 log_warn(LD_GENERAL
,"Error loading rendezvous service keys");
1198 /* Set up accounting */
1199 if (accounting_parse_options(options
, 0)<0) {
1200 log_warn(LD_CONFIG
,"Error in accounting options");
1203 if (accounting_is_enabled(options
))
1204 configure_accounting(time(NULL
));
1206 /* Check for transitions that need action. */
1208 if (options
->UseEntryGuards
&& !old_options
->UseEntryGuards
) {
1210 "Switching to entry guards; abandoning previous circuits");
1211 circuit_mark_all_unused_circs();
1212 circuit_expire_all_dirty_circs();
1215 if (options_transition_affects_workers(old_options
, options
)) {
1216 log_info(LD_GENERAL
,
1217 "Worker-related options changed. Rotating workers.");
1218 if (server_mode(options
) && !server_mode(old_options
)) {
1219 if (init_keys() < 0) {
1220 log_warn(LD_BUG
,"Error initializing keys; exiting");
1223 ip_address_changed(0);
1224 if (has_completed_circuit
|| !any_predicted_circuits(time(NULL
)))
1225 inform_testing_reachability();
1227 cpuworkers_rotate();
1235 if (options
->V3AuthoritativeDir
&& !old_options
->V3AuthoritativeDir
)
1239 /* Maybe load geoip file */
1240 if (options
->GeoIPFile
&&
1241 ((!old_options
|| !opt_streq(old_options
->GeoIPFile
, options
->GeoIPFile
))
1242 || !geoip_is_loaded())) {
1243 geoip_load_file(options
->GeoIPFile
);
1245 /* Check if we need to parse and add the EntryNodes config option. */
1246 if (options
->EntryNodes
&&
1248 !opt_streq(old_options
->EntryNodes
, options
->EntryNodes
)))
1249 entry_nodes_should_be_added();
1251 /* Since our options changed, we might need to regenerate and upload our
1252 * server descriptor.
1255 options_transition_affects_descriptor(old_options
, options
))
1256 mark_my_descriptor_dirty();
1258 /* We may need to reschedule some directory stuff if our status changed. */
1260 if (authdir_mode_v3(options
) && !authdir_mode_v3(old_options
))
1261 dirvote_recalculate_timing(options
, time(NULL
));
1262 if (!bool_eq(directory_fetches_dir_info_early(options
),
1263 directory_fetches_dir_info_early(old_options
)) ||
1264 !bool_eq(directory_fetches_dir_info_later(options
),
1265 directory_fetches_dir_info_later(old_options
))) {
1266 /* Make sure update_router_have_min_dir_info gets called. */
1267 router_dir_info_changed();
1268 /* We might need to download a new consensus status later or sooner than
1269 * we had expected. */
1270 update_consensus_networkstatus_fetch_time(time(NULL
));
1278 * Functions to parse config options
1281 /** If <b>option</b> is an official abbreviation for a longer option,
1282 * return the longer option. Otherwise return <b>option</b>.
1283 * If <b>command_line</b> is set, apply all abbreviations. Otherwise, only
1284 * apply abbreviations that work for the config file and the command line.
1285 * If <b>warn_obsolete</b> is set, warn about deprecated names. */
1287 expand_abbrev(config_format_t
*fmt
, const char *option
, int command_line
,
1293 for (i
=0; fmt
->abbrevs
[i
].abbreviated
; ++i
) {
1294 /* Abbreviations are casei. */
1295 if (!strcasecmp(option
,fmt
->abbrevs
[i
].abbreviated
) &&
1296 (command_line
|| !fmt
->abbrevs
[i
].commandline_only
)) {
1297 if (warn_obsolete
&& fmt
->abbrevs
[i
].warn
) {
1299 "The configuration option '%s' is deprecated; "
1300 "use '%s' instead.",
1301 fmt
->abbrevs
[i
].abbreviated
,
1302 fmt
->abbrevs
[i
].full
);
1304 return fmt
->abbrevs
[i
].full
;
1310 /** Helper: Read a list of configuration options from the command line.
1311 * If successful, put them in *<b>result</b> and return 0, and return
1312 * -1 and leave *<b>result</b> alone. */
1314 config_get_commandlines(int argc
, char **argv
, config_line_t
**result
)
1316 config_line_t
*front
= NULL
;
1317 config_line_t
**new = &front
;
1322 if (!strcmp(argv
[i
],"-f") ||
1323 !strcmp(argv
[i
],"--hash-password")) {
1324 i
+= 2; /* command-line option with argument. ignore them. */
1326 } else if (!strcmp(argv
[i
],"--list-fingerprint") ||
1327 !strcmp(argv
[i
],"--verify-config") ||
1328 !strcmp(argv
[i
],"--ignore-missing-torrc") ||
1329 !strcmp(argv
[i
],"--quiet")) {
1330 i
+= 1; /* command-line option. ignore it. */
1332 } else if (!strcmp(argv
[i
],"--nt-service") ||
1333 !strcmp(argv
[i
],"-nt-service")) {
1339 log_warn(LD_CONFIG
,"Command-line option '%s' with no value. Failing.",
1341 config_free_lines(front
);
1345 *new = tor_malloc_zero(sizeof(config_line_t
));
1351 (*new)->key
= tor_strdup(expand_abbrev(&options_format
, s
, 1, 1));
1352 (*new)->value
= tor_strdup(argv
[i
+1]);
1353 (*new)->next
= NULL
;
1354 log(LOG_DEBUG
, LD_CONFIG
, "Commandline: parsed keyword '%s', value '%s'",
1355 (*new)->key
, (*new)->value
);
1357 new = &((*new)->next
);
1364 /** Helper: allocate a new configuration option mapping 'key' to 'val',
1365 * append it to *<b>lst</b>. */
1367 config_line_append(config_line_t
**lst
,
1371 config_line_t
*newline
;
1373 newline
= tor_malloc(sizeof(config_line_t
));
1374 newline
->key
= tor_strdup(key
);
1375 newline
->value
= tor_strdup(val
);
1376 newline
->next
= NULL
;
1378 lst
= &((*lst
)->next
);
1383 /** Helper: parse the config string and strdup into key/value
1384 * strings. Set *result to the list, or NULL if parsing the string
1385 * failed. Return 0 on success, -1 on failure. Warn and ignore any
1386 * misformatted lines. */
1388 config_get_lines(const char *string
, config_line_t
**result
)
1390 config_line_t
*list
= NULL
, **next
;
1395 string
= parse_config_line_from_str(string
, &k
, &v
);
1397 config_free_lines(list
);
1401 /* This list can get long, so we keep a pointer to the end of it
1402 * rather than using config_line_append over and over and getting
1403 * n^2 performance. */
1404 *next
= tor_malloc(sizeof(config_line_t
));
1407 (*next
)->next
= NULL
;
1408 next
= &((*next
)->next
);
1420 * Free all the configuration lines on the linked list <b>front</b>.
1423 config_free_lines(config_line_t
*front
)
1432 tor_free(tmp
->value
);
1437 /** Return the description for a given configuration variable, or NULL if no
1438 * description exists. */
1440 config_find_description(config_format_t
*fmt
, const char *name
)
1443 for (i
=0; fmt
->descriptions
[i
].name
; ++i
) {
1444 if (!strcasecmp(name
, fmt
->descriptions
[i
].name
))
1445 return fmt
->descriptions
[i
].description
;
1450 /** If <b>key</b> is a configuration option, return the corresponding
1451 * config_var_t. Otherwise, if <b>key</b> is a non-standard abbreviation,
1452 * warn, and return the corresponding config_var_t. Otherwise return NULL.
1454 static config_var_t
*
1455 config_find_option(config_format_t
*fmt
, const char *key
)
1458 size_t keylen
= strlen(key
);
1460 return NULL
; /* if they say "--" on the commandline, it's not an option */
1461 /* First, check for an exact (case-insensitive) match */
1462 for (i
=0; fmt
->vars
[i
].name
; ++i
) {
1463 if (!strcasecmp(key
, fmt
->vars
[i
].name
)) {
1464 return &fmt
->vars
[i
];
1467 /* If none, check for an abbreviated match */
1468 for (i
=0; fmt
->vars
[i
].name
; ++i
) {
1469 if (!strncasecmp(key
, fmt
->vars
[i
].name
, keylen
)) {
1470 log_warn(LD_CONFIG
, "The abbreviation '%s' is deprecated. "
1471 "Please use '%s' instead",
1472 key
, fmt
->vars
[i
].name
);
1473 return &fmt
->vars
[i
];
1476 /* Okay, unrecognized option */
1481 * Functions to assign config options.
1484 /** <b>c</b>-\>key is known to be a real key. Update <b>options</b>
1485 * with <b>c</b>-\>value and return 0, or return -1 if bad value.
1487 * Called from config_assign_line() and option_reset().
1490 config_assign_value(config_format_t
*fmt
, or_options_t
*options
,
1491 config_line_t
*c
, char **msg
)
1498 CHECK(fmt
, options
);
1500 var
= config_find_option(fmt
, c
->key
);
1503 lvalue
= STRUCT_VAR_P(options
, var
->var_offset
);
1505 switch (var
->type
) {
1507 case CONFIG_TYPE_UINT
:
1508 i
= tor_parse_long(c
->value
, 10, 0, INT_MAX
, &ok
, NULL
);
1510 r
= tor_snprintf(buf
, sizeof(buf
),
1511 "Int keyword '%s %s' is malformed or out of bounds.",
1513 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
1519 case CONFIG_TYPE_INTERVAL
: {
1520 i
= config_parse_interval(c
->value
, &ok
);
1522 r
= tor_snprintf(buf
, sizeof(buf
),
1523 "Interval '%s %s' is malformed or out of bounds.",
1525 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
1532 case CONFIG_TYPE_MEMUNIT
: {
1533 uint64_t u64
= config_parse_memunit(c
->value
, &ok
);
1535 r
= tor_snprintf(buf
, sizeof(buf
),
1536 "Value '%s %s' is malformed or out of bounds.",
1538 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
1541 *(uint64_t *)lvalue
= u64
;
1545 case CONFIG_TYPE_BOOL
:
1546 i
= tor_parse_long(c
->value
, 10, 0, 1, &ok
, NULL
);
1548 r
= tor_snprintf(buf
, sizeof(buf
),
1549 "Boolean '%s %s' expects 0 or 1.",
1551 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
1557 case CONFIG_TYPE_STRING
:
1558 tor_free(*(char **)lvalue
);
1559 *(char **)lvalue
= tor_strdup(c
->value
);
1562 case CONFIG_TYPE_DOUBLE
:
1563 *(double *)lvalue
= atof(c
->value
);
1566 case CONFIG_TYPE_ISOTIME
:
1567 if (parse_iso_time(c
->value
, (time_t *)lvalue
)) {
1568 r
= tor_snprintf(buf
, sizeof(buf
),
1569 "Invalid time '%s' for keyword '%s'", c
->value
, c
->key
);
1570 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
1575 case CONFIG_TYPE_CSV
:
1576 if (*(smartlist_t
**)lvalue
) {
1577 SMARTLIST_FOREACH(*(smartlist_t
**)lvalue
, char *, cp
, tor_free(cp
));
1578 smartlist_clear(*(smartlist_t
**)lvalue
);
1580 *(smartlist_t
**)lvalue
= smartlist_create();
1583 smartlist_split_string(*(smartlist_t
**)lvalue
, c
->value
, ",",
1584 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1587 case CONFIG_TYPE_LINELIST
:
1588 case CONFIG_TYPE_LINELIST_S
:
1589 config_line_append((config_line_t
**)lvalue
, c
->key
, c
->value
);
1592 case CONFIG_TYPE_OBSOLETE
:
1593 log_warn(LD_CONFIG
, "Skipping obsolete configuration option '%s'", c
->key
);
1595 case CONFIG_TYPE_LINELIST_V
:
1596 r
= tor_snprintf(buf
, sizeof(buf
),
1597 "You may not provide a value for virtual option '%s'", c
->key
);
1598 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
1607 /** If <b>c</b> is a syntactically valid configuration line, update
1608 * <b>options</b> with its value and return 0. Otherwise return -1 for bad
1609 * key, -2 for bad value.
1611 * If <b>clear_first</b> is set, clear the value first. Then if
1612 * <b>use_defaults</b> is set, set the value to the default.
1614 * Called from config_assign().
1617 config_assign_line(config_format_t
*fmt
, or_options_t
*options
,
1618 config_line_t
*c
, int use_defaults
,
1619 int clear_first
, char **msg
)
1623 CHECK(fmt
, options
);
1625 var
= config_find_option(fmt
, c
->key
);
1628 void *lvalue
= STRUCT_VAR_P(options
, fmt
->extra
->var_offset
);
1630 "Found unrecognized option '%s'; saving it.", c
->key
);
1631 config_line_append((config_line_t
**)lvalue
, c
->key
, c
->value
);
1635 int tmp
= tor_snprintf(buf
, sizeof(buf
),
1636 "Unknown option '%s'. Failing.", c
->key
);
1637 *msg
= tor_strdup(tmp
>= 0 ? buf
: "internal error");
1641 /* Put keyword into canonical case. */
1642 if (strcmp(var
->name
, c
->key
)) {
1644 c
->key
= tor_strdup(var
->name
);
1647 if (!strlen(c
->value
)) {
1648 /* reset or clear it, then return */
1650 if (var
->type
== CONFIG_TYPE_LINELIST
||
1651 var
->type
== CONFIG_TYPE_LINELIST_S
) {
1652 /* We got an empty linelist from the torrc or commandline.
1653 As a special case, call this an error. Warn and ignore. */
1655 "Linelist option '%s' has no value. Skipping.", c
->key
);
1656 } else { /* not already cleared */
1657 option_reset(fmt
, options
, var
, use_defaults
);
1663 if (config_assign_value(fmt
, options
, c
, msg
) < 0)
1668 /** Restore the option named <b>key</b> in options to its default value.
1669 * Called from config_assign(). */
1671 config_reset_line(config_format_t
*fmt
, or_options_t
*options
,
1672 const char *key
, int use_defaults
)
1676 CHECK(fmt
, options
);
1678 var
= config_find_option(fmt
, key
);
1680 return; /* give error on next pass. */
1682 option_reset(fmt
, options
, var
, use_defaults
);
1685 /** Return true iff key is a valid configuration option. */
1687 option_is_recognized(const char *key
)
1689 config_var_t
*var
= config_find_option(&options_format
, key
);
1690 return (var
!= NULL
);
1693 /** Return the canonical name of a configuration option, or NULL
1694 * if no such option exists. */
1696 option_get_canonical_name(const char *key
)
1698 config_var_t
*var
= config_find_option(&options_format
, key
);
1699 return var
? var
->name
: NULL
;
1702 /** Return a canonicalized list of the options assigned for key.
1705 option_get_assignment(or_options_t
*options
, const char *key
)
1707 return get_assigned_option(&options_format
, options
, key
, 1);
1710 /** Return true iff value needs to be quoted and escaped to be used in
1711 * a configuration file. */
1713 config_value_needs_escape(const char *value
)
1723 /* Note: quotes and backspaces need special handling when we are using
1724 * quotes, not otherwise, so they don't trigger escaping on their
1728 if (!TOR_ISPRINT(*value
))
1736 /** Return a newly allocated deep copy of the lines in <b>inp</b>. */
1737 static config_line_t
*
1738 config_lines_dup(const config_line_t
*inp
)
1740 config_line_t
*result
= NULL
;
1741 config_line_t
**next_out
= &result
;
1743 *next_out
= tor_malloc(sizeof(config_line_t
));
1744 (*next_out
)->key
= tor_strdup(inp
->key
);
1745 (*next_out
)->value
= tor_strdup(inp
->value
);
1747 next_out
= &((*next_out
)->next
);
1753 /** Return newly allocated line or lines corresponding to <b>key</b> in the
1754 * configuration <b>options</b>. If <b>escape_val</b> is true and a
1755 * value needs to be quoted before it's put in a config file, quote and
1756 * escape that value. Return NULL if no such key exists. */
1757 static config_line_t
*
1758 get_assigned_option(config_format_t
*fmt
, or_options_t
*options
,
1759 const char *key
, int escape_val
)
1760 /* XXXX argument is options, but fmt is provided. Inconsistent. */
1765 config_line_t
*result
;
1766 tor_assert(options
&& key
);
1768 CHECK(fmt
, options
);
1770 var
= config_find_option(fmt
, key
);
1772 log_warn(LD_CONFIG
, "Unknown option '%s'. Failing.", key
);
1775 value
= STRUCT_VAR_P(options
, var
->var_offset
);
1777 result
= tor_malloc_zero(sizeof(config_line_t
));
1778 result
->key
= tor_strdup(var
->name
);
1781 case CONFIG_TYPE_STRING
:
1782 if (*(char**)value
) {
1783 result
->value
= tor_strdup(*(char**)value
);
1785 tor_free(result
->key
);
1790 case CONFIG_TYPE_ISOTIME
:
1791 if (*(time_t*)value
) {
1792 result
->value
= tor_malloc(ISO_TIME_LEN
+1);
1793 format_iso_time(result
->value
, *(time_t*)value
);
1795 tor_free(result
->key
);
1798 escape_val
= 0; /* Can't need escape. */
1800 case CONFIG_TYPE_INTERVAL
:
1801 case CONFIG_TYPE_UINT
:
1802 /* This means every or_options_t uint or bool element
1803 * needs to be an int. Not, say, a uint16_t or char. */
1804 tor_snprintf(buf
, sizeof(buf
), "%d", *(int*)value
);
1805 result
->value
= tor_strdup(buf
);
1806 escape_val
= 0; /* Can't need escape. */
1808 case CONFIG_TYPE_MEMUNIT
:
1809 tor_snprintf(buf
, sizeof(buf
), U64_FORMAT
,
1810 U64_PRINTF_ARG(*(uint64_t*)value
));
1811 result
->value
= tor_strdup(buf
);
1812 escape_val
= 0; /* Can't need escape. */
1814 case CONFIG_TYPE_DOUBLE
:
1815 tor_snprintf(buf
, sizeof(buf
), "%f", *(double*)value
);
1816 result
->value
= tor_strdup(buf
);
1817 escape_val
= 0; /* Can't need escape. */
1819 case CONFIG_TYPE_BOOL
:
1820 result
->value
= tor_strdup(*(int*)value
? "1" : "0");
1821 escape_val
= 0; /* Can't need escape. */
1823 case CONFIG_TYPE_CSV
:
1824 if (*(smartlist_t
**)value
)
1826 smartlist_join_strings(*(smartlist_t
**)value
, ",", 0, NULL
);
1828 result
->value
= tor_strdup("");
1830 case CONFIG_TYPE_OBSOLETE
:
1832 "You asked me for the value of an obsolete config option '%s'.",
1834 tor_free(result
->key
);
1837 case CONFIG_TYPE_LINELIST_S
:
1839 "Can't return context-sensitive '%s' on its own", key
);
1840 tor_free(result
->key
);
1843 case CONFIG_TYPE_LINELIST
:
1844 case CONFIG_TYPE_LINELIST_V
:
1845 tor_free(result
->key
);
1847 result
= config_lines_dup(*(const config_line_t
**)value
);
1850 tor_free(result
->key
);
1852 log_warn(LD_BUG
,"Unknown type %d for known key '%s'",
1858 config_line_t
*line
;
1859 for (line
= result
; line
; line
= line
->next
) {
1860 if (line
->value
&& config_value_needs_escape(line
->value
)) {
1861 char *newval
= esc_for_log(line
->value
);
1862 tor_free(line
->value
);
1863 line
->value
= newval
;
1871 /** Iterate through the linked list of requested options <b>list</b>.
1872 * For each item, convert as appropriate and assign to <b>options</b>.
1873 * If an item is unrecognized, set *msg and return -1 immediately,
1874 * else return 0 for success.
1876 * If <b>clear_first</b>, interpret config options as replacing (not
1877 * extending) their previous values. If <b>clear_first</b> is set,
1878 * then <b>use_defaults</b> to decide if you set to defaults after
1879 * clearing, or make the value 0 or NULL.
1881 * Here are the use cases:
1882 * 1. A non-empty AllowInvalid line in your torrc. Appends to current
1883 * if linelist, replaces current if csv.
1884 * 2. An empty AllowInvalid line in your torrc. Should clear it.
1885 * 3. "RESETCONF AllowInvalid" sets it to default.
1886 * 4. "SETCONF AllowInvalid" makes it NULL.
1887 * 5. "SETCONF AllowInvalid=foo" clears it and sets it to "foo".
1889 * Use_defaults Clear_first
1891 * 1 0 undefined, don't use
1892 * 0 1 "set to null first"
1893 * 1 1 "set to defaults first"
1894 * Return 0 on success, -1 on bad key, -2 on bad value.
1896 * As an additional special case, if a LINELIST config option has
1897 * no value and clear_first is 0, then warn and ignore it.
1901 There are three call cases for config_assign() currently.
1903 Case one: Torrc entry
1904 options_init_from_torrc() calls config_assign(0, 0)
1905 calls config_assign_line(0, 0).
1906 if value is empty, calls option_reset(0) and returns.
1907 calls config_assign_value(), appends.
1910 options_trial_assign() calls config_assign(0, 1)
1911 calls config_reset_line(0)
1912 calls option_reset(0)
1913 calls option_clear().
1914 calls config_assign_line(0, 1).
1915 if value is empty, returns.
1916 calls config_assign_value(), appends.
1918 Case three: resetconf
1919 options_trial_assign() calls config_assign(1, 1)
1920 calls config_reset_line(1)
1921 calls option_reset(1)
1922 calls option_clear().
1923 calls config_assign_value(default)
1924 calls config_assign_line(1, 1).
1928 config_assign(config_format_t
*fmt
, void *options
, config_line_t
*list
,
1929 int use_defaults
, int clear_first
, char **msg
)
1933 CHECK(fmt
, options
);
1935 /* pass 1: normalize keys */
1936 for (p
= list
; p
; p
= p
->next
) {
1937 const char *full
= expand_abbrev(fmt
, p
->key
, 0, 1);
1938 if (strcmp(full
,p
->key
)) {
1940 p
->key
= tor_strdup(full
);
1944 /* pass 2: if we're reading from a resetting source, clear all
1945 * mentioned config options, and maybe set to their defaults. */
1947 for (p
= list
; p
; p
= p
->next
)
1948 config_reset_line(fmt
, options
, p
->key
, use_defaults
);
1951 /* pass 3: assign. */
1954 if ((r
=config_assign_line(fmt
, options
, list
, use_defaults
,
1962 /** Try assigning <b>list</b> to the global options. You do this by duping
1963 * options, assigning list to the new one, then validating it. If it's
1964 * ok, then throw out the old one and stick with the new one. Else,
1965 * revert to old and return failure. Return 0 on success, -1 on bad
1966 * keys, -2 on bad values, -3 on bad transition, and -4 on failed-to-set.
1968 * If not success, point *<b>msg</b> to a newly allocated string describing
1972 options_trial_assign(config_line_t
*list
, int use_defaults
,
1973 int clear_first
, char **msg
)
1976 or_options_t
*trial_options
= options_dup(&options_format
, get_options());
1978 if ((r
=config_assign(&options_format
, trial_options
,
1979 list
, use_defaults
, clear_first
, msg
)) < 0) {
1980 config_free(&options_format
, trial_options
);
1984 if (options_validate(get_options(), trial_options
, 1, msg
) < 0) {
1985 config_free(&options_format
, trial_options
);
1989 if (options_transition_allowed(get_options(), trial_options
, msg
) < 0) {
1990 config_free(&options_format
, trial_options
);
1994 if (set_options(trial_options
, msg
)<0) {
1995 config_free(&options_format
, trial_options
);
1999 /* we liked it. put it in place. */
2003 /** Reset config option <b>var</b> to 0, 0.0, NULL, or the equivalent.
2004 * Called from option_reset() and config_free(). */
2006 option_clear(config_format_t
*fmt
, or_options_t
*options
, config_var_t
*var
)
2008 void *lvalue
= STRUCT_VAR_P(options
, var
->var_offset
);
2009 (void)fmt
; /* unused */
2010 switch (var
->type
) {
2011 case CONFIG_TYPE_STRING
:
2012 tor_free(*(char**)lvalue
);
2014 case CONFIG_TYPE_DOUBLE
:
2015 *(double*)lvalue
= 0.0;
2017 case CONFIG_TYPE_ISOTIME
:
2018 *(time_t*)lvalue
= 0;
2019 case CONFIG_TYPE_INTERVAL
:
2020 case CONFIG_TYPE_UINT
:
2021 case CONFIG_TYPE_BOOL
:
2024 case CONFIG_TYPE_MEMUNIT
:
2025 *(uint64_t*)lvalue
= 0;
2027 case CONFIG_TYPE_CSV
:
2028 if (*(smartlist_t
**)lvalue
) {
2029 SMARTLIST_FOREACH(*(smartlist_t
**)lvalue
, char *, cp
, tor_free(cp
));
2030 smartlist_free(*(smartlist_t
**)lvalue
);
2031 *(smartlist_t
**)lvalue
= NULL
;
2034 case CONFIG_TYPE_LINELIST
:
2035 case CONFIG_TYPE_LINELIST_S
:
2036 config_free_lines(*(config_line_t
**)lvalue
);
2037 *(config_line_t
**)lvalue
= NULL
;
2039 case CONFIG_TYPE_LINELIST_V
:
2040 /* handled by linelist_s. */
2042 case CONFIG_TYPE_OBSOLETE
:
2047 /** Clear the option indexed by <b>var</b> in <b>options</b>. Then if
2048 * <b>use_defaults</b>, set it to its default value.
2049 * Called by config_init() and option_reset_line() and option_assign_line(). */
2051 option_reset(config_format_t
*fmt
, or_options_t
*options
,
2052 config_var_t
*var
, int use_defaults
)
2056 CHECK(fmt
, options
);
2057 option_clear(fmt
, options
, var
); /* clear it first */
2059 return; /* all done */
2060 if (var
->initvalue
) {
2061 c
= tor_malloc_zero(sizeof(config_line_t
));
2062 c
->key
= tor_strdup(var
->name
);
2063 c
->value
= tor_strdup(var
->initvalue
);
2064 if (config_assign_value(fmt
, options
, c
, &msg
) < 0) {
2065 log_warn(LD_BUG
, "Failed to assign default: %s", msg
);
2066 tor_free(msg
); /* if this happens it's a bug */
2068 config_free_lines(c
);
2072 /** Print a usage message for tor. */
2077 "Copyright (c) 2001-2004, Roger Dingledine\n"
2078 "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
2079 "Copyright (c) 2007-2008, The Tor Project, Inc.\n\n"
2080 "tor -f <torrc> [args]\n"
2081 "See man page for options, or https://www.torproject.org/ for "
2082 "documentation.\n");
2085 /** Print all non-obsolete torrc options. */
2087 list_torrc_options(void)
2090 smartlist_t
*lines
= smartlist_create();
2091 for (i
= 0; _option_vars
[i
].name
; ++i
) {
2092 config_var_t
*var
= &_option_vars
[i
];
2094 if (var
->type
== CONFIG_TYPE_OBSOLETE
||
2095 var
->type
== CONFIG_TYPE_LINELIST_V
)
2097 desc
= config_find_description(&options_format
, var
->name
);
2098 printf("%s\n", var
->name
);
2100 wrap_string(lines
, desc
, 76, " ", " ");
2101 SMARTLIST_FOREACH(lines
, char *, cp
, {
2105 smartlist_clear(lines
);
2108 smartlist_free(lines
);
2111 /** Last value actually set by resolve_my_address. */
2112 static uint32_t last_resolved_addr
= 0;
2114 * Based on <b>options-\>Address</b>, guess our public IP address and put it
2115 * (in host order) into *<b>addr_out</b>. If <b>hostname_out</b> is provided,
2116 * set *<b>hostname_out</b> to a new string holding the hostname we used to
2117 * get the address. Return 0 if all is well, or -1 if we can't find a suitable
2118 * public IP address.
2121 resolve_my_address(int warn_severity
, or_options_t
*options
,
2122 uint32_t *addr_out
, char **hostname_out
)
2125 struct hostent
*rent
;
2128 int explicit_hostname
=1;
2129 int from_interface
=0;
2130 char tmpbuf
[INET_NTOA_BUF_LEN
];
2131 const char *address
= options
->Address
;
2132 int notice_severity
= warn_severity
<= LOG_NOTICE
?
2133 LOG_NOTICE
: warn_severity
;
2135 tor_assert(addr_out
);
2137 if (address
&& *address
) {
2138 strlcpy(hostname
, address
, sizeof(hostname
));
2139 } else { /* then we need to guess our address */
2140 explicit_ip
= 0; /* it's implicit */
2141 explicit_hostname
= 0; /* it's implicit */
2143 if (gethostname(hostname
, sizeof(hostname
)) < 0) {
2144 log_fn(warn_severity
, LD_NET
,"Error obtaining local hostname");
2147 log_debug(LD_CONFIG
,"Guessed local host name as '%s'",hostname
);
2150 /* now we know hostname. resolve it and keep only the IP address */
2152 if (tor_inet_aton(hostname
, &in
) == 0) {
2153 /* then we have to resolve it */
2155 rent
= (struct hostent
*)gethostbyname(hostname
);
2157 uint32_t interface_ip
;
2159 if (explicit_hostname
) {
2160 log_fn(warn_severity
, LD_CONFIG
,
2161 "Could not resolve local Address '%s'. Failing.", hostname
);
2164 log_fn(notice_severity
, LD_CONFIG
,
2165 "Could not resolve guessed local hostname '%s'. "
2166 "Trying something else.", hostname
);
2167 if (get_interface_address(warn_severity
, &interface_ip
)) {
2168 log_fn(warn_severity
, LD_CONFIG
,
2169 "Could not get local interface IP address. Failing.");
2173 in
.s_addr
= htonl(interface_ip
);
2174 tor_inet_ntoa(&in
,tmpbuf
,sizeof(tmpbuf
));
2175 log_fn(notice_severity
, LD_CONFIG
, "Learned IP address '%s' for "
2176 "local interface. Using that.", tmpbuf
);
2177 strlcpy(hostname
, "<guessed from interfaces>", sizeof(hostname
));
2179 tor_assert(rent
->h_length
== 4);
2180 memcpy(&in
.s_addr
, rent
->h_addr
, rent
->h_length
);
2182 if (!explicit_hostname
&&
2183 is_internal_IP(ntohl(in
.s_addr
), 0)) {
2184 uint32_t interface_ip
;
2186 tor_inet_ntoa(&in
,tmpbuf
,sizeof(tmpbuf
));
2187 log_fn(notice_severity
, LD_CONFIG
, "Guessed local hostname '%s' "
2188 "resolves to a private IP address (%s). Trying something "
2189 "else.", hostname
, tmpbuf
);
2191 if (get_interface_address(warn_severity
, &interface_ip
)) {
2192 log_fn(warn_severity
, LD_CONFIG
,
2193 "Could not get local interface IP address. Too bad.");
2194 } else if (is_internal_IP(interface_ip
, 0)) {
2196 in2
.s_addr
= htonl(interface_ip
);
2197 tor_inet_ntoa(&in2
,tmpbuf
,sizeof(tmpbuf
));
2198 log_fn(notice_severity
, LD_CONFIG
,
2199 "Interface IP address '%s' is a private address too. "
2200 "Ignoring.", tmpbuf
);
2203 in
.s_addr
= htonl(interface_ip
);
2204 tor_inet_ntoa(&in
,tmpbuf
,sizeof(tmpbuf
));
2205 log_fn(notice_severity
, LD_CONFIG
,
2206 "Learned IP address '%s' for local interface."
2207 " Using that.", tmpbuf
);
2208 strlcpy(hostname
, "<guessed from interfaces>", sizeof(hostname
));
2214 tor_inet_ntoa(&in
,tmpbuf
,sizeof(tmpbuf
));
2215 if (is_internal_IP(ntohl(in
.s_addr
), 0) &&
2216 options
->_PublishServerDescriptor
) {
2217 /* make sure we're ok with publishing an internal IP */
2218 if (!options
->DirServers
&& !options
->AlternateDirAuthority
) {
2219 /* if they are using the default dirservers, disallow internal IPs
2221 log_fn(warn_severity
, LD_CONFIG
,
2222 "Address '%s' resolves to private IP address '%s'. "
2223 "Tor servers that use the default DirServers must have public "
2224 "IP addresses.", hostname
, tmpbuf
);
2228 /* even if they've set their own dirservers, require an explicit IP if
2229 * they're using an internal address. */
2230 log_fn(warn_severity
, LD_CONFIG
, "Address '%s' resolves to private "
2231 "IP address '%s'. Please set the Address config option to be "
2232 "the IP address you want to use.", hostname
, tmpbuf
);
2237 log_debug(LD_CONFIG
, "Resolved Address to '%s'.", tmpbuf
);
2238 *addr_out
= ntohl(in
.s_addr
);
2239 if (last_resolved_addr
&& last_resolved_addr
!= *addr_out
) {
2240 /* Leave this as a notice, regardless of the requested severity,
2241 * at least until dynamic IP address support becomes bulletproof. */
2243 "Your IP address seems to have changed to %s. Updating.",
2245 ip_address_changed(0);
2247 if (last_resolved_addr
!= *addr_out
) {
2249 const char *h
= hostname
;
2251 method
= "CONFIGURED";
2253 } else if (explicit_hostname
) {
2254 method
= "RESOLVED";
2255 } else if (from_interface
) {
2256 method
= "INTERFACE";
2259 method
= "GETHOSTNAME";
2261 control_event_server_status(LOG_NOTICE
,
2262 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s %s%s",
2263 tmpbuf
, method
, h
?"HOSTNAME=":"", h
);
2265 last_resolved_addr
= *addr_out
;
2267 *hostname_out
= tor_strdup(hostname
);
2271 /** Return true iff <b>ip</b> (in host order) is judged to be on the
2272 * same network as us, or on a private network.
2275 is_local_IP(uint32_t ip
)
2277 if (is_internal_IP(ip
, 0))
2279 /* Check whether ip is on the same /24 as we are. */
2280 if (get_options()->EnforceDistinctSubnets
== 0)
2282 /* It's possible that this next check will hit before the first time
2283 * resolve_my_address actually succeeds. (For clients, it is likely that
2284 * resolve_my_address will never be called at all). In those cases,
2285 * last_resolved_addr will be 0, and so checking to see whether ip is on the
2286 * same /24 as last_resolved_addr will be the same as checking whether it
2287 * was on net 0, which is already done by is_internal_IP.
2289 if ((last_resolved_addr
& 0xffffff00ul
) == (ip
& 0xffffff00ul
))
2294 /** Called when we don't have a nickname set. Try to guess a good nickname
2295 * based on the hostname, and return it in a newly allocated string. If we
2296 * can't, return NULL and let the caller warn if it wants to. */
2298 get_default_nickname(void)
2300 static const char * const bad_default_nicknames
[] = {
2304 char localhostname
[256];
2305 char *cp
, *out
, *outp
;
2308 if (gethostname(localhostname
, sizeof(localhostname
)) < 0)
2311 /* Put it in lowercase; stop at the first dot. */
2312 if ((cp
= strchr(localhostname
, '.')))
2314 tor_strlower(localhostname
);
2316 /* Strip invalid characters. */
2318 out
= outp
= tor_malloc(strlen(localhostname
) + 1);
2320 if (strchr(LEGAL_NICKNAME_CHARACTERS
, *cp
))
2327 /* Enforce length. */
2328 if (strlen(out
) > MAX_NICKNAME_LEN
)
2329 out
[MAX_NICKNAME_LEN
]='\0';
2331 /* Check for dumb names. */
2332 for (i
= 0; bad_default_nicknames
[i
]; ++i
) {
2333 if (!strcmp(out
, bad_default_nicknames
[i
])) {
2342 /** Release storage held by <b>options</b>. */
2344 config_free(config_format_t
*fmt
, void *options
)
2348 tor_assert(options
);
2350 for (i
=0; fmt
->vars
[i
].name
; ++i
)
2351 option_clear(fmt
, options
, &(fmt
->vars
[i
]));
2353 config_line_t
**linep
= STRUCT_VAR_P(options
, fmt
->extra
->var_offset
);
2354 config_free_lines(*linep
);
2360 /** Return true iff a and b contain identical keys and values in identical
2363 config_lines_eq(config_line_t
*a
, config_line_t
*b
)
2366 if (strcasecmp(a
->key
, b
->key
) || strcmp(a
->value
, b
->value
))
2376 /** Return true iff the option <b>name</b> has the same value in <b>o1</b>
2377 * and <b>o2</b>. Must not be called for LINELIST_S or OBSOLETE options.
2380 option_is_same(config_format_t
*fmt
,
2381 or_options_t
*o1
, or_options_t
*o2
, const char *name
)
2383 config_line_t
*c1
, *c2
;
2388 c1
= get_assigned_option(fmt
, o1
, name
, 0);
2389 c2
= get_assigned_option(fmt
, o2
, name
, 0);
2390 r
= config_lines_eq(c1
, c2
);
2391 config_free_lines(c1
);
2392 config_free_lines(c2
);
2396 /** Copy storage held by <b>old</b> into a new or_options_t and return it. */
2397 static or_options_t
*
2398 options_dup(config_format_t
*fmt
, or_options_t
*old
)
2400 or_options_t
*newopts
;
2402 config_line_t
*line
;
2404 newopts
= config_alloc(fmt
);
2405 for (i
=0; fmt
->vars
[i
].name
; ++i
) {
2406 if (fmt
->vars
[i
].type
== CONFIG_TYPE_LINELIST_S
)
2408 if (fmt
->vars
[i
].type
== CONFIG_TYPE_OBSOLETE
)
2410 line
= get_assigned_option(fmt
, old
, fmt
->vars
[i
].name
, 0);
2413 if (config_assign(fmt
, newopts
, line
, 0, 0, &msg
) < 0) {
2414 log_err(LD_BUG
, "Config_get_assigned_option() generated "
2415 "something we couldn't config_assign(): %s", msg
);
2420 config_free_lines(line
);
2425 /** Return a new empty or_options_t. Used for testing. */
2429 return config_alloc(&options_format
);
2432 /** Set <b>options</b> to hold reasonable defaults for most options.
2433 * Each option defaults to zero. */
2435 options_init(or_options_t
*options
)
2437 config_init(&options_format
, options
);
2440 /* Set all vars in the configuration object 'options' to their default
2443 config_init(config_format_t
*fmt
, void *options
)
2447 CHECK(fmt
, options
);
2449 for (i
=0; fmt
->vars
[i
].name
; ++i
) {
2450 var
= &fmt
->vars
[i
];
2451 if (!var
->initvalue
)
2452 continue; /* defaults to NULL or 0 */
2453 option_reset(fmt
, options
, var
, 1);
2457 /** Allocate and return a new string holding the written-out values of the vars
2458 * in 'options'. If 'minimal', do not write out any default-valued vars.
2459 * Else, if comment_defaults, write default values as comments.
2462 config_dump(config_format_t
*fmt
, void *options
, int minimal
,
2463 int comment_defaults
)
2465 smartlist_t
*elements
;
2466 or_options_t
*defaults
;
2467 config_line_t
*line
, *assigned
;
2473 defaults
= config_alloc(fmt
);
2474 config_init(fmt
, defaults
);
2476 /* XXX use a 1 here so we don't add a new log line while dumping */
2477 if (fmt
->validate_fn(NULL
,defaults
, 1, &msg
) < 0) {
2478 log_err(LD_BUG
, "Failed to validate default config.");
2483 elements
= smartlist_create();
2484 for (i
=0; fmt
->vars
[i
].name
; ++i
) {
2485 int comment_option
= 0;
2486 if (fmt
->vars
[i
].type
== CONFIG_TYPE_OBSOLETE
||
2487 fmt
->vars
[i
].type
== CONFIG_TYPE_LINELIST_S
)
2489 /* Don't save 'hidden' control variables. */
2490 if (!strcmpstart(fmt
->vars
[i
].name
, "__"))
2492 if (minimal
&& option_is_same(fmt
, options
, defaults
, fmt
->vars
[i
].name
))
2494 else if (comment_defaults
&&
2495 option_is_same(fmt
, options
, defaults
, fmt
->vars
[i
].name
))
2498 desc
= config_find_description(fmt
, fmt
->vars
[i
].name
);
2499 line
= assigned
= get_assigned_option(fmt
, options
, fmt
->vars
[i
].name
, 1);
2502 /* Only dump the description if there's something to describe. */
2503 wrap_string(elements
, desc
, 78, "# ", "# ");
2506 for (; line
; line
= line
->next
) {
2507 size_t len
= strlen(line
->key
) + strlen(line
->value
) + 5;
2509 tmp
= tor_malloc(len
);
2510 if (tor_snprintf(tmp
, len
, "%s%s %s\n",
2511 comment_option
? "# " : "",
2512 line
->key
, line
->value
)<0) {
2513 log_err(LD_BUG
,"Internal error writing option value");
2516 smartlist_add(elements
, tmp
);
2518 config_free_lines(assigned
);
2522 line
= *(config_line_t
**)STRUCT_VAR_P(options
, fmt
->extra
->var_offset
);
2523 for (; line
; line
= line
->next
) {
2524 size_t len
= strlen(line
->key
) + strlen(line
->value
) + 3;
2526 tmp
= tor_malloc(len
);
2527 if (tor_snprintf(tmp
, len
, "%s %s\n", line
->key
, line
->value
)<0) {
2528 log_err(LD_BUG
,"Internal error writing option value");
2531 smartlist_add(elements
, tmp
);
2535 result
= smartlist_join_strings(elements
, "", 0, NULL
);
2536 SMARTLIST_FOREACH(elements
, char *, cp
, tor_free(cp
));
2537 smartlist_free(elements
);
2538 config_free(fmt
, defaults
);
2542 /** Return a string containing a possible configuration file that would give
2543 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
2544 * include options that are the same as Tor's defaults.
2547 options_dump(or_options_t
*options
, int minimal
)
2549 return config_dump(&options_format
, options
, minimal
, 0);
2552 /** Return 0 if every element of sl is a string holding a decimal
2553 * representation of a port number, or if sl is NULL.
2554 * Otherwise set *msg and return -1. */
2556 validate_ports_csv(smartlist_t
*sl
, const char *name
, char **msg
)
2565 SMARTLIST_FOREACH(sl
, const char *, cp
,
2568 if (i
< 1 || i
> 65535) {
2569 int r
= tor_snprintf(buf
, sizeof(buf
),
2570 "Port '%s' out of range in %s", cp
, name
);
2571 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
2578 /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
2579 * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
2583 ensure_bandwidth_cap(uint64_t *value
, const char *desc
, char **msg
)
2587 if (*value
> ROUTER_MAX_DECLARED_BANDWIDTH
) {
2588 /* This handles an understandable special case where somebody says "2gb"
2589 * whereas our actual maximum is 2gb-1 (INT_MAX) */
2592 if (*value
> ROUTER_MAX_DECLARED_BANDWIDTH
) {
2593 r
= tor_snprintf(buf
, sizeof(buf
), "%s ("U64_FORMAT
") must be at most %d",
2594 desc
, U64_PRINTF_ARG(*value
),
2595 ROUTER_MAX_DECLARED_BANDWIDTH
);
2596 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
2602 /** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
2603 * and write it to <b>options</b>-\>_PublishServerDescriptor. Treat "1"
2604 * as "v2,v3" unless BridgeRelay is 1, in which case treat it as "bridge".
2606 * Return 0 on success or -1 if not a recognized authority type (in which
2607 * case the value of _PublishServerDescriptor is undefined). */
2609 compute_publishserverdescriptor(or_options_t
*options
)
2611 smartlist_t
*list
= options
->PublishServerDescriptor
;
2612 authority_type_t
*auth
= &options
->_PublishServerDescriptor
;
2613 *auth
= NO_AUTHORITY
;
2614 if (!list
) /* empty list, answer is none */
2616 SMARTLIST_FOREACH(list
, const char *, string
, {
2617 if (!strcasecmp(string
, "v1"))
2618 *auth
|= V1_AUTHORITY
;
2619 else if (!strcmp(string
, "1"))
2620 if (options
->BridgeRelay
)
2621 *auth
|= BRIDGE_AUTHORITY
;
2623 *auth
|= V2_AUTHORITY
| V3_AUTHORITY
;
2624 else if (!strcasecmp(string
, "v2"))
2625 *auth
|= V2_AUTHORITY
;
2626 else if (!strcasecmp(string
, "v3"))
2627 *auth
|= V3_AUTHORITY
;
2628 else if (!strcasecmp(string
, "bridge"))
2629 *auth
|= BRIDGE_AUTHORITY
;
2630 else if (!strcasecmp(string
, "hidserv"))
2631 *auth
|= HIDSERV_AUTHORITY
;
2632 else if (!strcasecmp(string
, "") || !strcmp(string
, "0"))
2640 /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
2641 * services can overload the directory system. */
2642 #define MIN_REND_POST_PERIOD (10*60)
2644 /** Highest allowable value for RendPostPeriod. */
2645 #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
2647 /** Return 0 if every setting in <b>options</b> is reasonable, and a
2648 * permissible transition from <b>old_options</b>. Else return -1.
2649 * Should have no side effects, except for normalizing the contents of
2652 * On error, tor_strdup an error explanation into *<b>msg</b>.
2655 * If <b>from_setconf</b>, we were called by the controller, and our
2656 * Log line should stay empty. If it's 0, then give us a default log
2657 * if there are no logs defined.
2660 options_validate(or_options_t
*old_options
, or_options_t
*options
,
2661 int from_setconf
, char **msg
)
2665 const char *uname
= get_uname();
2667 #define REJECT(arg) \
2668 STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
2669 #define COMPLAIN(arg) STMT_BEGIN log(LOG_WARN, LD_CONFIG, arg); STMT_END
2674 if (options
->ORPort
< 0 || options
->ORPort
> 65535)
2675 REJECT("ORPort option out of bounds.");
2677 if (server_mode(options
) &&
2678 (!strcmpstart(uname
, "Windows 95") ||
2679 !strcmpstart(uname
, "Windows 98") ||
2680 !strcmpstart(uname
, "Windows Me"))) {
2681 log(LOG_WARN
, LD_CONFIG
, "Tor is running as a server, but you are "
2682 "running %s; this probably won't work. See "
2683 "http://wiki.noreply.org/noreply/TheOnionRouter/TorFAQ#ServerOS "
2684 "for details.", uname
);
2687 if (options
->ORPort
== 0 && options
->ORListenAddress
!= NULL
)
2688 REJECT("ORPort must be defined if ORListenAddress is defined.");
2690 if (options
->DirPort
== 0 && options
->DirListenAddress
!= NULL
)
2691 REJECT("DirPort must be defined if DirListenAddress is defined.");
2693 if (options
->DNSPort
== 0 && options
->DNSListenAddress
!= NULL
)
2694 REJECT("DNSPort must be defined if DNSListenAddress is defined.");
2696 if (options
->ControlPort
== 0 && options
->ControlListenAddress
!= NULL
)
2697 REJECT("ControlPort must be defined if ControlListenAddress is defined.");
2699 if (options
->TransPort
== 0 && options
->TransListenAddress
!= NULL
)
2700 REJECT("TransPort must be defined if TransListenAddress is defined.");
2702 if (options
->NatdPort
== 0 && options
->NatdListenAddress
!= NULL
)
2703 REJECT("NatdPort must be defined if NatdListenAddress is defined.");
2705 /* Don't gripe about SocksPort 0 with SocksListenAddress set; a standard
2706 * configuration does this. */
2708 for (i
= 0; i
< 3; ++i
) {
2709 int is_socks
= i
==0;
2710 int is_trans
= i
==1;
2711 config_line_t
*line
, *opt
, *old
;
2714 opt
= options
->SocksListenAddress
;
2715 old
= old_options
? old_options
->SocksListenAddress
: NULL
;
2717 } else if (is_trans
) {
2718 opt
= options
->TransListenAddress
;
2719 old
= old_options
? old_options
->TransListenAddress
: NULL
;
2720 tp
= "transparent proxy";
2722 opt
= options
->NatdListenAddress
;
2723 old
= old_options
? old_options
->NatdListenAddress
: NULL
;
2727 for (line
= opt
; line
; line
= line
->next
) {
2728 char *address
= NULL
;
2731 if (parse_addr_port(LOG_WARN
, line
->value
, &address
, &addr
, &port
)<0)
2732 continue; /* We'll warn about this later. */
2733 if (!is_internal_IP(addr
, 1) &&
2734 (!old_options
|| !config_lines_eq(old
, opt
))) {
2736 "You specified a public address '%s' for a %s. Other "
2737 "people on the Internet might find your computer and use it as "
2738 "an open %s. Please don't allow this unless you have "
2739 "a good reason.", address
, tp
, tp
);
2745 if (validate_data_directory(options
)<0)
2746 REJECT("Invalid DataDirectory");
2748 if (options
->Nickname
== NULL
) {
2749 if (server_mode(options
)) {
2750 if (!(options
->Nickname
= get_default_nickname())) {
2751 log_notice(LD_CONFIG
, "Couldn't pick a nickname based on "
2752 "our hostname; using %s instead.", UNNAMED_ROUTER_NICKNAME
);
2753 options
->Nickname
= tor_strdup(UNNAMED_ROUTER_NICKNAME
);
2755 log_notice(LD_CONFIG
, "Choosing default nickname '%s'",
2760 if (!is_legal_nickname(options
->Nickname
)) {
2761 r
= tor_snprintf(buf
, sizeof(buf
),
2762 "Nickname '%s' is wrong length or contains illegal characters.",
2764 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
2769 if (server_mode(options
) && !options
->ContactInfo
)
2770 log(LOG_NOTICE
, LD_CONFIG
, "Your ContactInfo config option is not set. "
2771 "Please consider setting it, so we can contact you if your server is "
2772 "misconfigured or something else goes wrong.");
2774 /* Special case on first boot if no Log options are given. */
2775 if (!options
->Logs
&& !options
->RunAsDaemon
&& !from_setconf
)
2776 config_line_append(&options
->Logs
, "Log", "notice stdout");
2778 if (options_init_logs(options
, 1)<0) /* Validate the log(s) */
2779 REJECT("Failed to validate Log options. See logs for details.");
2781 if (options
->NoPublish
) {
2782 log(LOG_WARN
, LD_CONFIG
,
2783 "NoPublish is obsolete. Use PublishServerDescriptor instead.");
2784 SMARTLIST_FOREACH(options
->PublishServerDescriptor
, char *, s
,
2786 smartlist_clear(options
->PublishServerDescriptor
);
2789 if (authdir_mode(options
)) {
2790 /* confirm that our address isn't broken, so we can complain now */
2792 if (resolve_my_address(LOG_WARN
, options
, &tmp
, NULL
) < 0)
2793 REJECT("Failed to resolve/guess local address. See logs for details.");
2797 if (options
->RunAsDaemon
&& torrc_fname
&& path_is_relative(torrc_fname
))
2798 REJECT("Can't use a relative path to torrc when RunAsDaemon is set.");
2801 if (options
->SocksPort
< 0 || options
->SocksPort
> 65535)
2802 REJECT("SocksPort option out of bounds.");
2804 if (options
->DNSPort
< 0 || options
->DNSPort
> 65535)
2805 REJECT("DNSPort option out of bounds.");
2807 if (options
->TransPort
< 0 || options
->TransPort
> 65535)
2808 REJECT("TransPort option out of bounds.");
2810 if (options
->NatdPort
< 0 || options
->NatdPort
> 65535)
2811 REJECT("NatdPort option out of bounds.");
2813 if (options
->SocksPort
== 0 && options
->TransPort
== 0 &&
2814 options
->NatdPort
== 0 && options
->ORPort
== 0 &&
2815 options
->DNSPort
== 0 && !options
->RendConfigLines
)
2816 log(LOG_WARN
, LD_CONFIG
,
2817 "SocksPort, TransPort, NatdPort, DNSPort, and ORPort are all "
2818 "undefined, and there aren't any hidden services configured. "
2819 "Tor will still run, but probably won't do anything.");
2821 if (options
->ControlPort
< 0 || options
->ControlPort
> 65535)
2822 REJECT("ControlPort option out of bounds.");
2824 if (options
->DirPort
< 0 || options
->DirPort
> 65535)
2825 REJECT("DirPort option out of bounds.");
2827 #ifndef USE_TRANSPARENT
2828 if (options
->TransPort
|| options
->TransListenAddress
)
2829 REJECT("TransPort and TransListenAddress are disabled in this build.");
2832 if (options
->StrictExitNodes
&&
2833 (!options
->ExitNodes
|| !strlen(options
->ExitNodes
)) &&
2835 (old_options
->StrictExitNodes
!= options
->StrictExitNodes
) ||
2836 (!opt_streq(old_options
->ExitNodes
, options
->ExitNodes
))))
2837 COMPLAIN("StrictExitNodes set, but no ExitNodes listed.");
2839 if (options
->StrictEntryNodes
&&
2840 (!options
->EntryNodes
|| !strlen(options
->EntryNodes
)) &&
2842 (old_options
->StrictEntryNodes
!= options
->StrictEntryNodes
) ||
2843 (!opt_streq(old_options
->EntryNodes
, options
->EntryNodes
))))
2844 COMPLAIN("StrictEntryNodes set, but no EntryNodes listed.");
2846 if (options
->AuthoritativeDir
) {
2847 if (!options
->ContactInfo
)
2848 REJECT("Authoritative directory servers must set ContactInfo");
2849 if (options
->V1AuthoritativeDir
&& !options
->RecommendedVersions
)
2850 REJECT("V1 auth dir servers must set RecommendedVersions.");
2851 if (!options
->RecommendedClientVersions
)
2852 options
->RecommendedClientVersions
=
2853 config_lines_dup(options
->RecommendedVersions
);
2854 if (!options
->RecommendedServerVersions
)
2855 options
->RecommendedServerVersions
=
2856 config_lines_dup(options
->RecommendedVersions
);
2857 if (options
->VersioningAuthoritativeDir
&&
2858 (!options
->RecommendedClientVersions
||
2859 !options
->RecommendedServerVersions
))
2860 REJECT("Versioning auth dir servers must set Recommended*Versions.");
2861 if (options
->UseEntryGuards
) {
2862 log_info(LD_CONFIG
, "Authoritative directory servers can't set "
2863 "UseEntryGuards. Disabling.");
2864 options
->UseEntryGuards
= 0;
2866 if (!options
->DownloadExtraInfo
&& authdir_mode_any_main(options
)) {
2867 log_info(LD_CONFIG
, "Authoritative directories always try to download "
2868 "extra-info documents. Setting DownloadExtraInfo.");
2869 options
->DownloadExtraInfo
= 1;
2871 if (!(options
->BridgeAuthoritativeDir
|| options
->HSAuthoritativeDir
||
2872 options
->V1AuthoritativeDir
|| options
->V2AuthoritativeDir
||
2873 options
->V3AuthoritativeDir
))
2874 REJECT("AuthoritativeDir is set, but none of "
2875 "(Bridge/HS/V1/V2/V3)AuthoritativeDir is set.");
2878 if (options
->AuthoritativeDir
&& !options
->DirPort
)
2879 REJECT("Running as authoritative directory, but no DirPort set.");
2881 if (options
->AuthoritativeDir
&& !options
->ORPort
)
2882 REJECT("Running as authoritative directory, but no ORPort set.");
2884 if (options
->AuthoritativeDir
&& options
->ClientOnly
)
2885 REJECT("Running as authoritative directory, but ClientOnly also set.");
2887 if (options
->HSAuthorityRecordStats
&& !options
->HSAuthoritativeDir
)
2888 REJECT("HSAuthorityRecordStats is set but we're not running as "
2889 "a hidden service authority.");
2891 if (options
->HidServDirectoryV2
&& !options
->DirPort
)
2892 REJECT("Running as hidden service directory, but no DirPort set.");
2894 if (options
->ConnLimit
<= 0) {
2895 r
= tor_snprintf(buf
, sizeof(buf
),
2896 "ConnLimit must be greater than 0, but was set to %d",
2897 options
->ConnLimit
);
2898 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
2902 if (validate_ports_csv(options
->FirewallPorts
, "FirewallPorts", msg
) < 0)
2905 if (validate_ports_csv(options
->LongLivedPorts
, "LongLivedPorts", msg
) < 0)
2908 if (validate_ports_csv(options
->RejectPlaintextPorts
,
2909 "RejectPlaintextPorts", msg
) < 0)
2912 if (validate_ports_csv(options
->WarnPlaintextPorts
,
2913 "WarnPlaintextPorts", msg
) < 0)
2916 if (options
->FascistFirewall
&& !options
->ReachableAddresses
) {
2917 if (options
->FirewallPorts
&& smartlist_len(options
->FirewallPorts
)) {
2918 /* We already have firewall ports set, so migrate them to
2919 * ReachableAddresses, which will set ReachableORAddresses and
2920 * ReachableDirAddresses if they aren't set explicitly. */
2921 smartlist_t
*instead
= smartlist_create();
2922 config_line_t
*new_line
= tor_malloc_zero(sizeof(config_line_t
));
2923 new_line
->key
= tor_strdup("ReachableAddresses");
2924 /* If we're configured with the old format, we need to prepend some
2926 SMARTLIST_FOREACH(options
->FirewallPorts
, const char *, portno
,
2928 int p
= atoi(portno
);
2932 tor_snprintf(s
, 16, "*:%d", p
);
2933 smartlist_add(instead
, s
);
2935 new_line
->value
= smartlist_join_strings(instead
,",",0,NULL
);
2936 /* These have been deprecated since 0.1.1.5-alpha-cvs */
2937 log(LOG_NOTICE
, LD_CONFIG
,
2938 "Converting FascistFirewall and FirewallPorts "
2939 "config options to new format: \"ReachableAddresses %s\"",
2941 options
->ReachableAddresses
= new_line
;
2942 SMARTLIST_FOREACH(instead
, char *, cp
, tor_free(cp
));
2943 smartlist_free(instead
);
2945 /* We do not have FirewallPorts set, so add 80 to
2946 * ReachableDirAddresses, and 443 to ReachableORAddresses. */
2947 if (!options
->ReachableDirAddresses
) {
2948 config_line_t
*new_line
= tor_malloc_zero(sizeof(config_line_t
));
2949 new_line
->key
= tor_strdup("ReachableDirAddresses");
2950 new_line
->value
= tor_strdup("*:80");
2951 options
->ReachableDirAddresses
= new_line
;
2952 log(LOG_NOTICE
, LD_CONFIG
, "Converting FascistFirewall config option "
2953 "to new format: \"ReachableDirAddresses *:80\"");
2955 if (!options
->ReachableORAddresses
) {
2956 config_line_t
*new_line
= tor_malloc_zero(sizeof(config_line_t
));
2957 new_line
->key
= tor_strdup("ReachableORAddresses");
2958 new_line
->value
= tor_strdup("*:443");
2959 options
->ReachableORAddresses
= new_line
;
2960 log(LOG_NOTICE
, LD_CONFIG
, "Converting FascistFirewall config option "
2961 "to new format: \"ReachableORAddresses *:443\"");
2966 for (i
=0; i
<3; i
++) {
2967 config_line_t
**linep
=
2968 (i
==0) ? &options
->ReachableAddresses
:
2969 (i
==1) ? &options
->ReachableORAddresses
:
2970 &options
->ReachableDirAddresses
;
2973 /* We need to end with a reject *:*, not an implicit accept *:* */
2975 if (!strcmp((*linep
)->value
, "reject *:*")) /* already there */
2977 linep
= &((*linep
)->next
);
2979 *linep
= tor_malloc_zero(sizeof(config_line_t
));
2980 (*linep
)->key
= tor_strdup(
2981 (i
==0) ? "ReachableAddresses" :
2982 (i
==1) ? "ReachableORAddresses" :
2983 "ReachableDirAddresses");
2984 (*linep
)->value
= tor_strdup("reject *:*");
2990 if ((options
->ReachableAddresses
||
2991 options
->ReachableORAddresses
||
2992 options
->ReachableDirAddresses
) &&
2993 server_mode(options
))
2994 REJECT("Servers must be able to freely connect to the rest "
2995 "of the Internet, so they must not set Reachable*Addresses "
2996 "or FascistFirewall.");
2998 if (options
->UseBridges
&&
2999 server_mode(options
))
3000 REJECT("Servers must be able to freely connect to the rest "
3001 "of the Internet, so they must not set UseBridges.");
3003 options
->_AllowInvalid
= 0;
3004 if (options
->AllowInvalidNodes
) {
3005 SMARTLIST_FOREACH(options
->AllowInvalidNodes
, const char *, cp
, {
3006 if (!strcasecmp(cp
, "entry"))
3007 options
->_AllowInvalid
|= ALLOW_INVALID_ENTRY
;
3008 else if (!strcasecmp(cp
, "exit"))
3009 options
->_AllowInvalid
|= ALLOW_INVALID_EXIT
;
3010 else if (!strcasecmp(cp
, "middle"))
3011 options
->_AllowInvalid
|= ALLOW_INVALID_MIDDLE
;
3012 else if (!strcasecmp(cp
, "introduction"))
3013 options
->_AllowInvalid
|= ALLOW_INVALID_INTRODUCTION
;
3014 else if (!strcasecmp(cp
, "rendezvous"))
3015 options
->_AllowInvalid
|= ALLOW_INVALID_RENDEZVOUS
;
3017 r
= tor_snprintf(buf
, sizeof(buf
),
3018 "Unrecognized value '%s' in AllowInvalidNodes", cp
);
3019 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
3025 if (compute_publishserverdescriptor(options
) < 0) {
3026 r
= tor_snprintf(buf
, sizeof(buf
),
3027 "Unrecognized value in PublishServerDescriptor");
3028 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
3032 if (options
->MinUptimeHidServDirectoryV2
< 0) {
3033 log_warn(LD_CONFIG
, "MinUptimeHidServDirectoryV2 option must be at "
3034 "least 0 seconds. Changing to 0.");
3035 options
->MinUptimeHidServDirectoryV2
= 0;
3038 if (options
->RendPostPeriod
< MIN_REND_POST_PERIOD
) {
3039 log(LOG_WARN
,LD_CONFIG
,"RendPostPeriod option must be at least %d seconds."
3040 " Clipping.", MIN_REND_POST_PERIOD
);
3041 options
->RendPostPeriod
= MIN_REND_POST_PERIOD
;
3044 if (options
->RendPostPeriod
> MAX_DIR_PERIOD
) {
3045 log(LOG_WARN
, LD_CONFIG
, "RendPostPeriod is too large; clipping to %ds.",
3047 options
->RendPostPeriod
= MAX_DIR_PERIOD
;
3050 if (options
->KeepalivePeriod
< 1)
3051 REJECT("KeepalivePeriod option must be positive.");
3053 if (ensure_bandwidth_cap(&options
->BandwidthRate
,
3054 "BandwidthRate", msg
) < 0)
3056 if (ensure_bandwidth_cap(&options
->BandwidthBurst
,
3057 "BandwidthBurst", msg
) < 0)
3059 if (ensure_bandwidth_cap(&options
->MaxAdvertisedBandwidth
,
3060 "MaxAdvertisedBandwidth", msg
) < 0)
3062 if (ensure_bandwidth_cap(&options
->RelayBandwidthRate
,
3063 "RelayBandwidthRate", msg
) < 0)
3065 if (ensure_bandwidth_cap(&options
->RelayBandwidthBurst
,
3066 "RelayBandwidthBurst", msg
) < 0)
3069 if (server_mode(options
)) {
3070 if (options
->BandwidthRate
< ROUTER_REQUIRED_MIN_BANDWIDTH
*2) {
3071 r
= tor_snprintf(buf
, sizeof(buf
),
3072 "BandwidthRate is set to %d bytes/second. "
3073 "For servers, it must be at least %d.",
3074 (int)options
->BandwidthRate
,
3075 ROUTER_REQUIRED_MIN_BANDWIDTH
*2);
3076 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
3078 } else if (options
->MaxAdvertisedBandwidth
<
3079 ROUTER_REQUIRED_MIN_BANDWIDTH
) {
3080 r
= tor_snprintf(buf
, sizeof(buf
),
3081 "MaxAdvertisedBandwidth is set to %d bytes/second. "
3082 "For servers, it must be at least %d.",
3083 (int)options
->MaxAdvertisedBandwidth
,
3084 ROUTER_REQUIRED_MIN_BANDWIDTH
);
3085 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
3088 if (options
->RelayBandwidthRate
&&
3089 options
->RelayBandwidthRate
< ROUTER_REQUIRED_MIN_BANDWIDTH
) {
3090 r
= tor_snprintf(buf
, sizeof(buf
),
3091 "RelayBandwidthRate is set to %d bytes/second. "
3092 "For servers, it must be at least %d.",
3093 (int)options
->RelayBandwidthRate
,
3094 ROUTER_REQUIRED_MIN_BANDWIDTH
);
3095 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
3100 if (options
->RelayBandwidthRate
&& !options
->RelayBandwidthBurst
)
3101 options
->RelayBandwidthBurst
= options
->RelayBandwidthRate
;
3103 if (options
->RelayBandwidthRate
> options
->RelayBandwidthBurst
)
3104 REJECT("RelayBandwidthBurst must be at least equal "
3105 "to RelayBandwidthRate.");
3107 if (options
->BandwidthRate
> options
->BandwidthBurst
)
3108 REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
3110 if (accounting_parse_options(options
, 1)<0)
3111 REJECT("Failed to parse accounting options. See logs for details.");
3113 if (options
->HttpProxy
) { /* parse it now */
3114 if (parse_addr_port(LOG_WARN
, options
->HttpProxy
, NULL
,
3115 &options
->HttpProxyAddr
, &options
->HttpProxyPort
) < 0)
3116 REJECT("HttpProxy failed to parse or resolve. Please fix.");
3117 if (options
->HttpProxyPort
== 0) { /* give it a default */
3118 options
->HttpProxyPort
= 80;
3122 if (options
->HttpProxyAuthenticator
) {
3123 if (strlen(options
->HttpProxyAuthenticator
) >= 48)
3124 REJECT("HttpProxyAuthenticator is too long (>= 48 chars).");
3127 if (options
->HttpsProxy
) { /* parse it now */
3128 if (parse_addr_port(LOG_WARN
, options
->HttpsProxy
, NULL
,
3129 &options
->HttpsProxyAddr
, &options
->HttpsProxyPort
) <0)
3130 REJECT("HttpsProxy failed to parse or resolve. Please fix.");
3131 if (options
->HttpsProxyPort
== 0) { /* give it a default */
3132 options
->HttpsProxyPort
= 443;
3136 if (options
->HttpsProxyAuthenticator
) {
3137 if (strlen(options
->HttpsProxyAuthenticator
) >= 48)
3138 REJECT("HttpsProxyAuthenticator is too long (>= 48 chars).");
3141 if (options
->HashedControlPassword
) {
3142 smartlist_t
*sl
= decode_hashed_passwords(options
->HashedControlPassword
);
3144 REJECT("Bad HashedControlPassword: wrong length or bad encoding");
3146 SMARTLIST_FOREACH(sl
, char*, cp
, tor_free(cp
));
3151 if (options
->ControlListenAddress
) {
3152 int all_are_local
= 1;
3154 for (ln
= options
->ControlListenAddress
; ln
; ln
= ln
->next
) {
3155 if (strcmpstart(ln
->value
, "127."))
3158 if (!all_are_local
) {
3159 if (!options
->HashedControlPassword
&& !options
->CookieAuthentication
) {
3160 log_warn(LD_CONFIG
, "You have a ControlListenAddress set to accept "
3161 "connections from a non-local address. This means that "
3162 "any program on the internet can reconfigure your Tor. "
3163 "That's so bad that I'm closing your ControlPort for you.");
3164 options
->ControlPort
= 0;
3166 log_warn(LD_CONFIG
, "You have a ControlListenAddress set to accept "
3167 "connections from a non-local address. This means that "
3168 "programs not running on your computer can reconfigure your "
3169 "Tor. That's pretty bad!");
3174 if (options
->ControlPort
&& !options
->HashedControlPassword
&&
3175 !options
->CookieAuthentication
) {
3176 log_warn(LD_CONFIG
, "ControlPort is open, but no authentication method "
3177 "has been configured. This means that any program on your "
3178 "computer can reconfigure your Tor. That's bad! You should "
3179 "upgrade your Tor controller as soon as possible.");
3182 if (options
->UseEntryGuards
&& ! options
->NumEntryGuards
)
3183 REJECT("Cannot enable UseEntryGuards with NumEntryGuards set to 0");
3185 if (check_nickname_list(options
->ExitNodes
, "ExitNodes", msg
))
3187 if (check_nickname_list(options
->EntryNodes
, "EntryNodes", msg
))
3189 if (check_nickname_list(options
->ExcludeNodes
, "ExcludeNodes", msg
))
3191 if (check_nickname_list(options
->RendNodes
, "RendNodes", msg
))
3193 if (check_nickname_list(options
->RendNodes
, "RendExcludeNodes", msg
))
3195 if (check_nickname_list(options
->TestVia
, "TestVia", msg
))
3197 if (check_nickname_list(options
->MyFamily
, "MyFamily", msg
))
3199 for (cl
= options
->NodeFamilies
; cl
; cl
= cl
->next
) {
3200 if (check_nickname_list(cl
->value
, "NodeFamily", msg
))
3204 if (validate_addr_policies(options
, msg
) < 0)
3207 for (cl
= options
->RedirectExit
; cl
; cl
= cl
->next
) {
3208 if (parse_redirect_line(NULL
, cl
, msg
)<0)
3212 if (validate_dir_authorities(options
, old_options
) < 0)
3213 REJECT("Directory authority line did not parse. See logs for details.");
3215 if (options
->UseBridges
&& !options
->Bridges
)
3216 REJECT("If you set UseBridges, you must specify at least one bridge.");
3217 if (options
->UseBridges
&& !options
->TunnelDirConns
)
3218 REJECT("If you set UseBridges, you must set TunnelDirConns.");
3219 if (options
->Bridges
) {
3220 for (cl
= options
->Bridges
; cl
; cl
= cl
->next
) {
3221 if (parse_bridge_line(cl
->value
, 1)<0)
3222 REJECT("Bridge line did not parse. See logs for details.");
3226 if (options
->ConstrainedSockets
) {
3227 /* If the user wants to constrain socket buffer use, make sure the desired
3228 * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
3229 if (options
->ConstrainedSockSize
< MIN_CONSTRAINED_TCP_BUFFER
||
3230 options
->ConstrainedSockSize
> MAX_CONSTRAINED_TCP_BUFFER
||
3231 options
->ConstrainedSockSize
% 1024) {
3232 r
= tor_snprintf(buf
, sizeof(buf
),
3233 "ConstrainedSockSize is invalid. Must be a value between %d and %d "
3234 "in 1024 byte increments.",
3235 MIN_CONSTRAINED_TCP_BUFFER
, MAX_CONSTRAINED_TCP_BUFFER
);
3236 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
3239 if (options
->DirPort
) {
3240 /* Providing cached directory entries while system TCP buffers are scarce
3241 * will exacerbate the socket errors. Suggest that this be disabled. */
3242 COMPLAIN("You have requested constrained socket buffers while also "
3243 "serving directory entries via DirPort. It is strongly "
3244 "suggested that you disable serving directory requests when "
3245 "system TCP buffer resources are scarce.");
3249 if (options
->V3AuthVoteDelay
+ options
->V3AuthDistDelay
>=
3250 options
->V3AuthVotingInterval
/2) {
3251 REJECT("V3AuthVoteDelay and V3AuthDistDelay must be no more than half "
3252 "V3AuthVotingInterval");
3254 if (options
->V3AuthVoteDelay
< MIN_VOTE_SECONDS
)
3255 REJECT("V3AuthVoteDelay is way too low.");
3256 if (options
->V3AuthDistDelay
< MIN_DIST_SECONDS
)
3257 REJECT("V3AuthDistDelay is way too low.");
3259 if (options
->V3AuthNIntervalsValid
< 2)
3260 REJECT("V3AuthNIntervalsValid must be at least 2.");
3262 if (options
->V3AuthVotingInterval
< MIN_VOTE_INTERVAL
) {
3263 REJECT("V3AuthVotingInterval is insanely low.");
3264 } else if (options
->V3AuthVotingInterval
> 24*60*60) {
3265 REJECT("V3AuthVotingInterval is insanely high.");
3266 } else if (((24*60*60) % options
->V3AuthVotingInterval
) != 0) {
3267 COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
3270 if (rend_config_services(options
, 1) < 0)
3271 REJECT("Failed to configure rendezvous options. See logs for details.");
3273 if (parse_virtual_addr_network(options
->VirtualAddrNetwork
, 1, NULL
)<0)
3276 if (options
->PreferTunneledDirConns
&& !options
->TunnelDirConns
)
3277 REJECT("Must set TunnelDirConns if PreferTunneledDirConns is set.");
3279 if (options
->AutomapHostsSuffixes
) {
3280 SMARTLIST_FOREACH(options
->AutomapHostsSuffixes
, char *, suf
,
3282 size_t len
= strlen(suf
);
3283 if (len
&& suf
[len
-1] == '.')
3293 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
3296 opt_streq(const char *s1
, const char *s2
)
3300 else if (s1
&& s2
&& !strcmp(s1
,s2
))
3306 /** Check if any of the previous options have changed but aren't allowed to. */
3308 options_transition_allowed(or_options_t
*old
, or_options_t
*new_val
,
3314 if (!opt_streq(old
->PidFile
, new_val
->PidFile
)) {
3315 *msg
= tor_strdup("PidFile is not allowed to change.");
3319 if (old
->RunAsDaemon
!= new_val
->RunAsDaemon
) {
3320 *msg
= tor_strdup("While Tor is running, changing RunAsDaemon "
3325 if (strcmp(old
->DataDirectory
,new_val
->DataDirectory
)!=0) {
3327 int r
= tor_snprintf(buf
, sizeof(buf
),
3328 "While Tor is running, changing DataDirectory "
3329 "(\"%s\"->\"%s\") is not allowed.",
3330 old
->DataDirectory
, new_val
->DataDirectory
);
3331 *msg
= tor_strdup(r
>= 0 ? buf
: "internal error");
3335 if (!opt_streq(old
->User
, new_val
->User
)) {
3336 *msg
= tor_strdup("While Tor is running, changing User is not allowed.");
3340 if (!opt_streq(old
->Group
, new_val
->Group
)) {
3341 *msg
= tor_strdup("While Tor is running, changing Group is not allowed.");
3345 if (old
->HardwareAccel
!= new_val
->HardwareAccel
) {
3346 *msg
= tor_strdup("While Tor is running, changing HardwareAccel is "
3354 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3355 * will require us to rotate the cpu and dns workers; else return 0. */
3357 options_transition_affects_workers(or_options_t
*old_options
,
3358 or_options_t
*new_options
)
3360 if (!opt_streq(old_options
->DataDirectory
, new_options
->DataDirectory
) ||
3361 old_options
->NumCpus
!= new_options
->NumCpus
||
3362 old_options
->ORPort
!= new_options
->ORPort
||
3363 old_options
->ServerDNSSearchDomains
!=
3364 new_options
->ServerDNSSearchDomains
||
3365 old_options
->SafeLogging
!= new_options
->SafeLogging
||
3366 old_options
->ClientOnly
!= new_options
->ClientOnly
||
3367 !config_lines_eq(old_options
->Logs
, new_options
->Logs
))
3370 /* Check whether log options match. */
3372 /* Nothing that changed matters. */
3376 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3377 * will require us to generate a new descriptor; else return 0. */
3379 options_transition_affects_descriptor(or_options_t
*old_options
,
3380 or_options_t
*new_options
)
3382 if (!opt_streq(old_options
->DataDirectory
, new_options
->DataDirectory
) ||
3383 !opt_streq(old_options
->Nickname
,new_options
->Nickname
) ||
3384 !opt_streq(old_options
->Address
,new_options
->Address
) ||
3385 !config_lines_eq(old_options
->ExitPolicy
,new_options
->ExitPolicy
) ||
3386 old_options
->ExitPolicyRejectPrivate
!=
3387 new_options
->ExitPolicyRejectPrivate
||
3388 old_options
->ORPort
!= new_options
->ORPort
||
3389 old_options
->DirPort
!= new_options
->DirPort
||
3390 old_options
->ClientOnly
!= new_options
->ClientOnly
||
3391 old_options
->NoPublish
!= new_options
->NoPublish
||
3392 old_options
->_PublishServerDescriptor
!=
3393 new_options
->_PublishServerDescriptor
||
3394 old_options
->BandwidthRate
!= new_options
->BandwidthRate
||
3395 old_options
->BandwidthBurst
!= new_options
->BandwidthBurst
||
3396 !opt_streq(old_options
->ContactInfo
, new_options
->ContactInfo
) ||
3397 !opt_streq(old_options
->MyFamily
, new_options
->MyFamily
) ||
3398 !opt_streq(old_options
->AccountingStart
, new_options
->AccountingStart
) ||
3399 old_options
->AccountingMax
!= new_options
->AccountingMax
)
3406 /** Return the directory on windows where we expect to find our application
3409 get_windows_conf_root(void)
3411 static int is_set
= 0;
3412 static char path
[MAX_PATH
+1];
3421 /* Find X:\documents and settings\username\application data\ .
3422 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
3424 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL
, CSIDL_APPDATA
,
3426 GetCurrentDirectory(MAX_PATH
, path
);
3429 "I couldn't find your application data folder: are you "
3430 "running an ancient version of Windows 95? Defaulting to \"%s\"",
3434 /* Convert the path from an "ID List" (whatever that is!) to a path. */
3435 result
= SHGetPathFromIDList(idl
, path
);
3436 /* Now we need to free the */
3439 m
->lpVtbl
->Free(m
, idl
);
3440 m
->lpVtbl
->Release(m
);
3442 if (!SUCCEEDED(result
)) {
3445 strlcat(path
,"\\tor",MAX_PATH
);
3451 /** Return the default location for our torrc file. */
3453 get_default_conf_file(void)
3456 static char path
[MAX_PATH
+1];
3457 strlcpy(path
, get_windows_conf_root(), MAX_PATH
);
3458 strlcat(path
,"\\torrc",MAX_PATH
);
3461 return (CONFDIR
"/torrc");
3465 /** Verify whether lst is a string containing valid-looking space-separated
3466 * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
3469 check_nickname_list(const char *lst
, const char *name
, char **msg
)
3476 sl
= smartlist_create();
3477 smartlist_split_string(sl
, lst
, ",", SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
3478 SMARTLIST_FOREACH(sl
, const char *, s
,
3480 if (!is_legal_nickname_or_hexdigest(s
)) {
3482 int tmp
= tor_snprintf(buf
, sizeof(buf
),
3483 "Invalid nickname '%s' in %s line", s
, name
);
3484 *msg
= tor_strdup(tmp
>= 0 ? buf
: "internal error");
3489 SMARTLIST_FOREACH(sl
, char *, s
, tor_free(s
));
3494 /** Read a configuration file into <b>options</b>, finding the configuration
3495 * file location based on the command line. After loading the options,
3496 * validate them for consistency, then take actions based on them.
3497 * Return 0 if success, -1 if failure. */
3499 options_init_from_torrc(int argc
, char **argv
)
3501 or_options_t
*oldoptions
, *newoptions
;
3503 char *cf
=NULL
, *fname
=NULL
, *errmsg
=NULL
;
3505 int using_default_torrc
;
3506 int ignore_missing_torrc
;
3507 static char **backup_argv
;
3508 static int backup_argc
;
3510 if (argv
) { /* first time we're called. save commandline args */
3514 } else { /* we're reloading. need to clean up old options first. */
3517 oldoptions
= get_options();
3519 if (argc
> 1 && (!strcmp(argv
[1], "-h") || !strcmp(argv
[1],"--help"))) {
3523 if (argc
> 1 && !strcmp(argv
[1], "--list-torrc-options")) {
3524 /* For documenting validating whether we've documented everything. */
3525 list_torrc_options();
3529 if (argc
> 1 && (!strcmp(argv
[1],"--version"))) {
3530 printf("Tor version %s.\n",get_version());
3531 if (argc
> 2 && (!strcmp(argv
[2],"--version"))) {
3532 print_svn_version();
3537 newoptions
= tor_malloc_zero(sizeof(or_options_t
));
3538 newoptions
->_magic
= OR_OPTIONS_MAGIC
;
3539 options_init(newoptions
);
3541 /* learn config file name */
3543 using_default_torrc
= 1;
3544 ignore_missing_torrc
= 0;
3545 newoptions
->command
= CMD_RUN_TOR
;
3546 for (i
= 1; i
< argc
; ++i
) {
3547 if (i
< argc
-1 && !strcmp(argv
[i
],"-f")) {
3549 log(LOG_WARN
, LD_CONFIG
, "Duplicate -f options on command line.");
3553 /* XXX one day we might want to extend expand_filename to work
3554 * under Windows as well. */
3555 fname
= tor_strdup(argv
[i
+1]);
3557 fname
= expand_filename(argv
[i
+1]);
3559 using_default_torrc
= 0;
3561 } else if (!strcmp(argv
[i
],"--ignore-missing-torrc")) {
3562 ignore_missing_torrc
= 1;
3563 } else if (!strcmp(argv
[i
],"--list-fingerprint")) {
3564 newoptions
->command
= CMD_LIST_FINGERPRINT
;
3565 } else if (!strcmp(argv
[i
],"--hash-password")) {
3566 newoptions
->command
= CMD_HASH_PASSWORD
;
3567 newoptions
->command_arg
= tor_strdup( (i
< argc
-1) ? argv
[i
+1] : "");
3569 } else if (!strcmp(argv
[i
],"--verify-config")) {
3570 newoptions
->command
= CMD_VERIFY_CONFIG
;
3573 if (using_default_torrc
) {
3574 /* didn't find one, try CONFDIR */
3575 const char *dflt
= get_default_conf_file();
3576 if (dflt
&& file_status(dflt
) == FN_FILE
) {
3577 fname
= tor_strdup(dflt
);
3581 fn
= expand_filename("~/.torrc");
3582 if (fn
&& file_status(fn
) == FN_FILE
) {
3586 fname
= tor_strdup(dflt
);
3589 fname
= tor_strdup(dflt
);
3594 log(LOG_DEBUG
, LD_CONFIG
, "Opening config file \"%s\"", fname
);
3596 tor_free(torrc_fname
);
3597 torrc_fname
= fname
;
3599 /* get config lines, assign them */
3600 if (file_status(fname
) != FN_FILE
||
3601 !(cf
= read_file_to_str(fname
,0,NULL
))) {
3602 if (using_default_torrc
== 1 || ignore_missing_torrc
) {
3603 log(LOG_NOTICE
, LD_CONFIG
, "Configuration file \"%s\" not present, "
3604 "using reasonable defaults.", fname
);
3605 tor_free(fname
); /* sets fname to NULL */
3608 log(LOG_WARN
, LD_CONFIG
,
3609 "Unable to open configuration file \"%s\".", fname
);
3612 } else { /* it opened successfully. use it. */
3613 retval
= config_get_lines(cf
, &cl
);
3617 retval
= config_assign(&options_format
, newoptions
, cl
, 0, 0, &errmsg
);
3618 config_free_lines(cl
);
3623 /* Go through command-line variables too */
3624 if (config_get_commandlines(argc
, argv
, &cl
) < 0)
3626 retval
= config_assign(&options_format
, newoptions
, cl
, 0, 0, &errmsg
);
3627 config_free_lines(cl
);
3631 /* Validate newoptions */
3632 if (options_validate(oldoptions
, newoptions
, 0, &errmsg
) < 0)
3635 if (options_transition_allowed(oldoptions
, newoptions
, &errmsg
) < 0)
3638 if (set_options(newoptions
, &errmsg
))
3639 goto err
; /* frees and replaces old options */
3645 config_free(&options_format
, newoptions
);
3647 log(LOG_WARN
,LD_CONFIG
,"Failed to parse/validate config: %s", errmsg
);
3653 /** Return the location for our configuration file.
3656 get_torrc_fname(void)
3661 return get_default_conf_file();
3664 /** Adjust the address map mased on the MapAddress elements in the
3665 * configuration <b>options</b>
3668 config_register_addressmaps(or_options_t
*options
)
3674 addressmap_clear_configured();
3675 elts
= smartlist_create();
3676 for (opt
= options
->AddressMap
; opt
; opt
= opt
->next
) {
3677 smartlist_split_string(elts
, opt
->value
, NULL
,
3678 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 2);
3679 if (smartlist_len(elts
) >= 2) {
3680 from
= smartlist_get(elts
,0);
3681 to
= smartlist_get(elts
,1);
3682 if (address_is_invalid_destination(to
, 1)) {
3684 "Skipping invalid argument '%s' to MapAddress", to
);
3686 addressmap_register(from
, tor_strdup(to
), 0);
3687 if (smartlist_len(elts
)>2) {
3688 log_warn(LD_CONFIG
,"Ignoring extra arguments to MapAddress.");
3692 log_warn(LD_CONFIG
,"MapAddress '%s' has too few arguments. Ignoring.",
3695 SMARTLIST_FOREACH(elts
, char*, cp
, tor_free(cp
));
3696 smartlist_clear(elts
);
3698 smartlist_free(elts
);
3701 /** If <b>range</b> is of the form MIN-MAX, for MIN and MAX both
3702 * recognized log severity levels, set *<b>min_out</b> to MIN and
3703 * *<b>max_out</b> to MAX and return 0. Else, if <b>range</b> is of
3704 * the form MIN, act as if MIN-err had been specified. Else, warn and
3708 parse_log_severity_range(const char *range
, int *min_out
, int *max_out
)
3710 int levelMin
, levelMax
;
3712 cp
= strchr(range
, '-');
3715 levelMin
= LOG_DEBUG
;
3717 char *tmp_sev
= tor_strndup(range
, cp
- range
);
3718 levelMin
= parse_log_level(tmp_sev
);
3720 log_warn(LD_CONFIG
, "Unrecognized minimum log severity '%s': must be "
3721 "one of err|warn|notice|info|debug", tmp_sev
);
3730 levelMax
= parse_log_level(cp
+1);
3732 log_warn(LD_CONFIG
, "Unrecognized maximum log severity '%s': must be "
3733 "one of err|warn|notice|info|debug", cp
+1);
3738 levelMin
= parse_log_level(range
);
3740 log_warn(LD_CONFIG
, "Unrecognized log severity '%s': must be one of "
3741 "err|warn|notice|info|debug", range
);
3747 *min_out
= levelMin
;
3748 *max_out
= levelMax
;
3754 * Initialize the logs based on the configuration file.
3757 options_init_logs(or_options_t
*options
, int validate_only
)
3766 options
->RunAsDaemon
;
3770 elts
= smartlist_create();
3772 for (opt
= options
->Logs
; opt
; opt
= opt
->next
) {
3773 int levelMin
=LOG_DEBUG
, levelMax
=LOG_ERR
;
3774 smartlist_split_string(elts
, opt
->value
, NULL
,
3775 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 3);
3776 if (smartlist_len(elts
) == 0) {
3777 log_warn(LD_CONFIG
, "No arguments to Log option 'Log %s'", opt
->value
);
3778 ok
= 0; goto cleanup
;
3780 if (parse_log_severity_range(smartlist_get(elts
,0), &levelMin
,
3782 ok
= 0; goto cleanup
;
3784 if (smartlist_len(elts
) < 2) { /* only loglevels were provided */
3785 if (!validate_only
) {
3788 "Can't log to stdout with RunAsDaemon set; skipping stdout");
3790 add_stream_log(levelMin
, levelMax
, "<stdout>", stdout
);
3795 if (!strcasecmp(smartlist_get(elts
,1), "file")) {
3796 if (smartlist_len(elts
) != 3) {
3797 log_warn(LD_CONFIG
, "Bad syntax on file Log option 'Log %s'",
3799 ok
= 0; goto cleanup
;
3801 if (!validate_only
) {
3802 if (add_file_log(levelMin
, levelMax
, smartlist_get(elts
, 2)) < 0) {
3803 log_warn(LD_CONFIG
, "Couldn't open file for 'Log %s'", opt
->value
);
3809 if (smartlist_len(elts
) != 2) {
3810 log_warn(LD_CONFIG
, "Wrong number of arguments on Log option 'Log %s'",
3812 ok
= 0; goto cleanup
;
3814 if (!strcasecmp(smartlist_get(elts
,1), "stdout")) {
3816 log_warn(LD_CONFIG
, "Can't log to stdout with RunAsDaemon set.");
3817 ok
= 0; goto cleanup
;
3819 if (!validate_only
) {
3820 add_stream_log(levelMin
, levelMax
, "<stdout>", stdout
);
3822 } else if (!strcasecmp(smartlist_get(elts
,1), "stderr")) {
3824 log_warn(LD_CONFIG
, "Can't log to stderr with RunAsDaemon set.");
3825 ok
= 0; goto cleanup
;
3827 if (!validate_only
) {
3828 add_stream_log(levelMin
, levelMax
, "<stderr>", stderr
);
3830 } else if (!strcasecmp(smartlist_get(elts
,1), "syslog")) {
3831 #ifdef HAVE_SYSLOG_H
3833 add_syslog_log(levelMin
, levelMax
);
3835 log_warn(LD_CONFIG
, "Syslog is not supported on this system. Sorry.");
3838 log_warn(LD_CONFIG
, "Unrecognized log type %s",
3839 (const char*)smartlist_get(elts
,1));
3840 if (strchr(smartlist_get(elts
,1), '/') ||
3841 strchr(smartlist_get(elts
,1), '\\')) {
3842 log_warn(LD_CONFIG
, "Did you mean to say 'Log %s file %s' ?",
3843 (const char *)smartlist_get(elts
,0),
3844 (const char *)smartlist_get(elts
,1));
3846 ok
= 0; goto cleanup
;
3849 SMARTLIST_FOREACH(elts
, char*, cp
, tor_free(cp
));
3850 smartlist_clear(elts
);
3852 smartlist_free(elts
);
3857 /** Parse a single RedirectExit line's contents from <b>line</b>. If
3858 * they are valid, and <b>result</b> is not NULL, add an element to
3859 * <b>result</b> and return 0. Else if they are valid, return 0.
3860 * Else set *msg and return -1. */
3862 parse_redirect_line(smartlist_t
*result
, config_line_t
*line
, char **msg
)
3864 smartlist_t
*elements
= NULL
;
3869 r
= tor_malloc_zero(sizeof(exit_redirect_t
));
3870 elements
= smartlist_create();
3871 smartlist_split_string(elements
, line
->value
, NULL
,
3872 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
3873 if (smartlist_len(elements
) != 2) {
3874 *msg
= tor_strdup("Wrong number of elements in RedirectExit line");
3877 if (parse_addr_and_port_range(smartlist_get(elements
,0),&r
->addr
,
3878 &r
->maskbits
,&r
->port_min
,&r
->port_max
)) {
3879 *msg
= tor_strdup("Error parsing source address in RedirectExit line");
3882 if (0==strcasecmp(smartlist_get(elements
,1), "pass")) {
3885 if (parse_addr_port(LOG_WARN
, smartlist_get(elements
,1),NULL
,
3886 &r
->addr_dest
, &r
->port_dest
)) {
3887 *msg
= tor_strdup("Error parsing dest address in RedirectExit line");
3897 SMARTLIST_FOREACH(elements
, char *, cp
, tor_free(cp
));
3898 smartlist_free(elements
);
3901 smartlist_add(result
, r
);
3911 /** Read the contents of a Bridge line from <b>line</b>. Return 0
3912 * if the line is well-formed, and -1 if it isn't. If
3913 * <b>validate_only</b> is 0, and the line is well-formed, then add
3914 * the bridge described in the line to our internal bridge list. */
3916 parse_bridge_line(const char *line
, int validate_only
)
3918 smartlist_t
*items
= NULL
;
3920 char *addrport
=NULL
, *address
=NULL
, *fingerprint
=NULL
;
3923 char digest
[DIGEST_LEN
];
3925 items
= smartlist_create();
3926 smartlist_split_string(items
, line
, NULL
,
3927 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, -1);
3928 if (smartlist_len(items
) < 1) {
3929 log_warn(LD_CONFIG
, "Too few arguments to Bridge line.");
3932 addrport
= smartlist_get(items
, 0);
3933 smartlist_del_keeporder(items
, 0);
3934 if (parse_addr_port(LOG_WARN
, addrport
, &address
, &addr
, &port
)<0) {
3935 log_warn(LD_CONFIG
, "Error parsing Bridge address '%s'", addrport
);
3939 log_warn(LD_CONFIG
, "Missing port in Bridge address '%s'",addrport
);
3943 if (smartlist_len(items
)) {
3944 fingerprint
= smartlist_join_strings(items
, "", 0, NULL
);
3945 if (strlen(fingerprint
) != HEX_DIGEST_LEN
) {
3946 log_warn(LD_CONFIG
, "Key digest for Bridge is wrong length.");
3949 if (base16_decode(digest
, DIGEST_LEN
, fingerprint
, HEX_DIGEST_LEN
)<0) {
3950 log_warn(LD_CONFIG
, "Unable to decode Bridge key digest.");
3955 if (!validate_only
) {
3956 log_debug(LD_DIR
, "Bridge at %s:%d (%s)", address
,
3958 fingerprint
? fingerprint
: "no key listed");
3959 bridge_add_from_config(addr
, port
, fingerprint
? digest
: NULL
);
3969 SMARTLIST_FOREACH(items
, char*, s
, tor_free(s
));
3970 smartlist_free(items
);
3973 tor_free(fingerprint
);
3977 /** Read the contents of a DirServer line from <b>line</b>. If
3978 * <b>validate_only</b> is 0, and the line is well-formed, and it
3979 * shares any bits with <b>required_type</b> or <b>required_type</b>
3980 * is 0, then add the dirserver described in the line (minus whatever
3981 * bits it's missing) as a valid authority. Return 0 on success,
3982 * or -1 if the line isn't well-formed or if we can't add it. */
3984 parse_dir_server_line(const char *line
, authority_type_t required_type
,
3987 smartlist_t
*items
= NULL
;
3989 char *addrport
=NULL
, *address
=NULL
, *nickname
=NULL
, *fingerprint
=NULL
;
3990 uint16_t dir_port
= 0, or_port
= 0;
3991 char digest
[DIGEST_LEN
];
3992 char v3_digest
[DIGEST_LEN
];
3993 authority_type_t type
= V2_AUTHORITY
;
3994 int is_not_hidserv_authority
= 0, is_not_v2_authority
= 0;
3996 items
= smartlist_create();
3997 smartlist_split_string(items
, line
, NULL
,
3998 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, -1);
3999 if (smartlist_len(items
) < 1) {
4000 log_warn(LD_CONFIG
, "No arguments on DirServer line.");
4004 if (is_legal_nickname(smartlist_get(items
, 0))) {
4005 nickname
= smartlist_get(items
, 0);
4006 smartlist_del_keeporder(items
, 0);
4009 while (smartlist_len(items
)) {
4010 char *flag
= smartlist_get(items
, 0);
4011 if (TOR_ISDIGIT(flag
[0]))
4013 if (!strcasecmp(flag
, "v1")) {
4014 type
|= (V1_AUTHORITY
| HIDSERV_AUTHORITY
);
4015 } else if (!strcasecmp(flag
, "hs")) {
4016 type
|= HIDSERV_AUTHORITY
;
4017 } else if (!strcasecmp(flag
, "no-hs")) {
4018 is_not_hidserv_authority
= 1;
4019 } else if (!strcasecmp(flag
, "bridge")) {
4020 type
|= BRIDGE_AUTHORITY
;
4021 } else if (!strcasecmp(flag
, "no-v2")) {
4022 is_not_v2_authority
= 1;
4023 } else if (!strcasecmpstart(flag
, "orport=")) {
4025 char *portstring
= flag
+ strlen("orport=");
4026 or_port
= (uint16_t) tor_parse_long(portstring
, 10, 1, 65535, &ok
, NULL
);
4028 log_warn(LD_CONFIG
, "Invalid orport '%s' on DirServer line.",
4030 } else if (!strcasecmpstart(flag
, "v3ident=")) {
4031 char *idstr
= flag
+ strlen("v3ident=");
4032 if (strlen(idstr
) != HEX_DIGEST_LEN
||
4033 base16_decode(v3_digest
, DIGEST_LEN
, idstr
, HEX_DIGEST_LEN
)<0) {
4034 log_warn(LD_CONFIG
, "Bad v3 identity digest '%s' on DirServer line",
4037 type
|= V3_AUTHORITY
;
4040 log_warn(LD_CONFIG
, "Unrecognized flag '%s' on DirServer line",
4044 smartlist_del_keeporder(items
, 0);
4046 if (is_not_hidserv_authority
)
4047 type
&= ~HIDSERV_AUTHORITY
;
4048 if (is_not_v2_authority
)
4049 type
&= ~V2_AUTHORITY
;
4051 if (smartlist_len(items
) < 2) {
4052 log_warn(LD_CONFIG
, "Too few arguments to DirServer line.");
4055 addrport
= smartlist_get(items
, 0);
4056 smartlist_del_keeporder(items
, 0);
4057 if (parse_addr_port(LOG_WARN
, addrport
, &address
, NULL
, &dir_port
)<0) {
4058 log_warn(LD_CONFIG
, "Error parsing DirServer address '%s'", addrport
);
4062 log_warn(LD_CONFIG
, "Missing port in DirServer address '%s'",addrport
);
4066 fingerprint
= smartlist_join_strings(items
, "", 0, NULL
);
4067 if (strlen(fingerprint
) != HEX_DIGEST_LEN
) {
4068 log_warn(LD_CONFIG
, "Key digest for DirServer is wrong length %d.",
4069 (int)strlen(fingerprint
));
4072 if (!strcmp(fingerprint
, "E623F7625FBE0C87820F11EC5F6D5377ED816294")) {
4073 /* a known bad fingerprint. refuse to use it. We can remove this
4074 * clause once Tor 0.1.2.17 is obsolete. */
4075 log_warn(LD_CONFIG
, "Dangerous dirserver line. To correct, erase your "
4076 "torrc file (%s), or reinstall Tor and use the default torrc.",
4080 if (base16_decode(digest
, DIGEST_LEN
, fingerprint
, HEX_DIGEST_LEN
)<0) {
4081 log_warn(LD_CONFIG
, "Unable to decode DirServer key digest.");
4085 if (!validate_only
&& (!required_type
|| required_type
& type
)) {
4087 type
&= required_type
; /* pare down what we think of them as an
4089 log_debug(LD_DIR
, "Trusted %d dirserver at %s:%d (%s)", (int)type
,
4090 address
, (int)dir_port
, (char*)smartlist_get(items
,0));
4091 if (!add_trusted_dir_server(nickname
, address
, dir_port
, or_port
,
4092 digest
, v3_digest
, type
))
4103 SMARTLIST_FOREACH(items
, char*, s
, tor_free(s
));
4104 smartlist_free(items
);
4108 tor_free(fingerprint
);
4112 /** Adjust the value of options->DataDirectory, or fill it in if it's
4113 * absent. Return 0 on success, -1 on failure. */
4115 normalize_data_directory(or_options_t
*options
)
4119 if (options
->DataDirectory
)
4120 return 0; /* all set */
4121 p
= tor_malloc(MAX_PATH
);
4122 strlcpy(p
,get_windows_conf_root(),MAX_PATH
);
4123 options
->DataDirectory
= p
;
4126 const char *d
= options
->DataDirectory
;
4130 if (strncmp(d
,"~/",2) == 0) {
4131 char *fn
= expand_filename(d
);
4133 log_warn(LD_CONFIG
,"Failed to expand filename \"%s\".", d
);
4136 if (!options
->DataDirectory
&& !strcmp(fn
,"/.tor")) {
4137 /* If our homedir is /, we probably don't want to use it. */
4138 /* Default to LOCALSTATEDIR/tor which is probably closer to what we
4141 "Default DataDirectory is \"~/.tor\". This expands to "
4142 "\"%s\", which is probably not what you want. Using "
4143 "\"%s"PATH_SEPARATOR
"tor\" instead
", fn, LOCALSTATEDIR);
4145 fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor
");
4147 tor_free(options->DataDirectory);
4148 options->DataDirectory = fn;
4154 /** Check and normalize the value of options->DataDirectory; return 0 if it
4155 * sane, -1 otherwise. */
4157 validate_data_directory(or_options_t *options)
4159 if (normalize_data_directory(options) < 0)
4161 tor_assert(options->DataDirectory);
4162 if (strlen(options->DataDirectory) > (512-128)) {
4163 log_warn(LD_CONFIG, "DataDirectory is too
long.");
4169 /** This string must remain the same forevermore. It is how we
4170 * recognize that the torrc file doesn't need to be backed up. */
4171 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
4172 "if you edit it, comments will not be preserved"
4173 /** This string can change; it tries to give the reader an idea
4174 * that editing this file by hand is not a good plan. */
4175 #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
4176 "to torrc.orig.1 or similar, and Tor will ignore it"
4178 /** Save a configuration file for the configuration in <b>options</b>
4179 * into the file <b>fname</b>. If the file already exists, and
4180 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
4181 * replace it. Return 0 on success, -1 on failure. */
4183 write_configuration_file(const char *fname, or_options_t *options)
4185 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
4186 int rename_old = 0, r;
4190 switch (file_status(fname)) {
4192 old_val = read_file_to_str(fname, 0, NULL);
4193 if (strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
4204 "Config file \"%s\" is not a file? Failing.", fname);
4209 if (!(new_conf = options_dump(options, 1))) {
4210 log_warn(LD_BUG, "Couldn't get configuration string");
4214 len = strlen(new_conf)+256;
4215 new_val = tor_malloc(len);
4216 tor_snprintf(new_val, len, "%s\n%s\n\n%s",
4217 GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
4221 size_t fn_tmp_len = strlen(fname)+32;
4223 tor_assert(fn_tmp_len > strlen(fname)); /*check for overflow*/
4224 fn_tmp = tor_malloc(fn_tmp_len);
4226 if (tor_snprintf(fn_tmp, fn_tmp_len, "%s.orig.%d", fname, i)<0) {
4227 log_warn(LD_BUG, "tor_snprintf failed inexplicably");
4231 if (file_status(fn_tmp) == FN_NOENT)
4235 log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
4236 if (rename(fname, fn_tmp) < 0) {
4238 "Couldn't rename configuration file \"%s\" to \"%s\": %s",
4239 fname, fn_tmp, strerror(errno));
4246 if (write_str_to_file(fname, new_val, 0) < 0)
4260 * Save the current configuration file value to disk. Return 0 on
4261 * success, -1 on failure.
4264 options_save_current(void)
4267 /* This fails if we can't write to our configuration file.
4269 * If we try falling back to datadirectory or something, we have a better
4270 * chance of saving the configuration, but a better chance of doing
4271 * something the user never expected. Let's just warn instead. */
4272 return write_configuration_file(torrc_fname, get_options());
4274 return write_configuration_file(get_default_conf_file(), get_options());
4277 /** Mapping from a unit name to a multiplier for converting that unit into a
4279 struct unit_table_t {
4281 uint64_t multiplier;
4284 static struct unit_table_t memory_units[] = {
4291 { "kbytes", 1<<10 },
4292 { "kilobyte", 1<<10 },
4293 { "kilobytes", 1<<10 },
4297 { "mbytes", 1<<20 },
4298 { "megabyte", 1<<20 },
4299 { "megabytes", 1<<20 },
4302 { "gbytes", 1<<30 },
4303 { "gigabyte", 1<<30 },
4304 { "gigabytes", 1<<30 },
4305 { "tb", U64_LITERAL(1)<<40 },
4306 { "terabyte", U64_LITERAL(1)<<40 },
4307 { "terabytes", U64_LITERAL(1)<<40 },
4311 static struct unit_table_t time_units[] = {
4319 { "day", 24*60*60 },
4320 { "days", 24*60*60 },
4321 { "week", 7*24*60*60 },
4322 { "weeks", 7*24*60*60 },
4326 /** Parse a string <b>val</b> containing a number, zero or more
4327 * spaces, and an optional unit string. If the unit appears in the
4328 * table <b>u</b>, then multiply the number by the unit multiplier.
4329 * On success, set *<b>ok</b> to 1 and return this product.
4330 * Otherwise, set *<b>ok</b> to 0.
4333 config_parse_units(const char *val, struct unit_table_t *u, int *ok)
4340 v = tor_parse_uint64(val, 10, 0, UINT64_MAX, ok, &cp);
4347 while (TOR_ISSPACE(*cp))
4349 for ( ;u->unit;++u) {
4350 if (!strcasecmp(u->unit, cp)) {
4356 log_warn(LD_CONFIG, "Unknown unit '%s'.", cp);
4361 /** Parse a string in the format "number unit", where unit is a unit of
4362 * information (byte, KB, M, etc). On success, set *<b>ok</b> to true
4363 * and return the number of bytes specified. Otherwise, set
4364 * *<b>ok</b> to false and return 0. */
4366 config_parse_memunit(const char *s, int *ok)
4368 return config_parse_units(s, memory_units, ok);
4371 /** Parse a string in the format "number unit", where unit is a unit of time.
4372 * On success, set *<b>ok</b> to true and return the number of seconds in
4373 * the provided interval. Otherwise, set *<b>ok</b> to 0 and return -1.
4376 config_parse_interval(const char *s, int *ok)
4379 r = config_parse_units(s, time_units, ok);
4383 log_warn(LD_CONFIG, "Interval '%s' is too long", s);
4391 * Initialize the libevent library.
4396 configure_libevent_logging();
4397 /* If the kernel complains that some method (say, epoll) doesn't
4398 * exist, we don't care about it, since libevent will cope.
4400 suppress_libevent_log_msg("Function not implemented");
4402 if (decode_libevent_version() < LE_11B) {
4403 setenv("EVENT_NOKQUEUE","1",1);
4407 suppress_libevent_log_msg(NULL);
4408 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
4409 /* Making this a NOTICE for now so we can link bugs to a libevent versions
4410 * or methods better. */
4411 log(LOG_NOTICE, LD_GENERAL,
4412 "Initialized libevent version %s using method %s. Good.",
4413 event_get_version(), event_get_method());
4414 check_libevent_version(event_get_method(), get_options()->ORPort != 0);
4416 log(LOG_NOTICE, LD_GENERAL,
4417 "Initialized old libevent (version 1.0b or earlier).");
4418 log(LOG_WARN, LD_GENERAL,
4419 "You have a *VERY* old version of libevent. It is likely to be buggy; "
4420 "please build Tor with a more recent version.");
4424 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
4425 /** Table mapping return value of event_get_version() to le_version_t. */
4426 static const struct {
4427 const char *name; le_version_t version;
4428 } le_version_table[] = {
4429 /* earlier versions don't have get_version. */
4446 /** Return the le_version_t for the current version of libevent. If the
4447 * version is very new, return LE_OTHER. If the version is so old that it
4448 * doesn't support event_get_version(), return LE_OLD. */
4450 decode_libevent_version(void)
4452 const char *v = event_get_version();
4454 for (i=0; le_version_table[i].name; ++i) {
4455 if (!strcmp(le_version_table[i].name, v)) {
4456 return le_version_table[i].version;
4463 * Compare the given libevent method and version to a list of versions
4464 * which are known not to work. Warn the user as appropriate.
4467 check_libevent_version(const char *m, int server)
4469 int buggy = 0, iffy = 0, slow = 0, thread_unsafe = 0;
4470 le_version_t version;
4471 const char *v = event_get_version();
4472 const char *badness = NULL;
4473 const char *sad_os = "";
4475 version = decode_libevent_version();
4477 /* XXX Would it be worthwhile disabling the methods that we know
4478 * are buggy, rather than just warning about them and then proceeding
4479 * to use them? If so, we should probably not wrap this whole thing
4480 * in HAVE_EVENT_GET_VERSION and HAVE_EVENT_GET_METHOD. -RD */
4481 /* XXXX The problem is that it's not trivial to get libevent to change it's
4482 * method once it's initialized, and it's not trivial to tell what method it
4483 * will use without initializing it. I guess we could preemptively disable
4484 * buggy libevent modes based on the version _before_ initializing it,
4485 * though, but then there's no good way (afaict) to warn "I would have used
4486 * kqueue
, but instead I
'm using select." -NM */
4487 if (!strcmp(m, "kqueue")) {
4488 if (version < LE_11B)
4490 } else if (!strcmp(m, "epoll")) {
4491 if (version < LE_11)
4493 } else if (!strcmp(m, "poll")) {
4494 if (version < LE_10E)
4496 else if (version < LE_11)
4498 } else if (!strcmp(m, "select")) {
4499 if (version < LE_11)
4501 } else if (!strcmp(m, "win32")) {
4502 if (version < LE_11B)
4506 /* Libevent versions before 1.3b do very badly on operating systems with
4507 * user-space threading implementations. */
4508 #if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__)
4509 if (server && version < LE_13B) {
4511 sad_os = "BSD variants";
4513 #elif defined(__APPLE__) || defined(__darwin__)
4514 if (server && version < LE_13B) {
4516 sad_os = "Mac OS X";
4520 if (thread_unsafe) {
4521 log(LOG_WARN, LD_GENERAL,
4522 "Libevent version %s often crashes when running a Tor server with %s. "
4523 "Please use the latest version of libevent (1.3b or later)",v,sad_os);
4526 log(LOG_WARN, LD_GENERAL,
4527 "There are serious bugs in using %s with libevent %s. "
4528 "Please use the latest version of libevent.", m, v);
4531 log(LOG_WARN, LD_GENERAL,
4532 "There are minor bugs in using %s with libevent %s. "
4533 "You may want to use the latest version of libevent.", m, v);
4535 } else if (slow && server) {
4536 log(LOG_WARN, LD_GENERAL,
4537 "libevent %s can be very slow with %s. "
4538 "When running a server, please use the latest version of libevent.",
4543 control_event_general_status(LOG_WARN,
4544 "BAD_LIBEVENT VERSION=%s METHOD=%s BADNESS=%s RECOVERED=NO",
4551 decode_libevent_version(void)
4557 /** Return the persistent state struct for this Tor. */
4561 tor_assert(global_state);
4562 return global_state;
4565 /** Return a newly allocated string holding a filename relative to the data
4566 * directory. If <b>sub1</b> is present, it is the first path component after
4567 * the data directory. If <b>sub2</b> is also present, it is the second path
4568 * component after the data directory. If <b>suffix</b> is present, it
4569 * is appended to the filename.
4572 * get_datadir_fname2_suffix("a", NULL, NULL) -> $DATADIR/a
4573 * get_datadir_fname2_suffix("a", NULL, ".tmp") -> $DATADIR/a.tmp
4574 * get_datadir_fname2_suffix("a", "b", ".tmp") -> $DATADIR/a/b/.tmp
4575 * get_datadir_fname2_suffix("a", "b", NULL) -> $DATADIR/a/b
4577 * Note: Consider using the get_datadir_fname* macros in or.h.
4580 get_datadir_fname2_suffix(const char *sub1, const char *sub2,
4583 or_options_t *options = get_options();
4586 tor_assert(options);
4587 tor_assert(options->DataDirectory);
4588 tor_assert(sub1 || !sub2); /* If sub2 is present, sub1 must be present. */
4589 len = strlen(options->DataDirectory);
4591 len += strlen(sub1)+1;
4593 len += strlen(sub2)+1;
4596 len += strlen(suffix);
4598 fname = tor_malloc(len);
4601 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s",
4602 options->DataDirectory, sub1, sub2);
4604 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s",
4605 options->DataDirectory, sub1);
4608 strlcpy(fname, options->DataDirectory, len);
4611 strlcat(fname, suffix, len);
4615 /** Return 0 if every setting in <b>state</b> is reasonable, and a
4616 * permissible transition from <b>old_state</b>. Else warn and return -1.
4617 * Should have no side effects, except for normalizing the contents of
4620 /* XXX from_setconf is here because of bug 238 */
4622 or_state_validate(or_state_t *old_state, or_state_t *state,
4623 int from_setconf, char **msg)
4625 /* We don't use these
; only options
do. Still
, we need to match that
4627 (void) from_setconf
;
4630 if (entry_guards_parse_state(state
, 0, msg
)<0)
4636 /** Replace the current persistent state with <b>new_state</b> */
4638 or_state_set(or_state_t
*new_state
)
4641 tor_assert(new_state
);
4643 config_free(&state_format
, global_state
);
4644 global_state
= new_state
;
4645 if (entry_guards_parse_state(global_state
, 1, &err
)<0) {
4646 log_warn(LD_GENERAL
,"%s",err
);
4649 if (rep_hist_load_state(global_state
, &err
)<0) {
4650 log_warn(LD_GENERAL
,"Unparseable bandwidth history state: %s",err
);
4655 /** Reload the persistent state from disk, generating a new state as needed.
4656 * Return 0 on success, less than 0 on failure.
4661 or_state_t
*new_state
= NULL
;
4662 char *contents
= NULL
, *fname
;
4663 char *errmsg
= NULL
;
4664 int r
= -1, badstate
= 0;
4666 fname
= get_datadir_fname("state");
4667 switch (file_status(fname
)) {
4669 if (!(contents
= read_file_to_str(fname
, 0, NULL
))) {
4670 log_warn(LD_FS
, "Unable to read state file \"%s\"", fname
);
4679 log_warn(LD_GENERAL
,"State file \"%s\" is not a file? Failing.", fname
);
4682 new_state
= tor_malloc_zero(sizeof(or_state_t
));
4683 new_state
->_magic
= OR_STATE_MAGIC
;
4684 config_init(&state_format
, new_state
);
4686 config_line_t
*lines
=NULL
;
4688 if (config_get_lines(contents
, &lines
)<0)
4690 assign_retval
= config_assign(&state_format
, new_state
,
4691 lines
, 0, 0, &errmsg
);
4692 config_free_lines(lines
);
4693 if (assign_retval
<0)
4696 log_warn(LD_GENERAL
, "%s", errmsg
);
4701 if (!badstate
&& or_state_validate(NULL
, new_state
, 1, &errmsg
) < 0)
4705 log_warn(LD_GENERAL
, "%s", errmsg
);
4709 if (badstate
&& !contents
) {
4710 log_warn(LD_BUG
, "Uh oh. We couldn't even validate our own default state."
4711 " This is a bug in Tor.");
4713 } else if (badstate
&& contents
) {
4715 file_status_t status
;
4716 size_t len
= strlen(fname
)+16;
4717 char *fname2
= tor_malloc(len
);
4718 for (i
= 0; i
< 100; ++i
) {
4719 tor_snprintf(fname2
, len
, "%s.%d", fname
, i
);
4720 status
= file_status(fname2
);
4721 if (status
== FN_NOENT
)
4725 log_warn(LD_BUG
, "Unable to parse state in \"%s\"; too many saved bad "
4726 "state files to move aside. Discarding the old state file.",
4730 log_warn(LD_BUG
, "Unable to parse state in \"%s\". Moving it aside "
4731 "to \"%s\". This could be a bug in Tor; please tell "
4732 "the developers.", fname
, fname2
);
4733 rename(fname
, fname2
);
4737 config_free(&state_format
, new_state
);
4739 new_state
= tor_malloc_zero(sizeof(or_state_t
));
4740 new_state
->_magic
= OR_STATE_MAGIC
;
4741 config_init(&state_format
, new_state
);
4742 } else if (contents
) {
4743 log_info(LD_GENERAL
, "Loaded state from \"%s\"", fname
);
4745 log_info(LD_GENERAL
, "Initialized state");
4747 or_state_set(new_state
);
4750 global_state
->next_write
= 0;
4751 or_state_save(time(NULL
));
4759 config_free(&state_format
, new_state
);
4764 /** Write the persistent state to disk. Return 0 for success, <0 on failure. */
4766 or_state_save(time_t now
)
4768 char *state
, *contents
;
4769 char tbuf
[ISO_TIME_LEN
+1];
4773 tor_assert(global_state
);
4775 if (global_state
->next_write
> now
)
4778 /* Call everything else that might dirty the state even more, in order
4779 * to avoid redundant writes. */
4780 entry_guards_update_state(global_state
);
4781 rep_hist_update_state(global_state
);
4782 if (accounting_is_enabled(get_options()))
4783 accounting_run_housekeeping(now
);
4785 global_state
->LastWritten
= time(NULL
);
4786 tor_free(global_state
->TorVersion
);
4787 len
= strlen(get_version())+8;
4788 global_state
->TorVersion
= tor_malloc(len
);
4789 tor_snprintf(global_state
->TorVersion
, len
, "Tor %s", get_version());
4791 state
= config_dump(&state_format
, global_state
, 1, 0);
4792 len
= strlen(state
)+256;
4793 contents
= tor_malloc(len
);
4794 format_local_iso_time(tbuf
, time(NULL
));
4795 tor_snprintf(contents
, len
,
4796 "# Tor state file last generated on %s local time\n"
4797 "# Other times below are in GMT\n"
4798 "# You *do not* need to edit this file.\n\n%s",
4801 fname
= get_datadir_fname("state");
4802 if (write_str_to_file(fname
, contents
, 0)<0) {
4803 log_warn(LD_FS
, "Unable to write state to file \"%s\"", fname
);
4808 log_info(LD_GENERAL
, "Saved state to \"%s\"", fname
);
4812 global_state
->next_write
= TIME_MAX
;
4816 /** Given a file name check to see whether the file exists but has not been
4817 * modified for a very long time. If so, remove it. */
4819 remove_file_if_very_old(const char *fname
, time_t now
)
4821 #define VERY_OLD_FILE_AGE (28*24*60*60)
4824 if (stat(fname
, &st
)==0 && st
.st_mtime
< now
-VERY_OLD_FILE_AGE
) {
4825 char buf
[ISO_TIME_LEN
+1];
4826 format_local_iso_time(buf
, st
.st_mtime
);
4827 log_notice(LD_GENERAL
, "Obsolete file %s hasn't been modified since %s. "
4828 "Removing it.", fname
, buf
);
4833 /** Helper to implement GETINFO functions about configuration variables (not
4834 * their values). Given a "config/names" question, set *<b>answer</b> to a
4835 * new string describing the supported configuration variables and their
4838 getinfo_helper_config(control_connection_t
*conn
,
4839 const char *question
, char **answer
)
4842 if (!strcmp(question
, "config/names")) {
4843 smartlist_t
*sl
= smartlist_create();
4845 for (i
= 0; _option_vars
[i
].name
; ++i
) {
4846 config_var_t
*var
= &_option_vars
[i
];
4847 const char *type
, *desc
;
4850 desc
= config_find_description(&options_format
, var
->name
);
4851 switch (var
->type
) {
4852 case CONFIG_TYPE_STRING
: type
= "String"; break;
4853 case CONFIG_TYPE_UINT
: type
= "Integer"; break;
4854 case CONFIG_TYPE_INTERVAL
: type
= "TimeInterval"; break;
4855 case CONFIG_TYPE_MEMUNIT
: type
= "DataSize"; break;
4856 case CONFIG_TYPE_DOUBLE
: type
= "Float"; break;
4857 case CONFIG_TYPE_BOOL
: type
= "Boolean"; break;
4858 case CONFIG_TYPE_ISOTIME
: type
= "Time"; break;
4859 case CONFIG_TYPE_CSV
: type
= "CommaList"; break;
4860 case CONFIG_TYPE_LINELIST
: type
= "LineList"; break;
4861 case CONFIG_TYPE_LINELIST_S
: type
= "Dependant"; break;
4862 case CONFIG_TYPE_LINELIST_V
: type
= "Virtual"; break;
4864 case CONFIG_TYPE_OBSOLETE
:
4869 len
= strlen(var
->name
)+strlen(type
)+16;
4871 len
+= strlen(desc
);
4872 line
= tor_malloc(len
);
4874 tor_snprintf(line
, len
, "%s %s %s\n",var
->name
,type
,desc
);
4876 tor_snprintf(line
, len
, "%s %s\n",var
->name
,type
);
4877 smartlist_add(sl
, line
);
4879 *answer
= smartlist_join_strings(sl
, "", 0, NULL
);
4880 SMARTLIST_FOREACH(sl
, char *, c
, tor_free(c
));
4890 extern const char aes_c_id
[];
4891 extern const char compat_c_id
[];
4892 extern const char container_c_id
[];
4893 extern const char crypto_c_id
[];
4894 extern const char log_c_id
[];
4895 extern const char torgzip_c_id
[];
4896 extern const char tortls_c_id
[];
4897 extern const char util_c_id
[];
4899 extern const char buffers_c_id
[];
4900 extern const char circuitbuild_c_id
[];
4901 extern const char circuitlist_c_id
[];
4902 extern const char circuituse_c_id
[];
4903 extern const char command_c_id
[];
4904 // extern const char config_c_id[];
4905 extern const char connection_c_id
[];
4906 extern const char connection_edge_c_id
[];
4907 extern const char connection_or_c_id
[];
4908 extern const char control_c_id
[];
4909 extern const char cpuworker_c_id
[];
4910 extern const char directory_c_id
[];
4911 extern const char dirserv_c_id
[];
4912 extern const char dns_c_id
[];
4913 extern const char hibernate_c_id
[];
4914 extern const char main_c_id
[];
4916 extern const char ntmain_c_id
[];
4918 extern const char onion_c_id
[];
4919 extern const char policies_c_id
[];
4920 extern const char relay_c_id
[];
4921 extern const char rendclient_c_id
[];
4922 extern const char rendcommon_c_id
[];
4923 extern const char rendmid_c_id
[];
4924 extern const char rendservice_c_id
[];
4925 extern const char rephist_c_id
[];
4926 extern const char router_c_id
[];
4927 extern const char routerlist_c_id
[];
4928 extern const char routerparse_c_id
[];
4930 /** Dump the version of every file to the log. */
4932 print_svn_version(void)
4936 puts(CONTAINER_H_ID
);
4947 puts(container_c_id
);
4956 puts(circuitbuild_c_id
);
4957 puts(circuitlist_c_id
);
4958 puts(circuituse_c_id
);
4961 puts(connection_c_id
);
4962 puts(connection_edge_c_id
);
4963 puts(connection_or_c_id
);
4965 puts(cpuworker_c_id
);
4966 puts(directory_c_id
);
4969 puts(hibernate_c_id
);
4975 puts(policies_c_id
);
4977 puts(rendclient_c_id
);
4978 puts(rendcommon_c_id
);
4980 puts(rendservice_c_id
);
4983 puts(routerlist_c_id
);
4984 puts(routerparse_c_id
);