correct copyright statement
[tor.git] / src / or / config.c
blobb0eeec63760a5dae060d562439b28b40f4f3ab26
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 */
6 /* $Id$ */
7 const char config_c_id[] = \
8 "$Id$";
10 /**
11 * \file config.c
12 * \brief Code to parse and interpret configuration files.
13 **/
15 #define CONFIG_PRIVATE
17 #include "or.h"
18 #ifdef MS_WINDOWS
19 #include <shlobj.h>
20 #endif
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. */
40 } config_type_t;
42 /** An abbreviation for a configuration option allowed on the command line. */
43 typedef struct config_abbrev_t {
44 const char *abbreviated;
45 const char *full;
46 int commandline_only;
47 int warn;
48 } config_abbrev_t;
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[] = {
56 PLURAL(ExitNode),
57 PLURAL(EntryNode),
58 PLURAL(ExcludeNode),
59 PLURAL(FirewallPort),
60 PLURAL(LongLivedPort),
61 PLURAL(HiddenServiceNode),
62 PLURAL(HiddenServiceExcludeNode),
63 PLURAL(NumCpu),
64 PLURAL(RendNode),
65 PLURAL(RendExcludeNode),
66 PLURAL(StrictEntryNode),
67 PLURAL(StrictExitNode),
68 { "l", "Log", 1, 0},
69 { "AllowUnverifiedNodes", "AllowInvalidNodes", 0, 0},
70 { "AutomapHostSuffixes", "AutomapHostsSuffixes", 0, 0},
71 { "AutomapHostOnResolve", "AutomapHostsOnResolve", 0, 0},
72 { "BandwidthRateBytes", "BandwidthRate", 0, 0},
73 { "BandwidthBurstBytes", "BandwidthBurst", 0, 0},
74 { "DirFetchPostPeriod", "StatusFetchPeriod", 0, 0},
75 { "MaxConn", "ConnLimit", 0, 1},
76 { "ORBindAddress", "ORListenAddress", 0, 0},
77 { "DirBindAddress", "DirListenAddress", 0, 0},
78 { "SocksBindAddress", "SocksListenAddress", 0, 0},
79 { "UseHelperNodes", "UseEntryGuards", 0, 0},
80 { "NumHelperNodes", "NumEntryGuards", 0, 0},
81 { "UseEntryNodes", "UseEntryGuards", 0, 0},
82 { "NumEntryNodes", "NumEntryGuards", 0, 0},
83 { "ResolvConf", "ServerDNSResolvConfFile", 0, 1},
84 { "SearchDomains", "ServerDNSSearchDomains", 0, 1},
85 { "PreferTunnelledDirConns", "PreferTunneledDirConns", 0, 0},
86 { "BridgeAuthoritativeDirectory", "BridgeAuthoritativeDir", 0, 0},
87 { NULL, NULL, 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 },
98 { NULL, NULL, 0, 0},
100 #undef PLURAL
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
106 * value. */
107 off_t var_offset; /**< Offset of the corresponding member of or_options_t. */
108 const char *initvalue; /**< String (or null) describing initial value. */
109 } config_var_t;
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), \
117 initvalue }
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
126 * be chosen first.
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"),
222 OBSOLETE("LogFile"),
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"),
282 OBSOLETE("SysLog"),
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 }
311 #undef VAR
313 #define VAR(name,conftype,member,initvalue) \
314 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_state_t, member), \
315 initvalue }
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 }
344 #undef VAR
345 #undef V
346 #undef OBSOLETE
348 /** Represents an English description of a configuration variable; used when
349 * generating configuration file comments. */
350 typedef struct config_var_description_t {
351 const char *name;
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 "
380 "authorities." },
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 "
386 "when it can." },
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 "
391 "HTTPProxy." },
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 "
395 "HTTPSProxy." },
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, "
453 "when possible." },
454 { "RendExcludenodes", "A list of nodes never to use as rendezvous points." },
455 /* SafeSOCKS */
456 { "SOCKSPort", "The port where we listen for SOCKS connections from "
457 "applications." },
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." },
462 /* SocksTimeout */
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." },
467 /* TestSocks */
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 "
482 "server." },
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 "
498 "and servers." },
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." },
509 /* { "TestVia", } */
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 "
517 "port" },
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 */
530 { NULL, NULL },
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?" },
562 { NULL, NULL },
565 /** Type of a callback to validate whether a given configuration is
566 * well-formed and consistent. See options_trial_assign() for documentation
567 * of arguments. */
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. */
573 typedef struct {
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. */
587 config_var_t *extra;
588 } config_format_t;
590 /** Macro: assert that <b>cfg</b> has the right magic field for format
591 * <b>fmt</b>. */
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)); \
596 STMT_END
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,
601 config_var_t *var);
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,
608 const char *name);
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,
615 char **msg);
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,
626 int validate_only);
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,
630 int *max_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,
635 int escape_val);
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. */
648 typedef enum {
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,
653 LE_OTHER
654 } le_version_t;
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);
658 #endif
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),
666 OR_OPTIONS_MAGIC,
667 STRUCT_OFFSET(or_options_t, _magic),
668 _option_abbrevs,
669 _option_vars,
670 (validate_fn_t)options_validate,
671 options_description,
672 NULL
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 = {
686 sizeof(or_state_t),
687 OR_STATE_MAGIC,
688 STRUCT_OFFSET(or_state_t, _magic),
689 _state_abbrevs,
690 _state_vars,
691 (validate_fn_t)or_state_validate,
692 state_description,
693 &state_extra_var,
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. */
708 static void *
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;
713 CHECK(fmt, opts);
714 return opts;
717 /** Return the currently configured options. */
718 or_options_t *
719 get_options(void)
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
727 * as necessary.
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) {
737 tor_assert(*msg);
738 global_options = old_options;
739 return -1;
741 if (options_act(old_options) < 0) { /* acting on the options failed. die. */
742 log_err(LD_BUG,
743 "Acting on config options left us in a broken state. Dying.");
744 exit(1);
746 if (old_options)
747 config_free(&options_format, old_options);
749 return 0;
752 extern const char tor_svn_revision[]; /* from tor_main.c */
754 static char *_version = NULL;
756 /** Return the current Tor version, possibly */
757 const char *
758 get_version(void)
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);
765 } else {
766 _version = tor_strdup(VERSION);
769 return _version;
772 /** Release all memory and resources held by global configuration structures.
774 void
775 config_free_all(void)
777 if (global_options) {
778 config_free(&options_format, global_options);
779 global_options = NULL;
781 if (global_state) {
782 config_free(&state_format, global_state);
783 global_state = NULL;
785 tor_free(torrc_fname);
786 tor_free(_version);
789 /** If options->SafeLogging is on, return a not very useful string,
790 * else return address.
792 const char *
793 safe_str(const char *address)
795 tor_assert(address);
796 if (get_options()->SafeLogging)
797 return "[scrubbed]";
798 else
799 return address;
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
804 * log statement. */
805 const char *
806 escaped_safe_str(const char *address)
808 if (get_options()->SafeLogging)
809 return "[scrubbed]";
810 else
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>. */
816 static void
817 add_default_trusted_dir_authorities(authority_type_t type)
819 int i;
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",
841 NULL
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",
846 dirservers[i]);
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.
855 static int
856 validate_dir_authorities(or_options_t *options, or_options_t *old_options)
858 config_line_t *cl;
860 if (options->DirServers &&
861 (options->AlternateDirAuthority || options->AlternateBridgeAuthority ||
862 options->AlternateHSAuthority)) {
863 log_warn(LD_CONFIG,
864 "You cannot set both DirServers and Alternate*Authority.");
865 return -1;
868 /* do we want to complain to the user about being partitionable? */
869 if ((options->DirServers &&
870 (!old_options ||
871 !config_lines_eq(options->DirServers, old_options->DirServers))) ||
872 (options->AlternateDirAuthority &&
873 (!old_options ||
874 !config_lines_eq(options->AlternateDirAuthority,
875 old_options->AlternateDirAuthority)))) {
876 log_warn(LD_CONFIG,
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)
890 return -1;
891 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
892 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
893 return -1;
894 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
895 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
896 return -1;
897 for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
898 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
899 return -1;
900 return 0;
903 /** Look at all the config options and assign new dir authorities
904 * as appropriate.
906 static int
907 consider_adding_dir_authorities(or_options_t *options,
908 or_options_t *old_options)
910 config_line_t *cl;
911 int need_to_update =
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);
921 if (!need_to_update)
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)
941 return -1;
942 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
943 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
944 return -1;
945 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
946 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
947 return -1;
948 for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
949 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
950 return -1;
951 return 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.
960 static int
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;
969 int r = -1;
970 int logs_marked = 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
974 * processes. */
975 if (running_tor && options->RunAsDaemon) {
976 /* No need to roll back, since you can't change the value. */
977 start_daemon();
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.");
984 goto rollback;
986 #endif
988 if (running_tor) {
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.");
994 goto rollback;
996 set_conn_limit = 1;
998 /* Set up libevent. (We need to do this before we can register the
999 * listeners as listeners.) */
1000 if (running_tor && !libevent_initialized) {
1001 init_libevent();
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.");
1009 goto rollback;
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.");
1019 goto done;
1023 /* Ensure data directory is private; create if possible. */
1024 if (check_private_dir(options->DataDirectory,
1025 running_tor ? CPD_CREATE : CPD_CHECK)<0) {
1026 char buf[1024];
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");
1031 goto done;
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. */
1037 if (!running_tor)
1038 goto commit;
1040 mark_logs_temp(); /* Close current logs once new logs are open. */
1041 logs_marked = 1;
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.");
1044 goto rollback;
1047 commit:
1048 r = 0;
1049 if (logs_marked) {
1050 close_temp_logs();
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);
1061 goto done;
1063 rollback:
1064 r = -1;
1065 tor_assert(*msg);
1067 if (logs_marked) {
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);
1083 done:
1084 smartlist_free(new_listeners);
1085 smartlist_free(replaced_listeners);
1086 return r;
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.
1098 static int
1099 options_act(or_options_t *old_options)
1101 config_line_t *cl;
1102 char *fn;
1103 size_t len;
1104 or_options_t *options = get_options();
1105 int running_tor = options->command == CMD_RUN_TOR;
1106 char *msg;
1108 if (consider_adding_dir_authorities(options, old_options) < 0)
1109 return -1;
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) {
1115 log_warn(LD_BUG,
1116 "Previously validated Bridge line could not be added!");
1117 return -1;
1122 if (running_tor && rend_config_services(options, 0)<0) {
1123 log_warn(LD_BUG,
1124 "Previously validated hidden services line could not be added!");
1125 return -1;
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) {
1134 log_warn(LD_CONFIG,
1135 "Couldn't access/create private data directory \"%s\"", fn);
1136 tor_free(fn);
1137 return -1;
1139 tor_free(fn);
1142 /* Load state */
1143 if (! global_state && options->command == CMD_RUN_TOR) {
1144 if (or_state_load())
1145 return -1;
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. */
1151 if (!running_tor)
1152 return 0;
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);
1160 tor_free(errmsg);
1161 SMARTLIST_FOREACH(sl, exit_redirect_t *, er, tor_free(er));
1162 smartlist_free(sl);
1163 return -1;
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.");
1189 return -1;
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");
1195 return -1;
1198 /* Set up accounting */
1199 if (accounting_parse_options(options, 0)<0) {
1200 log_warn(LD_CONFIG,"Error in accounting options");
1201 return -1;
1203 if (accounting_is_enabled(options))
1204 configure_accounting(time(NULL));
1206 /* Check for transitions that need action. */
1207 if (old_options) {
1208 if (options->UseEntryGuards && !old_options->UseEntryGuards) {
1209 log_info(LD_CIRC,
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");
1221 return -1;
1223 ip_address_changed(0);
1224 if (has_completed_circuit || !any_predicted_circuits(time(NULL)))
1225 inform_testing_reachability();
1227 cpuworkers_rotate();
1228 if (dns_reset())
1229 return -1;
1230 } else {
1231 if (dns_reset())
1232 return -1;
1235 if (options->V3AuthoritativeDir && !old_options->V3AuthoritativeDir)
1236 init_keys();
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 &&
1247 (!old_options ||
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.
1254 if (!old_options ||
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. */
1259 if (old_options) {
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));
1274 return 0;
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. */
1286 static const char *
1287 expand_abbrev(config_format_t *fmt, const char *option, int command_line,
1288 int warn_obsolete)
1290 int i;
1291 if (! fmt->abbrevs)
1292 return option;
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) {
1298 log_warn(LD_CONFIG,
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;
1307 return option;
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. */
1313 static int
1314 config_get_commandlines(int argc, char **argv, config_line_t **result)
1316 config_line_t *front = NULL;
1317 config_line_t **new = &front;
1318 char *s;
1319 int i = 1;
1321 while (i < argc) {
1322 if (!strcmp(argv[i],"-f") ||
1323 !strcmp(argv[i],"--hash-password")) {
1324 i += 2; /* command-line option with argument. ignore them. */
1325 continue;
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. */
1331 continue;
1332 } else if (!strcmp(argv[i],"--nt-service") ||
1333 !strcmp(argv[i],"-nt-service")) {
1334 i += 1;
1335 continue;
1338 if (i == argc-1) {
1339 log_warn(LD_CONFIG,"Command-line option '%s' with no value. Failing.",
1340 argv[i]);
1341 config_free_lines(front);
1342 return -1;
1345 *new = tor_malloc_zero(sizeof(config_line_t));
1346 s = argv[i];
1348 while (*s == '-')
1349 s++;
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);
1358 i += 2;
1360 *result = front;
1361 return 0;
1364 /** Helper: allocate a new configuration option mapping 'key' to 'val',
1365 * append it to *<b>lst</b>. */
1366 static void
1367 config_line_append(config_line_t **lst,
1368 const char *key,
1369 const char *val)
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;
1377 while (*lst)
1378 lst = &((*lst)->next);
1380 (*lst) = newline;
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;
1391 char *k, *v;
1393 next = &list;
1394 do {
1395 string = parse_config_line_from_str(string, &k, &v);
1396 if (!string) {
1397 config_free_lines(list);
1398 return -1;
1400 if (k && v) {
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));
1405 (*next)->key = k;
1406 (*next)->value = v;
1407 (*next)->next = NULL;
1408 next = &((*next)->next);
1409 } else {
1410 tor_free(k);
1411 tor_free(v);
1413 } while (*string);
1415 *result = list;
1416 return 0;
1420 * Free all the configuration lines on the linked list <b>front</b>.
1422 void
1423 config_free_lines(config_line_t *front)
1425 config_line_t *tmp;
1427 while (front) {
1428 tmp = front;
1429 front = tmp->next;
1431 tor_free(tmp->key);
1432 tor_free(tmp->value);
1433 tor_free(tmp);
1437 /** Return the description for a given configuration variable, or NULL if no
1438 * description exists. */
1439 static const char *
1440 config_find_description(config_format_t *fmt, const char *name)
1442 int i;
1443 for (i=0; fmt->descriptions[i].name; ++i) {
1444 if (!strcasecmp(name, fmt->descriptions[i].name))
1445 return fmt->descriptions[i].description;
1447 return NULL;
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)
1457 int i;
1458 size_t keylen = strlen(key);
1459 if (!keylen)
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 */
1477 return NULL;
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().
1489 static int
1490 config_assign_value(config_format_t *fmt, or_options_t *options,
1491 config_line_t *c, char **msg)
1493 int i, r, ok;
1494 char buf[1024];
1495 config_var_t *var;
1496 void *lvalue;
1498 CHECK(fmt, options);
1500 var = config_find_option(fmt, c->key);
1501 tor_assert(var);
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);
1509 if (!ok) {
1510 r = tor_snprintf(buf, sizeof(buf),
1511 "Int keyword '%s %s' is malformed or out of bounds.",
1512 c->key, c->value);
1513 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1514 return -1;
1516 *(int *)lvalue = i;
1517 break;
1519 case CONFIG_TYPE_INTERVAL: {
1520 i = config_parse_interval(c->value, &ok);
1521 if (!ok) {
1522 r = tor_snprintf(buf, sizeof(buf),
1523 "Interval '%s %s' is malformed or out of bounds.",
1524 c->key, c->value);
1525 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1526 return -1;
1528 *(int *)lvalue = i;
1529 break;
1532 case CONFIG_TYPE_MEMUNIT: {
1533 uint64_t u64 = config_parse_memunit(c->value, &ok);
1534 if (!ok) {
1535 r = tor_snprintf(buf, sizeof(buf),
1536 "Value '%s %s' is malformed or out of bounds.",
1537 c->key, c->value);
1538 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1539 return -1;
1541 *(uint64_t *)lvalue = u64;
1542 break;
1545 case CONFIG_TYPE_BOOL:
1546 i = tor_parse_long(c->value, 10, 0, 1, &ok, NULL);
1547 if (!ok) {
1548 r = tor_snprintf(buf, sizeof(buf),
1549 "Boolean '%s %s' expects 0 or 1.",
1550 c->key, c->value);
1551 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1552 return -1;
1554 *(int *)lvalue = i;
1555 break;
1557 case CONFIG_TYPE_STRING:
1558 tor_free(*(char **)lvalue);
1559 *(char **)lvalue = tor_strdup(c->value);
1560 break;
1562 case CONFIG_TYPE_DOUBLE:
1563 *(double *)lvalue = atof(c->value);
1564 break;
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");
1571 return -1;
1573 break;
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);
1579 } else {
1580 *(smartlist_t**)lvalue = smartlist_create();
1583 smartlist_split_string(*(smartlist_t**)lvalue, c->value, ",",
1584 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1585 break;
1587 case CONFIG_TYPE_LINELIST:
1588 case CONFIG_TYPE_LINELIST_S:
1589 config_line_append((config_line_t**)lvalue, c->key, c->value);
1590 break;
1592 case CONFIG_TYPE_OBSOLETE:
1593 log_warn(LD_CONFIG, "Skipping obsolete configuration option '%s'", c->key);
1594 break;
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");
1599 return -1;
1600 default:
1601 tor_assert(0);
1602 break;
1604 return 0;
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().
1616 static int
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)
1621 config_var_t *var;
1623 CHECK(fmt, options);
1625 var = config_find_option(fmt, c->key);
1626 if (!var) {
1627 if (fmt->extra) {
1628 void *lvalue = STRUCT_VAR_P(options, fmt->extra->var_offset);
1629 log_info(LD_CONFIG,
1630 "Found unrecognized option '%s'; saving it.", c->key);
1631 config_line_append((config_line_t**)lvalue, c->key, c->value);
1632 return 0;
1633 } else {
1634 char buf[1024];
1635 int tmp = tor_snprintf(buf, sizeof(buf),
1636 "Unknown option '%s'. Failing.", c->key);
1637 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1638 return -1;
1641 /* Put keyword into canonical case. */
1642 if (strcmp(var->name, c->key)) {
1643 tor_free(c->key);
1644 c->key = tor_strdup(var->name);
1647 if (!strlen(c->value)) {
1648 /* reset or clear it, then return */
1649 if (!clear_first) {
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. */
1654 log_warn(LD_CONFIG,
1655 "Linelist option '%s' has no value. Skipping.", c->key);
1656 } else { /* not already cleared */
1657 option_reset(fmt, options, var, use_defaults);
1660 return 0;
1663 if (config_assign_value(fmt, options, c, msg) < 0)
1664 return -2;
1665 return 0;
1668 /** Restore the option named <b>key</b> in options to its default value.
1669 * Called from config_assign(). */
1670 static void
1671 config_reset_line(config_format_t *fmt, or_options_t *options,
1672 const char *key, int use_defaults)
1674 config_var_t *var;
1676 CHECK(fmt, options);
1678 var = config_find_option(fmt, key);
1679 if (!var)
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. */
1695 const char *
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.
1704 config_line_t *
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. */
1712 static int
1713 config_value_needs_escape(const char *value)
1715 if (*value == '\"')
1716 return 1;
1717 while (*value) {
1718 switch (*value)
1720 case '\r':
1721 case '\n':
1722 case '#':
1723 /* Note: quotes and backspaces need special handling when we are using
1724 * quotes, not otherwise, so they don't trigger escaping on their
1725 * own. */
1726 return 1;
1727 default:
1728 if (!TOR_ISPRINT(*value))
1729 return 1;
1731 ++value;
1733 return 0;
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;
1742 while (inp) {
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);
1746 inp = inp->next;
1747 next_out = &((*next_out)->next);
1749 (*next_out) = NULL;
1750 return result;
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. */
1762 config_var_t *var;
1763 const void *value;
1764 char buf[32];
1765 config_line_t *result;
1766 tor_assert(options && key);
1768 CHECK(fmt, options);
1770 var = config_find_option(fmt, key);
1771 if (!var) {
1772 log_warn(LD_CONFIG, "Unknown option '%s'. Failing.", key);
1773 return NULL;
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);
1779 switch (var->type)
1781 case CONFIG_TYPE_STRING:
1782 if (*(char**)value) {
1783 result->value = tor_strdup(*(char**)value);
1784 } else {
1785 tor_free(result->key);
1786 tor_free(result);
1787 return NULL;
1789 break;
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);
1794 } else {
1795 tor_free(result->key);
1796 tor_free(result);
1798 escape_val = 0; /* Can't need escape. */
1799 break;
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. */
1807 break;
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. */
1813 break;
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. */
1818 break;
1819 case CONFIG_TYPE_BOOL:
1820 result->value = tor_strdup(*(int*)value ? "1" : "0");
1821 escape_val = 0; /* Can't need escape. */
1822 break;
1823 case CONFIG_TYPE_CSV:
1824 if (*(smartlist_t**)value)
1825 result->value =
1826 smartlist_join_strings(*(smartlist_t**)value, ",", 0, NULL);
1827 else
1828 result->value = tor_strdup("");
1829 break;
1830 case CONFIG_TYPE_OBSOLETE:
1831 log_warn(LD_CONFIG,
1832 "You asked me for the value of an obsolete config option '%s'.",
1833 key);
1834 tor_free(result->key);
1835 tor_free(result);
1836 return NULL;
1837 case CONFIG_TYPE_LINELIST_S:
1838 log_warn(LD_CONFIG,
1839 "Can't return context-sensitive '%s' on its own", key);
1840 tor_free(result->key);
1841 tor_free(result);
1842 return NULL;
1843 case CONFIG_TYPE_LINELIST:
1844 case CONFIG_TYPE_LINELIST_V:
1845 tor_free(result->key);
1846 tor_free(result);
1847 result = config_lines_dup(*(const config_line_t**)value);
1848 break;
1849 default:
1850 tor_free(result->key);
1851 tor_free(result);
1852 log_warn(LD_BUG,"Unknown type %d for known key '%s'",
1853 var->type, key);
1854 return NULL;
1857 if (escape_val) {
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;
1868 return result;
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
1890 * 0 0 "append"
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.
1909 Case two: setconf
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).
1925 returns.
1927 static int
1928 config_assign(config_format_t *fmt, void *options, config_line_t *list,
1929 int use_defaults, int clear_first, char **msg)
1931 config_line_t *p;
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)) {
1939 tor_free(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. */
1946 if (clear_first) {
1947 for (p = list; p; p = p->next)
1948 config_reset_line(fmt, options, p->key, use_defaults);
1951 /* pass 3: assign. */
1952 while (list) {
1953 int r;
1954 if ((r=config_assign_line(fmt, options, list, use_defaults,
1955 clear_first, msg)))
1956 return r;
1957 list = list->next;
1959 return 0;
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
1969 * what went wrong.
1972 options_trial_assign(config_line_t *list, int use_defaults,
1973 int clear_first, char **msg)
1975 int r;
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);
1981 return r;
1984 if (options_validate(get_options(), trial_options, 1, msg) < 0) {
1985 config_free(&options_format, trial_options);
1986 return -2;
1989 if (options_transition_allowed(get_options(), trial_options, msg) < 0) {
1990 config_free(&options_format, trial_options);
1991 return -3;
1994 if (set_options(trial_options, msg)<0) {
1995 config_free(&options_format, trial_options);
1996 return -4;
1999 /* we liked it. put it in place. */
2000 return 0;
2003 /** Reset config option <b>var</b> to 0, 0.0, NULL, or the equivalent.
2004 * Called from option_reset() and config_free(). */
2005 static void
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);
2013 break;
2014 case CONFIG_TYPE_DOUBLE:
2015 *(double*)lvalue = 0.0;
2016 break;
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:
2022 *(int*)lvalue = 0;
2023 break;
2024 case CONFIG_TYPE_MEMUNIT:
2025 *(uint64_t*)lvalue = 0;
2026 break;
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;
2033 break;
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;
2038 break;
2039 case CONFIG_TYPE_LINELIST_V:
2040 /* handled by linelist_s. */
2041 break;
2042 case CONFIG_TYPE_OBSOLETE:
2043 break;
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(). */
2050 static void
2051 option_reset(config_format_t *fmt, or_options_t *options,
2052 config_var_t *var, int use_defaults)
2054 config_line_t *c;
2055 char *msg = NULL;
2056 CHECK(fmt, options);
2057 option_clear(fmt, options, var); /* clear it first */
2058 if (!use_defaults)
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. */
2073 static void
2074 print_usage(void)
2076 printf(
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. */
2086 static void
2087 list_torrc_options(void)
2089 int i;
2090 smartlist_t *lines = smartlist_create();
2091 for (i = 0; _option_vars[i].name; ++i) {
2092 config_var_t *var = &_option_vars[i];
2093 const char *desc;
2094 if (var->type == CONFIG_TYPE_OBSOLETE ||
2095 var->type == CONFIG_TYPE_LINELIST_V)
2096 continue;
2097 desc = config_find_description(&options_format, var->name);
2098 printf("%s\n", var->name);
2099 if (desc) {
2100 wrap_string(lines, desc, 76, " ", " ");
2101 SMARTLIST_FOREACH(lines, char *, cp, {
2102 printf("%s", cp);
2103 tor_free(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)
2124 struct in_addr in;
2125 struct hostent *rent;
2126 char hostname[256];
2127 int explicit_ip=1;
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");
2145 return -1;
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 */
2154 explicit_ip = 0;
2155 rent = (struct hostent *)gethostbyname(hostname);
2156 if (!rent) {
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);
2162 return -1;
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.");
2170 return -1;
2172 from_interface = 1;
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));
2178 } else {
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)) {
2195 struct in_addr in2;
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);
2201 } else {
2202 from_interface = 1;
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
2220 * always. */
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);
2225 return -1;
2227 if (!explicit_ip) {
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);
2233 return -1;
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. */
2242 log_notice(LD_NET,
2243 "Your IP address seems to have changed to %s. Updating.",
2244 tmpbuf);
2245 ip_address_changed(0);
2247 if (last_resolved_addr != *addr_out) {
2248 const char *method;
2249 const char *h = hostname;
2250 if (explicit_ip) {
2251 method = "CONFIGURED";
2252 h = NULL;
2253 } else if (explicit_hostname) {
2254 method = "RESOLVED";
2255 } else if (from_interface) {
2256 method = "INTERFACE";
2257 h = NULL;
2258 } else {
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;
2266 if (hostname_out)
2267 *hostname_out = tor_strdup(hostname);
2268 return 0;
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))
2278 return 1;
2279 /* Check whether ip is on the same /24 as we are. */
2280 if (get_options()->EnforceDistinctSubnets == 0)
2281 return 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))
2290 return 1;
2291 return 0;
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. */
2297 static char *
2298 get_default_nickname(void)
2300 static const char * const bad_default_nicknames[] = {
2301 "localhost",
2302 NULL,
2304 char localhostname[256];
2305 char *cp, *out, *outp;
2306 int i;
2308 if (gethostname(localhostname, sizeof(localhostname)) < 0)
2309 return NULL;
2311 /* Put it in lowercase; stop at the first dot. */
2312 if ((cp = strchr(localhostname, '.')))
2313 *cp = '\0';
2314 tor_strlower(localhostname);
2316 /* Strip invalid characters. */
2317 cp = localhostname;
2318 out = outp = tor_malloc(strlen(localhostname) + 1);
2319 while (*cp) {
2320 if (strchr(LEGAL_NICKNAME_CHARACTERS, *cp))
2321 *outp++ = *cp++;
2322 else
2323 cp++;
2325 *outp = '\0';
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])) {
2334 tor_free(out);
2335 return NULL;
2339 return out;
2342 /** Release storage held by <b>options</b>. */
2343 static void
2344 config_free(config_format_t *fmt, void *options)
2346 int i;
2348 tor_assert(options);
2350 for (i=0; fmt->vars[i].name; ++i)
2351 option_clear(fmt, options, &(fmt->vars[i]));
2352 if (fmt->extra) {
2353 config_line_t **linep = STRUCT_VAR_P(options, fmt->extra->var_offset);
2354 config_free_lines(*linep);
2355 *linep = NULL;
2357 tor_free(options);
2360 /** Return true iff a and b contain identical keys and values in identical
2361 * order. */
2362 static int
2363 config_lines_eq(config_line_t *a, config_line_t *b)
2365 while (a && b) {
2366 if (strcasecmp(a->key, b->key) || strcmp(a->value, b->value))
2367 return 0;
2368 a = a->next;
2369 b = b->next;
2371 if (a || b)
2372 return 0;
2373 return 1;
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.
2379 static int
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;
2384 int r = 1;
2385 CHECK(fmt, o1);
2386 CHECK(fmt, o2);
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);
2393 return r;
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;
2401 int i;
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)
2407 continue;
2408 if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE)
2409 continue;
2410 line = get_assigned_option(fmt, old, fmt->vars[i].name, 0);
2411 if (line) {
2412 char *msg = NULL;
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);
2416 tor_free(msg);
2417 tor_assert(0);
2420 config_free_lines(line);
2422 return newopts;
2425 /** Return a new empty or_options_t. Used for testing. */
2426 or_options_t *
2427 options_new(void)
2429 return config_alloc(&options_format);
2432 /** Set <b>options</b> to hold reasonable defaults for most options.
2433 * Each option defaults to zero. */
2434 void
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
2441 * values. */
2442 static void
2443 config_init(config_format_t *fmt, void *options)
2445 int i;
2446 config_var_t *var;
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.
2461 static char *
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;
2468 char *result;
2469 int i;
2470 const char *desc;
2471 char *msg = NULL;
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.");
2479 tor_free(msg);
2480 tor_assert(0);
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)
2488 continue;
2489 /* Don't save 'hidden' control variables. */
2490 if (!strcmpstart(fmt->vars[i].name, "__"))
2491 continue;
2492 if (minimal && option_is_same(fmt, options, defaults, fmt->vars[i].name))
2493 continue;
2494 else if (comment_defaults &&
2495 option_is_same(fmt, options, defaults, fmt->vars[i].name))
2496 comment_option = 1;
2498 desc = config_find_description(fmt, fmt->vars[i].name);
2499 line = assigned = get_assigned_option(fmt, options, fmt->vars[i].name, 1);
2501 if (line && desc) {
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;
2508 char *tmp;
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");
2514 tor_assert(0);
2516 smartlist_add(elements, tmp);
2518 config_free_lines(assigned);
2521 if (fmt->extra) {
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;
2525 char *tmp;
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");
2529 tor_assert(0);
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);
2539 return result;
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.
2546 static char *
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. */
2555 static int
2556 validate_ports_csv(smartlist_t *sl, const char *name, char **msg)
2558 int i;
2559 char buf[1024];
2560 tor_assert(name);
2562 if (!sl)
2563 return 0;
2565 SMARTLIST_FOREACH(sl, const char *, cp,
2567 i = atoi(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");
2572 return -1;
2575 return 0;
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.
2580 * Else return 0.
2582 static int
2583 ensure_bandwidth_cap(uint64_t *value, const char *desc, char **msg)
2585 int r;
2586 char buf[1024];
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) */
2590 --*value;
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");
2597 return -1;
2599 return 0;
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".
2605 * Treat "0" as "".
2606 * Return 0 on success or -1 if not a recognized authority type (in which
2607 * case the value of _PublishServerDescriptor is undefined). */
2608 static int
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 */
2615 return 0;
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;
2622 else
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"))
2633 /* no authority */;
2634 else
2635 return -1;
2637 return 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
2650 * <b>options</b>.
2652 * On error, tor_strdup an error explanation into *<b>msg</b>.
2654 * XXX
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.
2659 static int
2660 options_validate(or_options_t *old_options, or_options_t *options,
2661 int from_setconf, char **msg)
2663 int i, r;
2664 config_line_t *cl;
2665 const char *uname = get_uname();
2666 char buf[1024];
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
2671 tor_assert(msg);
2672 *msg = NULL;
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;
2712 const char *tp;
2713 if (is_socks) {
2714 opt = options->SocksListenAddress;
2715 old = old_options ? old_options->SocksListenAddress : NULL;
2716 tp = "SOCKS proxy";
2717 } else if (is_trans) {
2718 opt = options->TransListenAddress;
2719 old = old_options ? old_options->TransListenAddress : NULL;
2720 tp = "transparent proxy";
2721 } else {
2722 opt = options->NatdListenAddress;
2723 old = old_options ? old_options->NatdListenAddress : NULL;
2724 tp = "natd proxy";
2727 for (line = opt; line; line = line->next) {
2728 char *address = NULL;
2729 uint16_t port;
2730 uint32_t addr;
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))) {
2735 log_warn(LD_CONFIG,
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);
2741 tor_free(address);
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);
2754 } else {
2755 log_notice(LD_CONFIG, "Choosing default nickname '%s'",
2756 options->Nickname);
2759 } else {
2760 if (!is_legal_nickname(options->Nickname)) {
2761 r = tor_snprintf(buf, sizeof(buf),
2762 "Nickname '%s' is wrong length or contains illegal characters.",
2763 options->Nickname);
2764 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2765 return -1;
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,
2785 tor_free(s));
2786 smartlist_clear(options->PublishServerDescriptor);
2789 if (authdir_mode(options)) {
2790 /* confirm that our address isn't broken, so we can complain now */
2791 uint32_t tmp;
2792 if (resolve_my_address(LOG_WARN, options, &tmp, NULL) < 0)
2793 REJECT("Failed to resolve/guess local address. See logs for details.");
2796 #ifndef MS_WINDOWS
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.");
2799 #endif
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.");
2830 #endif
2832 if (options->StrictExitNodes &&
2833 (!options->ExitNodes || !strlen(options->ExitNodes)) &&
2834 (!old_options ||
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)) &&
2841 (!old_options ||
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)AuthoriativeDir 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");
2899 return -1;
2902 if (validate_ports_csv(options->FirewallPorts, "FirewallPorts", msg) < 0)
2903 return -1;
2905 if (validate_ports_csv(options->LongLivedPorts, "LongLivedPorts", msg) < 0)
2906 return -1;
2908 if (validate_ports_csv(options->RejectPlaintextPorts,
2909 "RejectPlaintextPorts", msg) < 0)
2910 return -1;
2912 if (validate_ports_csv(options->WarnPlaintextPorts,
2913 "WarnPlaintextPorts", msg) < 0)
2914 return -1;
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
2925 * open ports. */
2926 SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
2928 int p = atoi(portno);
2929 char *s;
2930 if (p<0) continue;
2931 s = tor_malloc(16);
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\"",
2940 new_line->value);
2941 options->ReachableAddresses = new_line;
2942 SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
2943 smartlist_free(instead);
2944 } else {
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;
2971 if (!*linep)
2972 continue;
2973 /* We need to end with a reject *:*, not an implicit accept *:* */
2974 for (;;) {
2975 if (!strcmp((*linep)->value, "reject *:*")) /* already there */
2976 break;
2977 linep = &((*linep)->next);
2978 if (!*linep) {
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 *:*");
2985 break;
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;
3016 else {
3017 r = tor_snprintf(buf, sizeof(buf),
3018 "Unrecognized value '%s' in AllowInvalidNodes", cp);
3019 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3020 return -1;
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");
3029 return -1;
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.",
3046 MAX_DIR_PERIOD);
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)
3055 return -1;
3056 if (ensure_bandwidth_cap(&options->BandwidthBurst,
3057 "BandwidthBurst", msg) < 0)
3058 return -1;
3059 if (ensure_bandwidth_cap(&options->MaxAdvertisedBandwidth,
3060 "MaxAdvertisedBandwidth", msg) < 0)
3061 return -1;
3062 if (ensure_bandwidth_cap(&options->RelayBandwidthRate,
3063 "RelayBandwidthRate", msg) < 0)
3064 return -1;
3065 if (ensure_bandwidth_cap(&options->RelayBandwidthBurst,
3066 "RelayBandwidthBurst", msg) < 0)
3067 return -1;
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");
3077 return -1;
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");
3086 return -1;
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");
3096 return -1;
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);
3143 if (!sl) {
3144 REJECT("Bad HashedControlPassword: wrong length or bad encoding");
3145 } else {
3146 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3147 smartlist_free(sl);
3151 if (options->ControlListenAddress) {
3152 int all_are_local = 1;
3153 config_line_t *ln;
3154 for (ln = options->ControlListenAddress; ln; ln = ln->next) {
3155 if (strcmpstart(ln->value, "127."))
3156 all_are_local = 0;
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;
3165 } else {
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))
3186 return -1;
3187 if (check_nickname_list(options->EntryNodes, "EntryNodes", msg))
3188 return -1;
3189 if (check_nickname_list(options->ExcludeNodes, "ExcludeNodes", msg))
3190 return -1;
3191 if (check_nickname_list(options->RendNodes, "RendNodes", msg))
3192 return -1;
3193 if (check_nickname_list(options->RendNodes, "RendExcludeNodes", msg))
3194 return -1;
3195 if (check_nickname_list(options->TestVia, "TestVia", msg))
3196 return -1;
3197 if (check_nickname_list(options->MyFamily, "MyFamily", msg))
3198 return -1;
3199 for (cl = options->NodeFamilies; cl; cl = cl->next) {
3200 if (check_nickname_list(cl->value, "NodeFamily", msg))
3201 return -1;
3204 if (validate_addr_policies(options, msg) < 0)
3205 return -1;
3207 for (cl = options->RedirectExit; cl; cl = cl->next) {
3208 if (parse_redirect_line(NULL, cl, msg)<0)
3209 return -1;
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");
3237 return -1;
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)
3274 return -1;
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] == '.')
3284 suf[len-1] = '\0';
3288 return 0;
3289 #undef REJECT
3290 #undef COMPLAIN
3293 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
3294 * equal strings. */
3295 static int
3296 opt_streq(const char *s1, const char *s2)
3298 if (!s1 && !s2)
3299 return 1;
3300 else if (s1 && s2 && !strcmp(s1,s2))
3301 return 1;
3302 else
3303 return 0;
3306 /** Check if any of the previous options have changed but aren't allowed to. */
3307 static int
3308 options_transition_allowed(or_options_t *old, or_options_t *new_val,
3309 char **msg)
3311 if (!old)
3312 return 0;
3314 if (!opt_streq(old->PidFile, new_val->PidFile)) {
3315 *msg = tor_strdup("PidFile is not allowed to change.");
3316 return -1;
3319 if (old->RunAsDaemon != new_val->RunAsDaemon) {
3320 *msg = tor_strdup("While Tor is running, changing RunAsDaemon "
3321 "is not allowed.");
3322 return -1;
3325 if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
3326 char buf[1024];
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");
3332 return -1;
3335 if (!opt_streq(old->User, new_val->User)) {
3336 *msg = tor_strdup("While Tor is running, changing User is not allowed.");
3337 return -1;
3340 if (!opt_streq(old->Group, new_val->Group)) {
3341 *msg = tor_strdup("While Tor is running, changing Group is not allowed.");
3342 return -1;
3345 if (old->HardwareAccel != new_val->HardwareAccel) {
3346 *msg = tor_strdup("While Tor is running, changing HardwareAccel is "
3347 "not allowed.");
3348 return -1;
3351 return 0;
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. */
3356 static int
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))
3368 return 1;
3370 /* Check whether log options match. */
3372 /* Nothing that changed matters. */
3373 return 0;
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. */
3378 static int
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)
3400 return 1;
3402 return 0;
3405 #ifdef MS_WINDOWS
3406 /** Return the directory on windows where we expect to find our application
3407 * data. */
3408 static char *
3409 get_windows_conf_root(void)
3411 static int is_set = 0;
3412 static char path[MAX_PATH+1];
3414 LPITEMIDLIST idl;
3415 IMalloc *m;
3416 HRESULT result;
3418 if (is_set)
3419 return path;
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,
3425 &idl))) {
3426 GetCurrentDirectory(MAX_PATH, path);
3427 is_set = 1;
3428 log_warn(LD_CONFIG,
3429 "I couldn't find your application data folder: are you "
3430 "running an ancient version of Windows 95? Defaulting to \"%s\"",
3431 path);
3432 return path;
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 */
3437 SHGetMalloc(&m);
3438 if (m) {
3439 m->lpVtbl->Free(m, idl);
3440 m->lpVtbl->Release(m);
3442 if (!SUCCEEDED(result)) {
3443 return NULL;
3445 strlcat(path,"\\tor",MAX_PATH);
3446 is_set = 1;
3447 return path;
3449 #endif
3451 /** Return the default location for our torrc file. */
3452 static const char *
3453 get_default_conf_file(void)
3455 #ifdef MS_WINDOWS
3456 static char path[MAX_PATH+1];
3457 strlcpy(path, get_windows_conf_root(), MAX_PATH);
3458 strlcat(path,"\\torrc",MAX_PATH);
3459 return path;
3460 #else
3461 return (CONFDIR "/torrc");
3462 #endif
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.
3468 static int
3469 check_nickname_list(const char *lst, const char *name, char **msg)
3471 int r = 0;
3472 smartlist_t *sl;
3474 if (!lst)
3475 return 0;
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)) {
3481 char buf[1024];
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");
3485 r = -1;
3486 break;
3489 SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
3490 smartlist_free(sl);
3491 return r;
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;
3502 config_line_t *cl;
3503 char *cf=NULL, *fname=NULL, *errmsg=NULL;
3504 int i, retval;
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 */
3511 backup_argv = argv;
3512 backup_argc = argc;
3513 oldoptions = NULL;
3514 } else { /* we're reloading. need to clean up old options first. */
3515 argv = backup_argv;
3516 argc = backup_argc;
3517 oldoptions = get_options();
3519 if (argc > 1 && (!strcmp(argv[1], "-h") || !strcmp(argv[1],"--help"))) {
3520 print_usage();
3521 exit(0);
3523 if (argc > 1 && !strcmp(argv[1], "--list-torrc-options")) {
3524 /* For documenting validating whether we've documented everything. */
3525 list_torrc_options();
3526 exit(0);
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();
3534 exit(0);
3537 newoptions = tor_malloc_zero(sizeof(or_options_t));
3538 newoptions->_magic = OR_OPTIONS_MAGIC;
3539 options_init(newoptions);
3541 /* learn config file name */
3542 fname = NULL;
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")) {
3548 if (fname) {
3549 log(LOG_WARN, LD_CONFIG, "Duplicate -f options on command line.");
3550 tor_free(fname);
3552 #ifdef MS_WINDOWS
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]);
3556 #else
3557 fname = expand_filename(argv[i+1]);
3558 #endif
3559 using_default_torrc = 0;
3560 ++i;
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] : "");
3568 ++i;
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);
3578 } else {
3579 #ifndef MS_WINDOWS
3580 char *fn;
3581 fn = expand_filename("~/.torrc");
3582 if (fn && file_status(fn) == FN_FILE) {
3583 fname = fn;
3584 } else {
3585 tor_free(fn);
3586 fname = tor_strdup(dflt);
3588 #else
3589 fname = tor_strdup(dflt);
3590 #endif
3593 tor_assert(fname);
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 */
3606 torrc_fname = NULL;
3607 } else {
3608 log(LOG_WARN, LD_CONFIG,
3609 "Unable to open configuration file \"%s\".", fname);
3610 goto err;
3612 } else { /* it opened successfully. use it. */
3613 retval = config_get_lines(cf, &cl);
3614 tor_free(cf);
3615 if (retval < 0)
3616 goto err;
3617 retval = config_assign(&options_format, newoptions, cl, 0, 0, &errmsg);
3618 config_free_lines(cl);
3619 if (retval < 0)
3620 goto err;
3623 /* Go through command-line variables too */
3624 if (config_get_commandlines(argc, argv, &cl) < 0)
3625 goto err;
3626 retval = config_assign(&options_format, newoptions, cl, 0, 0, &errmsg);
3627 config_free_lines(cl);
3628 if (retval < 0)
3629 goto err;
3631 /* Validate newoptions */
3632 if (options_validate(oldoptions, newoptions, 0, &errmsg) < 0)
3633 goto err;
3635 if (options_transition_allowed(oldoptions, newoptions, &errmsg) < 0)
3636 goto err;
3638 if (set_options(newoptions, &errmsg))
3639 goto err; /* frees and replaces old options */
3641 return 0;
3642 err:
3643 tor_free(fname);
3644 torrc_fname = NULL;
3645 config_free(&options_format, newoptions);
3646 if (errmsg) {
3647 log(LOG_WARN,LD_CONFIG,"Failed to parse/validate config: %s", errmsg);
3648 tor_free(errmsg);
3650 return -1;
3653 /** Return the location for our configuration file.
3655 const char *
3656 get_torrc_fname(void)
3658 if (torrc_fname)
3659 return torrc_fname;
3660 else
3661 return get_default_conf_file();
3664 /** Adjust the address map mased on the MapAddress elements in the
3665 * configuration <b>options</b>
3667 static void
3668 config_register_addressmaps(or_options_t *options)
3670 smartlist_t *elts;
3671 config_line_t *opt;
3672 char *from, *to;
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)) {
3683 log_warn(LD_CONFIG,
3684 "Skipping invalid argument '%s' to MapAddress", to);
3685 } else {
3686 addressmap_register(from, tor_strdup(to), 0);
3687 if (smartlist_len(elts)>2) {
3688 log_warn(LD_CONFIG,"Ignoring extra arguments to MapAddress.");
3691 } else {
3692 log_warn(LD_CONFIG,"MapAddress '%s' has too few arguments. Ignoring.",
3693 opt->value);
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
3705 * return -1.
3707 static int
3708 parse_log_severity_range(const char *range, int *min_out, int *max_out)
3710 int levelMin, levelMax;
3711 const char *cp;
3712 cp = strchr(range, '-');
3713 if (cp) {
3714 if (cp == range) {
3715 levelMin = LOG_DEBUG;
3716 } else {
3717 char *tmp_sev = tor_strndup(range, cp - range);
3718 levelMin = parse_log_level(tmp_sev);
3719 if (levelMin < 0) {
3720 log_warn(LD_CONFIG, "Unrecognized minimum log severity '%s': must be "
3721 "one of err|warn|notice|info|debug", tmp_sev);
3722 tor_free(tmp_sev);
3723 return -1;
3725 tor_free(tmp_sev);
3727 if (!*(cp+1)) {
3728 levelMax = LOG_ERR;
3729 } else {
3730 levelMax = parse_log_level(cp+1);
3731 if (levelMax < 0) {
3732 log_warn(LD_CONFIG, "Unrecognized maximum log severity '%s': must be "
3733 "one of err|warn|notice|info|debug", cp+1);
3734 return -1;
3737 } else {
3738 levelMin = parse_log_level(range);
3739 if (levelMin < 0) {
3740 log_warn(LD_CONFIG, "Unrecognized log severity '%s': must be one of "
3741 "err|warn|notice|info|debug", range);
3742 return -1;
3744 levelMax = LOG_ERR;
3747 *min_out = levelMin;
3748 *max_out = levelMax;
3750 return 0;
3754 * Initialize the logs based on the configuration file.
3756 static int
3757 options_init_logs(or_options_t *options, int validate_only)
3759 config_line_t *opt;
3760 int ok;
3761 smartlist_t *elts;
3762 int daemon =
3763 #ifdef MS_WINDOWS
3765 #else
3766 options->RunAsDaemon;
3767 #endif
3769 ok = 1;
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,
3781 &levelMax)) {
3782 ok = 0; goto cleanup;
3784 if (smartlist_len(elts) < 2) { /* only loglevels were provided */
3785 if (!validate_only) {
3786 if (daemon) {
3787 log_warn(LD_CONFIG,
3788 "Can't log to stdout with RunAsDaemon set; skipping stdout");
3789 } else {
3790 add_stream_log(levelMin, levelMax, "<stdout>", stdout);
3793 goto cleanup;
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'",
3798 opt->value);
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);
3804 ok = 0;
3807 goto cleanup;
3809 if (smartlist_len(elts) != 2) {
3810 log_warn(LD_CONFIG, "Wrong number of arguments on Log option 'Log %s'",
3811 opt->value);
3812 ok = 0; goto cleanup;
3814 if (!strcasecmp(smartlist_get(elts,1), "stdout")) {
3815 if (daemon) {
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")) {
3823 if (daemon) {
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
3832 if (!validate_only)
3833 add_syslog_log(levelMin, levelMax);
3834 #else
3835 log_warn(LD_CONFIG, "Syslog is not supported on this system. Sorry.");
3836 #endif
3837 } else {
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;
3848 cleanup:
3849 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
3850 smartlist_clear(elts);
3852 smartlist_free(elts);
3854 return ok?0:-1;
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. */
3861 static int
3862 parse_redirect_line(smartlist_t *result, config_line_t *line, char **msg)
3864 smartlist_t *elements = NULL;
3865 exit_redirect_t *r;
3867 tor_assert(line);
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");
3875 goto err;
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");
3880 goto err;
3882 if (0==strcasecmp(smartlist_get(elements,1), "pass")) {
3883 r->is_redirect = 0;
3884 } else {
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");
3888 goto err;
3890 r->is_redirect = 1;
3893 goto done;
3894 err:
3895 tor_free(r);
3896 done:
3897 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
3898 smartlist_free(elements);
3899 if (r) {
3900 if (result)
3901 smartlist_add(result, r);
3902 else
3903 tor_free(r);
3904 return 0;
3905 } else {
3906 tor_assert(*msg);
3907 return -1;
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. */
3915 static int
3916 parse_bridge_line(const char *line, int validate_only)
3918 smartlist_t *items = NULL;
3919 int r;
3920 char *addrport=NULL, *address=NULL, *fingerprint=NULL;
3921 uint32_t addr = 0;
3922 uint16_t port = 0;
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.");
3930 goto err;
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);
3936 goto err;
3938 if (!port) {
3939 log_warn(LD_CONFIG, "Missing port in Bridge address '%s'",addrport);
3940 goto err;
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.");
3947 goto err;
3949 if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
3950 log_warn(LD_CONFIG, "Unable to decode Bridge key digest.");
3951 goto err;
3955 if (!validate_only) {
3956 log_debug(LD_DIR, "Bridge at %s:%d (%s)", address,
3957 (int)port,
3958 fingerprint ? fingerprint : "no key listed");
3959 bridge_add_from_config(addr, port, fingerprint ? digest : NULL);
3962 r = 0;
3963 goto done;
3965 err:
3966 r = -1;
3968 done:
3969 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
3970 smartlist_free(items);
3971 tor_free(addrport);
3972 tor_free(address);
3973 tor_free(fingerprint);
3974 return r;
3977 /** Read the contents of a DirServer line from <b>line</b>. Return 0
3978 * if the line is well-formed, and -1 if it isn't. If
3979 * <b>validate_only</b> is 0, and the line is well-formed, and it
3980 * shares any bits with <b>required_type</b> or <b>required_type</b>
3981 * is 0, then add the dirserver described in the line (minus whatever
3982 * bits it's missing) as a valid authority. */
3983 static int
3984 parse_dir_server_line(const char *line, authority_type_t required_type,
3985 int validate_only)
3987 smartlist_t *items = NULL;
3988 int r;
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.");
4001 goto err;
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]))
4012 break;
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=")) {
4024 int ok;
4025 char *portstring = flag + strlen("orport=");
4026 or_port = (uint16_t) tor_parse_long(portstring, 10, 1, 65535, &ok, NULL);
4027 if (!ok)
4028 log_warn(LD_CONFIG, "Invalid orport '%s' on DirServer line.",
4029 portstring);
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",
4035 flag);
4036 } else {
4037 type |= V3_AUTHORITY;
4039 } else {
4040 log_warn(LD_CONFIG, "Unrecognized flag '%s' on DirServer line",
4041 flag);
4043 tor_free(flag);
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.");
4053 goto err;
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);
4059 goto err;
4061 if (!dir_port) {
4062 log_warn(LD_CONFIG, "Missing port in DirServer address '%s'",addrport);
4063 goto err;
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));
4070 goto err;
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.",
4077 get_torrc_fname());
4078 goto err;
4080 if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
4081 log_warn(LD_CONFIG, "Unable to decode DirServer key digest.");
4082 goto err;
4085 if (!validate_only && (!required_type || required_type & type)) {
4086 if (required_type)
4087 type &= required_type; /* pare down what we think of them as an
4088 * authority for. */
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 add_trusted_dir_server(nickname, address, dir_port, or_port, digest,
4092 v3_digest, type);
4095 r = 0;
4096 goto done;
4098 err:
4099 r = -1;
4101 done:
4102 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4103 smartlist_free(items);
4104 tor_free(addrport);
4105 tor_free(address);
4106 tor_free(nickname);
4107 tor_free(fingerprint);
4108 return r;
4111 /** Adjust the value of options->DataDirectory, or fill it in if it's
4112 * absent. Return 0 on success, -1 on failure. */
4113 static int
4114 normalize_data_directory(or_options_t *options)
4116 #ifdef MS_WINDOWS
4117 char *p;
4118 if (options->DataDirectory)
4119 return 0; /* all set */
4120 p = tor_malloc(MAX_PATH);
4121 strlcpy(p,get_windows_conf_root(),MAX_PATH);
4122 options->DataDirectory = p;
4123 return 0;
4124 #else
4125 const char *d = options->DataDirectory;
4126 if (!d)
4127 d = "~/.tor";
4129 if (strncmp(d,"~/",2) == 0) {
4130 char *fn = expand_filename(d);
4131 if (!fn) {
4132 log_warn(LD_CONFIG,"Failed to expand filename \"%s\".", d);
4133 return -1;
4135 if (!options->DataDirectory && !strcmp(fn,"/.tor")) {
4136 /* If our homedir is /, we probably don't want to use it. */
4137 /* Default to LOCALSTATEDIR/tor which is probably closer to what we
4138 * want. */
4139 log_warn(LD_CONFIG,
4140 "Default DataDirectory is \"~/.tor\". This expands to "
4141 "\"%s\", which is probably not what you want. Using "
4142 "\"%s"PATH_SEPARATOR"tor\" instead", fn, LOCALSTATEDIR);
4143 tor_free(fn);
4144 fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor");
4146 tor_free(options->DataDirectory);
4147 options->DataDirectory = fn;
4149 return 0;
4150 #endif
4153 /** Check and normalize the value of options->DataDirectory; return 0 if it
4154 * sane, -1 otherwise. */
4155 static int
4156 validate_data_directory(or_options_t *options)
4158 if (normalize_data_directory(options) < 0)
4159 return -1;
4160 tor_assert(options->DataDirectory);
4161 if (strlen(options->DataDirectory) > (512-128)) {
4162 log_warn(LD_CONFIG, "DataDirectory is too long.");
4163 return -1;
4165 return 0;
4168 /** This string must remain the same forevermore. It is how we
4169 * recognize that the torrc file doesn't need to be backed up. */
4170 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
4171 "if you edit it, comments will not be preserved"
4172 /** This string can change; it tries to give the reader an idea
4173 * that editing this file by hand is not a good plan. */
4174 #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
4175 "to torrc.orig.1 or similar, and Tor will ignore it"
4177 /** Save a configuration file for the configuration in <b>options</b>
4178 * into the file <b>fname</b>. If the file already exists, and
4179 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
4180 * replace it. Return 0 on success, -1 on failure. */
4181 static int
4182 write_configuration_file(const char *fname, or_options_t *options)
4184 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
4185 int rename_old = 0, r;
4186 size_t len;
4188 if (fname) {
4189 switch (file_status(fname)) {
4190 case FN_FILE:
4191 old_val = read_file_to_str(fname, 0, NULL);
4192 if (strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
4193 rename_old = 1;
4195 tor_free(old_val);
4196 break;
4197 case FN_NOENT:
4198 break;
4199 case FN_ERROR:
4200 case FN_DIR:
4201 default:
4202 log_warn(LD_CONFIG,
4203 "Config file \"%s\" is not a file? Failing.", fname);
4204 return -1;
4208 if (!(new_conf = options_dump(options, 1))) {
4209 log_warn(LD_BUG, "Couldn't get configuration string");
4210 goto err;
4213 len = strlen(new_conf)+256;
4214 new_val = tor_malloc(len);
4215 tor_snprintf(new_val, len, "%s\n%s\n\n%s",
4216 GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
4218 if (rename_old) {
4219 int i = 1;
4220 size_t fn_tmp_len = strlen(fname)+32;
4221 char *fn_tmp;
4222 tor_assert(fn_tmp_len > strlen(fname)); /*check for overflow*/
4223 fn_tmp = tor_malloc(fn_tmp_len);
4224 while (1) {
4225 if (tor_snprintf(fn_tmp, fn_tmp_len, "%s.orig.%d", fname, i)<0) {
4226 log_warn(LD_BUG, "tor_snprintf failed inexplicably");
4227 tor_free(fn_tmp);
4228 goto err;
4230 if (file_status(fn_tmp) == FN_NOENT)
4231 break;
4232 ++i;
4234 log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
4235 if (rename(fname, fn_tmp) < 0) {
4236 log_warn(LD_FS,
4237 "Couldn't rename configuration file \"%s\" to \"%s\": %s",
4238 fname, fn_tmp, strerror(errno));
4239 tor_free(fn_tmp);
4240 goto err;
4242 tor_free(fn_tmp);
4245 if (write_str_to_file(fname, new_val, 0) < 0)
4246 goto err;
4248 r = 0;
4249 goto done;
4250 err:
4251 r = -1;
4252 done:
4253 tor_free(new_val);
4254 tor_free(new_conf);
4255 return r;
4259 * Save the current configuration file value to disk. Return 0 on
4260 * success, -1 on failure.
4263 options_save_current(void)
4265 if (torrc_fname) {
4266 /* This fails if we can't write to our configuration file.
4268 * If we try falling back to datadirectory or something, we have a better
4269 * chance of saving the configuration, but a better chance of doing
4270 * something the user never expected. Let's just warn instead. */
4271 return write_configuration_file(torrc_fname, get_options());
4273 return write_configuration_file(get_default_conf_file(), get_options());
4276 /** Mapping from a unit name to a multiplier for converting that unit into a
4277 * base unit. */
4278 struct unit_table_t {
4279 const char *unit;
4280 uint64_t multiplier;
4283 static struct unit_table_t memory_units[] = {
4284 { "", 1 },
4285 { "b", 1<< 0 },
4286 { "byte", 1<< 0 },
4287 { "bytes", 1<< 0 },
4288 { "kb", 1<<10 },
4289 { "kbyte", 1<<10 },
4290 { "kbytes", 1<<10 },
4291 { "kilobyte", 1<<10 },
4292 { "kilobytes", 1<<10 },
4293 { "m", 1<<20 },
4294 { "mb", 1<<20 },
4295 { "mbyte", 1<<20 },
4296 { "mbytes", 1<<20 },
4297 { "megabyte", 1<<20 },
4298 { "megabytes", 1<<20 },
4299 { "gb", 1<<30 },
4300 { "gbyte", 1<<30 },
4301 { "gbytes", 1<<30 },
4302 { "gigabyte", 1<<30 },
4303 { "gigabytes", 1<<30 },
4304 { "tb", U64_LITERAL(1)<<40 },
4305 { "terabyte", U64_LITERAL(1)<<40 },
4306 { "terabytes", U64_LITERAL(1)<<40 },
4307 { NULL, 0 },
4310 static struct unit_table_t time_units[] = {
4311 { "", 1 },
4312 { "second", 1 },
4313 { "seconds", 1 },
4314 { "minute", 60 },
4315 { "minutes", 60 },
4316 { "hour", 60*60 },
4317 { "hours", 60*60 },
4318 { "day", 24*60*60 },
4319 { "days", 24*60*60 },
4320 { "week", 7*24*60*60 },
4321 { "weeks", 7*24*60*60 },
4322 { NULL, 0 },
4325 /** Parse a string <b>val</b> containing a number, zero or more
4326 * spaces, and an optional unit string. If the unit appears in the
4327 * table <b>u</b>, then multiply the number by the unit multiplier.
4328 * On success, set *<b>ok</b> to 1 and return this product.
4329 * Otherwise, set *<b>ok</b> to 0.
4331 static uint64_t
4332 config_parse_units(const char *val, struct unit_table_t *u, int *ok)
4334 uint64_t v;
4335 char *cp;
4337 tor_assert(ok);
4339 v = tor_parse_uint64(val, 10, 0, UINT64_MAX, ok, &cp);
4340 if (!*ok)
4341 return 0;
4342 if (!cp) {
4343 *ok = 1;
4344 return v;
4346 while (TOR_ISSPACE(*cp))
4347 ++cp;
4348 for ( ;u->unit;++u) {
4349 if (!strcasecmp(u->unit, cp)) {
4350 v *= u->multiplier;
4351 *ok = 1;
4352 return v;
4355 log_warn(LD_CONFIG, "Unknown unit '%s'.", cp);
4356 *ok = 0;
4357 return 0;
4360 /** Parse a string in the format "number unit", where unit is a unit of
4361 * information (byte, KB, M, etc). On success, set *<b>ok</b> to true
4362 * and return the number of bytes specified. Otherwise, set
4363 * *<b>ok</b> to false and return 0. */
4364 static uint64_t
4365 config_parse_memunit(const char *s, int *ok)
4367 return config_parse_units(s, memory_units, ok);
4370 /** Parse a string in the format "number unit", where unit is a unit of time.
4371 * On success, set *<b>ok</b> to true and return the number of seconds in
4372 * the provided interval. Otherwise, set *<b>ok</b> to 0 and return -1.
4374 static int
4375 config_parse_interval(const char *s, int *ok)
4377 uint64_t r;
4378 r = config_parse_units(s, time_units, ok);
4379 if (!ok)
4380 return -1;
4381 if (r > INT_MAX) {
4382 log_warn(LD_CONFIG, "Interval '%s' is too long", s);
4383 *ok = 0;
4384 return -1;
4386 return (int)r;
4390 * Initialize the libevent library.
4392 static void
4393 init_libevent(void)
4395 configure_libevent_logging();
4396 /* If the kernel complains that some method (say, epoll) doesn't
4397 * exist, we don't care about it, since libevent will cope.
4399 suppress_libevent_log_msg("Function not implemented");
4400 #ifdef __APPLE__
4401 if (decode_libevent_version() < LE_11B) {
4402 setenv("EVENT_NOKQUEUE","1",1);
4404 #endif
4405 event_init();
4406 suppress_libevent_log_msg(NULL);
4407 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
4408 /* Making this a NOTICE for now so we can link bugs to a libevent versions
4409 * or methods better. */
4410 log(LOG_NOTICE, LD_GENERAL,
4411 "Initialized libevent version %s using method %s. Good.",
4412 event_get_version(), event_get_method());
4413 check_libevent_version(event_get_method(), get_options()->ORPort != 0);
4414 #else
4415 log(LOG_NOTICE, LD_GENERAL,
4416 "Initialized old libevent (version 1.0b or earlier).");
4417 log(LOG_WARN, LD_GENERAL,
4418 "You have a *VERY* old version of libevent. It is likely to be buggy; "
4419 "please build Tor with a more recent version.");
4420 #endif
4423 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
4424 /** Table mapping return value of event_get_version() to le_version_t. */
4425 static const struct {
4426 const char *name; le_version_t version;
4427 } le_version_table[] = {
4428 /* earlier versions don't have get_version. */
4429 { "1.0c", LE_10C },
4430 { "1.0d", LE_10D },
4431 { "1.0e", LE_10E },
4432 { "1.1", LE_11 },
4433 { "1.1a", LE_11A },
4434 { "1.1b", LE_11B },
4435 { "1.2", LE_12 },
4436 { "1.2a", LE_12A },
4437 { "1.3", LE_13 },
4438 { "1.3a", LE_13A },
4439 { "1.3b", LE_13B },
4440 { "1.3c", LE_13C },
4441 { "1.3d", LE_13D },
4442 { NULL, LE_OTHER }
4445 /** Return the le_version_t for the current version of libevent. If the
4446 * version is very new, return LE_OTHER. If the version is so old that it
4447 * doesn't support event_get_version(), return LE_OLD. */
4448 static le_version_t
4449 decode_libevent_version(void)
4451 const char *v = event_get_version();
4452 int i;
4453 for (i=0; le_version_table[i].name; ++i) {
4454 if (!strcmp(le_version_table[i].name, v)) {
4455 return le_version_table[i].version;
4458 return LE_OTHER;
4462 * Compare the given libevent method and version to a list of versions
4463 * which are known not to work. Warn the user as appropriate.
4465 static void
4466 check_libevent_version(const char *m, int server)
4468 int buggy = 0, iffy = 0, slow = 0, thread_unsafe = 0;
4469 le_version_t version;
4470 const char *v = event_get_version();
4471 const char *badness = NULL;
4472 const char *sad_os = "";
4474 version = decode_libevent_version();
4476 /* XXX Would it be worthwhile disabling the methods that we know
4477 * are buggy, rather than just warning about them and then proceeding
4478 * to use them? If so, we should probably not wrap this whole thing
4479 * in HAVE_EVENT_GET_VERSION and HAVE_EVENT_GET_METHOD. -RD */
4480 /* XXXX The problem is that it's not trivial to get libevent to change it's
4481 * method once it's initialized, and it's not trivial to tell what method it
4482 * will use without initializing it. I guess we could preemptively disable
4483 * buggy libevent modes based on the version _before_ initializing it,
4484 * though, but then there's no good way (afaict) to warn "I would have used
4485 * kqueue, but instead I'm using select." -NM */
4486 if (!strcmp(m, "kqueue")) {
4487 if (version < LE_11B)
4488 buggy = 1;
4489 } else if (!strcmp(m, "epoll")) {
4490 if (version < LE_11)
4491 iffy = 1;
4492 } else if (!strcmp(m, "poll")) {
4493 if (version < LE_10E)
4494 buggy = 1;
4495 else if (version < LE_11)
4496 slow = 1;
4497 } else if (!strcmp(m, "select")) {
4498 if (version < LE_11)
4499 slow = 1;
4500 } else if (!strcmp(m, "win32")) {
4501 if (version < LE_11B)
4502 buggy = 1;
4505 /* Libevent versions before 1.3b do very badly on operating systems with
4506 * user-space threading implementations. */
4507 #if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__)
4508 if (server && version < LE_13B) {
4509 thread_unsafe = 1;
4510 sad_os = "BSD variants";
4512 #elif defined(__APPLE__) || defined(__darwin__)
4513 if (server && version < LE_13B) {
4514 thread_unsafe = 1;
4515 sad_os = "Mac OS X";
4517 #endif
4519 if (thread_unsafe) {
4520 log(LOG_WARN, LD_GENERAL,
4521 "Libevent version %s often crashes when running a Tor server with %s. "
4522 "Please use the latest version of libevent (1.3b or later)",v,sad_os);
4523 badness = "BROKEN";
4524 } else if (buggy) {
4525 log(LOG_WARN, LD_GENERAL,
4526 "There are serious bugs in using %s with libevent %s. "
4527 "Please use the latest version of libevent.", m, v);
4528 badness = "BROKEN";
4529 } else if (iffy) {
4530 log(LOG_WARN, LD_GENERAL,
4531 "There are minor bugs in using %s with libevent %s. "
4532 "You may want to use the latest version of libevent.", m, v);
4533 badness = "BUGGY";
4534 } else if (slow && server) {
4535 log(LOG_WARN, LD_GENERAL,
4536 "libevent %s can be very slow with %s. "
4537 "When running a server, please use the latest version of libevent.",
4538 v,m);
4539 badness = "SLOW";
4541 if (badness) {
4542 control_event_general_status(LOG_WARN,
4543 "BAD_LIBEVENT VERSION=%s METHOD=%s BADNESS=%s RECOVERED=NO",
4544 v, m, badness);
4548 #else
4549 static le_version_t
4550 decode_libevent_version(void)
4552 return LE_OLD;
4554 #endif
4556 /** Return the persistent state struct for this Tor. */
4557 or_state_t *
4558 get_or_state(void)
4560 tor_assert(global_state);
4561 return global_state;
4564 /** Return a newly allocated string holding a filename relative to the data
4565 * directory. If <b>sub1</b> is present, it is the first path component after
4566 * the data directory. If <b>sub2</b> is also present, it is the second path
4567 * component after the data directory. If <b>suffix</b> is present, it
4568 * is appended to the filename.
4570 * Examples:
4571 * get_datadir_fname2_suffix("a", NULL, NULL) -> $DATADIR/a
4572 * get_datadir_fname2_suffix("a", NULL, ".tmp") -> $DATADIR/a.tmp
4573 * get_datadir_fname2_suffix("a", "b", ".tmp") -> $DATADIR/a/b/.tmp
4574 * get_datadir_fname2_suffix("a", "b", NULL) -> $DATADIR/a/b
4576 * Note: Consider using the get_datadir_fname* macros in or.h.
4578 char *
4579 get_datadir_fname2_suffix(const char *sub1, const char *sub2,
4580 const char *suffix)
4582 or_options_t *options = get_options();
4583 char *fname = NULL;
4584 size_t len;
4585 tor_assert(options);
4586 tor_assert(options->DataDirectory);
4587 tor_assert(sub1 || !sub2); /* If sub2 is present, sub1 must be present. */
4588 len = strlen(options->DataDirectory);
4589 if (sub1) {
4590 len += strlen(sub1)+1;
4591 if (sub2)
4592 len += strlen(sub2)+1;
4594 if (suffix)
4595 len += strlen(suffix);
4596 len++;
4597 fname = tor_malloc(len);
4598 if (sub1) {
4599 if (sub2) {
4600 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s",
4601 options->DataDirectory, sub1, sub2);
4602 } else {
4603 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s",
4604 options->DataDirectory, sub1);
4606 } else {
4607 strlcpy(fname, options->DataDirectory, len);
4609 if (suffix)
4610 strlcat(fname, suffix, len);
4611 return fname;
4614 /** Return 0 if every setting in <b>state</b> is reasonable, and a
4615 * permissible transition from <b>old_state</b>. Else warn and return -1.
4616 * Should have no side effects, except for normalizing the contents of
4617 * <b>state</b>.
4619 /* XXX from_setconf is here because of bug 238 */
4620 static int
4621 or_state_validate(or_state_t *old_state, or_state_t *state,
4622 int from_setconf, char **msg)
4624 /* We don't use these; only options do. Still, we need to match that
4625 * signature. */
4626 (void) from_setconf;
4627 (void) old_state;
4629 if (entry_guards_parse_state(state, 0, msg)<0)
4630 return -1;
4632 return 0;
4635 /** Replace the current persistent state with <b>new_state</b> */
4636 static void
4637 or_state_set(or_state_t *new_state)
4639 char *err = NULL;
4640 tor_assert(new_state);
4641 if (global_state)
4642 config_free(&state_format, global_state);
4643 global_state = new_state;
4644 if (entry_guards_parse_state(global_state, 1, &err)<0) {
4645 log_warn(LD_GENERAL,"%s",err);
4646 tor_free(err);
4648 if (rep_hist_load_state(global_state, &err)<0) {
4649 log_warn(LD_GENERAL,"Unparseable bandwidth history state: %s",err);
4650 tor_free(err);
4654 /** Reload the persistent state from disk, generating a new state as needed.
4655 * Return 0 on success, less than 0 on failure.
4657 static int
4658 or_state_load(void)
4660 or_state_t *new_state = NULL;
4661 char *contents = NULL, *fname;
4662 char *errmsg = NULL;
4663 int r = -1, badstate = 0;
4665 fname = get_datadir_fname("state");
4666 switch (file_status(fname)) {
4667 case FN_FILE:
4668 if (!(contents = read_file_to_str(fname, 0, NULL))) {
4669 log_warn(LD_FS, "Unable to read state file \"%s\"", fname);
4670 goto done;
4672 break;
4673 case FN_NOENT:
4674 break;
4675 case FN_ERROR:
4676 case FN_DIR:
4677 default:
4678 log_warn(LD_GENERAL,"State file \"%s\" is not a file? Failing.", fname);
4679 goto done;
4681 new_state = tor_malloc_zero(sizeof(or_state_t));
4682 new_state->_magic = OR_STATE_MAGIC;
4683 config_init(&state_format, new_state);
4684 if (contents) {
4685 config_line_t *lines=NULL;
4686 int assign_retval;
4687 if (config_get_lines(contents, &lines)<0)
4688 goto done;
4689 assign_retval = config_assign(&state_format, new_state,
4690 lines, 0, 0, &errmsg);
4691 config_free_lines(lines);
4692 if (assign_retval<0)
4693 badstate = 1;
4694 if (errmsg) {
4695 log_warn(LD_GENERAL, "%s", errmsg);
4696 tor_free(errmsg);
4700 if (!badstate && or_state_validate(NULL, new_state, 1, &errmsg) < 0)
4701 badstate = 1;
4703 if (errmsg) {
4704 log_warn(LD_GENERAL, "%s", errmsg);
4705 tor_free(errmsg);
4708 if (badstate && !contents) {
4709 log_warn(LD_BUG, "Uh oh. We couldn't even validate our own default state."
4710 " This is a bug in Tor.");
4711 goto done;
4712 } else if (badstate && contents) {
4713 int i;
4714 file_status_t status;
4715 size_t len = strlen(fname)+16;
4716 char *fname2 = tor_malloc(len);
4717 for (i = 0; i < 100; ++i) {
4718 tor_snprintf(fname2, len, "%s.%d", fname, i);
4719 status = file_status(fname2);
4720 if (status == FN_NOENT)
4721 break;
4723 if (i == 100) {
4724 log_warn(LD_BUG, "Unable to parse state in \"%s\"; too many saved bad "
4725 "state files to move aside. Discarding the old state file.",
4726 fname);
4727 unlink(fname);
4728 } else {
4729 log_warn(LD_BUG, "Unable to parse state in \"%s\". Moving it aside "
4730 "to \"%s\". This could be a bug in Tor; please tell "
4731 "the developers.", fname, fname2);
4732 rename(fname, fname2);
4734 tor_free(fname2);
4735 tor_free(contents);
4736 config_free(&state_format, new_state);
4738 new_state = tor_malloc_zero(sizeof(or_state_t));
4739 new_state->_magic = OR_STATE_MAGIC;
4740 config_init(&state_format, new_state);
4741 } else if (contents) {
4742 log_info(LD_GENERAL, "Loaded state from \"%s\"", fname);
4743 } else {
4744 log_info(LD_GENERAL, "Initialized state");
4746 or_state_set(new_state);
4747 new_state = NULL;
4748 if (!contents) {
4749 global_state->next_write = 0;
4750 or_state_save(time(NULL));
4752 r = 0;
4754 done:
4755 tor_free(fname);
4756 tor_free(contents);
4757 if (new_state)
4758 config_free(&state_format, new_state);
4760 return r;
4763 /** Write the persistent state to disk. Return 0 for success, <0 on failure. */
4765 or_state_save(time_t now)
4767 char *state, *contents;
4768 char tbuf[ISO_TIME_LEN+1];
4769 size_t len;
4770 char *fname;
4772 tor_assert(global_state);
4774 if (global_state->next_write > now)
4775 return 0;
4777 /* Call everything else that might dirty the state even more, in order
4778 * to avoid redundant writes. */
4779 entry_guards_update_state(global_state);
4780 rep_hist_update_state(global_state);
4781 if (accounting_is_enabled(get_options()))
4782 accounting_run_housekeeping(now);
4784 global_state->LastWritten = time(NULL);
4785 tor_free(global_state->TorVersion);
4786 len = strlen(get_version())+8;
4787 global_state->TorVersion = tor_malloc(len);
4788 tor_snprintf(global_state->TorVersion, len, "Tor %s", get_version());
4790 state = config_dump(&state_format, global_state, 1, 0);
4791 len = strlen(state)+256;
4792 contents = tor_malloc(len);
4793 format_local_iso_time(tbuf, time(NULL));
4794 tor_snprintf(contents, len,
4795 "# Tor state file last generated on %s local time\n"
4796 "# Other times below are in GMT\n"
4797 "# You *do not* need to edit this file.\n\n%s",
4798 tbuf, state);
4799 tor_free(state);
4800 fname = get_datadir_fname("state");
4801 if (write_str_to_file(fname, contents, 0)<0) {
4802 log_warn(LD_FS, "Unable to write state to file \"%s\"", fname);
4803 tor_free(fname);
4804 tor_free(contents);
4805 return -1;
4807 log_info(LD_GENERAL, "Saved state to \"%s\"", fname);
4808 tor_free(fname);
4809 tor_free(contents);
4811 global_state->next_write = TIME_MAX;
4812 return 0;
4815 /** Given a file name check to see whether the file exists but has not been
4816 * modified for a very long time. If so, remove it. */
4817 void
4818 remove_file_if_very_old(const char *fname, time_t now)
4820 #define VERY_OLD_FILE_AGE (28*24*60*60)
4821 struct stat st;
4823 if (stat(fname, &st)==0 && st.st_mtime < now-VERY_OLD_FILE_AGE) {
4824 char buf[ISO_TIME_LEN+1];
4825 format_local_iso_time(buf, st.st_mtime);
4826 log_notice(LD_GENERAL, "Obsolete file %s hasn't been modified since %s. "
4827 "Removing it.", fname, buf);
4828 unlink(fname);
4832 /** Helper to implement GETINFO functions about configuration variables (not
4833 * their values). Given a "config/names" question, set *<b>answer</b> to a
4834 * new string describing the supported configuration variables and their
4835 * types. */
4837 getinfo_helper_config(control_connection_t *conn,
4838 const char *question, char **answer)
4840 (void) conn;
4841 if (!strcmp(question, "config/names")) {
4842 smartlist_t *sl = smartlist_create();
4843 int i;
4844 for (i = 0; _option_vars[i].name; ++i) {
4845 config_var_t *var = &_option_vars[i];
4846 const char *type, *desc;
4847 char *line;
4848 size_t len;
4849 desc = config_find_description(&options_format, var->name);
4850 switch (var->type) {
4851 case CONFIG_TYPE_STRING: type = "String"; break;
4852 case CONFIG_TYPE_UINT: type = "Integer"; break;
4853 case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
4854 case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
4855 case CONFIG_TYPE_DOUBLE: type = "Float"; break;
4856 case CONFIG_TYPE_BOOL: type = "Boolean"; break;
4857 case CONFIG_TYPE_ISOTIME: type = "Time"; break;
4858 case CONFIG_TYPE_CSV: type = "CommaList"; break;
4859 case CONFIG_TYPE_LINELIST: type = "LineList"; break;
4860 case CONFIG_TYPE_LINELIST_S: type = "Dependant"; break;
4861 case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
4862 default:
4863 case CONFIG_TYPE_OBSOLETE:
4864 type = NULL; break;
4866 if (!type)
4867 continue;
4868 len = strlen(var->name)+strlen(type)+16;
4869 if (desc)
4870 len += strlen(desc);
4871 line = tor_malloc(len);
4872 if (desc)
4873 tor_snprintf(line, len, "%s %s %s\n",var->name,type,desc);
4874 else
4875 tor_snprintf(line, len, "%s %s\n",var->name,type);
4876 smartlist_add(sl, line);
4878 *answer = smartlist_join_strings(sl, "", 0, NULL);
4879 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
4880 smartlist_free(sl);
4882 return 0;
4885 #include "aes.h"
4886 #include "ht.h"
4887 #include "test.h"
4889 extern const char aes_c_id[];
4890 extern const char compat_c_id[];
4891 extern const char container_c_id[];
4892 extern const char crypto_c_id[];
4893 extern const char log_c_id[];
4894 extern const char torgzip_c_id[];
4895 extern const char tortls_c_id[];
4896 extern const char util_c_id[];
4898 extern const char buffers_c_id[];
4899 extern const char circuitbuild_c_id[];
4900 extern const char circuitlist_c_id[];
4901 extern const char circuituse_c_id[];
4902 extern const char command_c_id[];
4903 // extern const char config_c_id[];
4904 extern const char connection_c_id[];
4905 extern const char connection_edge_c_id[];
4906 extern const char connection_or_c_id[];
4907 extern const char control_c_id[];
4908 extern const char cpuworker_c_id[];
4909 extern const char directory_c_id[];
4910 extern const char dirserv_c_id[];
4911 extern const char dns_c_id[];
4912 extern const char hibernate_c_id[];
4913 extern const char main_c_id[];
4914 #ifdef NT_SERVICE
4915 extern const char ntmain_c_id[];
4916 #endif
4917 extern const char onion_c_id[];
4918 extern const char policies_c_id[];
4919 extern const char relay_c_id[];
4920 extern const char rendclient_c_id[];
4921 extern const char rendcommon_c_id[];
4922 extern const char rendmid_c_id[];
4923 extern const char rendservice_c_id[];
4924 extern const char rephist_c_id[];
4925 extern const char router_c_id[];
4926 extern const char routerlist_c_id[];
4927 extern const char routerparse_c_id[];
4929 /** Dump the version of every file to the log. */
4930 static void
4931 print_svn_version(void)
4933 puts(AES_H_ID);
4934 puts(COMPAT_H_ID);
4935 puts(CONTAINER_H_ID);
4936 puts(CRYPTO_H_ID);
4937 puts(HT_H_ID);
4938 puts(TEST_H_ID);
4939 puts(LOG_H_ID);
4940 puts(TORGZIP_H_ID);
4941 puts(TORINT_H_ID);
4942 puts(TORTLS_H_ID);
4943 puts(UTIL_H_ID);
4944 puts(aes_c_id);
4945 puts(compat_c_id);
4946 puts(container_c_id);
4947 puts(crypto_c_id);
4948 puts(log_c_id);
4949 puts(torgzip_c_id);
4950 puts(tortls_c_id);
4951 puts(util_c_id);
4953 puts(OR_H_ID);
4954 puts(buffers_c_id);
4955 puts(circuitbuild_c_id);
4956 puts(circuitlist_c_id);
4957 puts(circuituse_c_id);
4958 puts(command_c_id);
4959 puts(config_c_id);
4960 puts(connection_c_id);
4961 puts(connection_edge_c_id);
4962 puts(connection_or_c_id);
4963 puts(control_c_id);
4964 puts(cpuworker_c_id);
4965 puts(directory_c_id);
4966 puts(dirserv_c_id);
4967 puts(dns_c_id);
4968 puts(hibernate_c_id);
4969 puts(main_c_id);
4970 #ifdef NT_SERVICE
4971 puts(ntmain_c_id);
4972 #endif
4973 puts(onion_c_id);
4974 puts(policies_c_id);
4975 puts(relay_c_id);
4976 puts(rendclient_c_id);
4977 puts(rendcommon_c_id);
4978 puts(rendmid_c_id);
4979 puts(rendservice_c_id);
4980 puts(rephist_c_id);
4981 puts(router_c_id);
4982 puts(routerlist_c_id);
4983 puts(routerparse_c_id);