New config options WarnPlaintextPorts and RejectPlaintextPorts so
[tor.git] / src / or / config.c
blob39ad4be4bb8b6c378f8d2b178d0cfd4c02537bef
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, 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 NULL
840 for (i=0; dirservers[i]; i++) {
841 if (parse_dir_server_line(dirservers[i], type, 0)<0) {
842 log_err(LD_BUG, "Couldn't parse internal dirserver line %s",
843 dirservers[i]);
848 /** Look at all the config options for using alternate directory
849 * authorities, and make sure none of them are broken. Also, warn the
850 * user if we changed any dangerous ones.
852 static int
853 validate_dir_authorities(or_options_t *options, or_options_t *old_options)
855 config_line_t *cl;
857 if (options->DirServers &&
858 (options->AlternateDirAuthority || options->AlternateBridgeAuthority ||
859 options->AlternateHSAuthority)) {
860 log_warn(LD_CONFIG,
861 "You cannot set both DirServers and Alternate*Authority.");
862 return -1;
865 /* do we want to complain to the user about being partitionable? */
866 if ((options->DirServers &&
867 (!old_options ||
868 !config_lines_eq(options->DirServers, old_options->DirServers))) ||
869 (options->AlternateDirAuthority &&
870 (!old_options ||
871 !config_lines_eq(options->AlternateDirAuthority,
872 old_options->AlternateDirAuthority)))) {
873 log_warn(LD_CONFIG,
874 "You have used DirServer or AlternateDirAuthority to "
875 "specify alternate directory authorities in "
876 "your configuration. This is potentially dangerous: it can "
877 "make you look different from all other Tor users, and hurt "
878 "your anonymity. Even if you've specified the same "
879 "authorities as Tor uses by default, the defaults could "
880 "change in the future. Be sure you know what you're doing.");
883 /* Now go through the four ways you can configure an alternate
884 * set of directory authorities, and make sure none are broken. */
885 for (cl = options->DirServers; cl; cl = cl->next)
886 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
887 return -1;
888 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
889 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
890 return -1;
891 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
892 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
893 return -1;
894 for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
895 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
896 return -1;
897 return 0;
900 /** Look at all the config options and assign new dir authorities
901 * as appropriate.
903 static int
904 consider_adding_dir_authorities(or_options_t *options,
905 or_options_t *old_options)
907 config_line_t *cl;
908 int need_to_update =
909 !smartlist_len(router_get_trusted_dir_servers()) || !old_options ||
910 !config_lines_eq(options->DirServers, old_options->DirServers) ||
911 !config_lines_eq(options->AlternateBridgeAuthority,
912 old_options->AlternateBridgeAuthority) ||
913 !config_lines_eq(options->AlternateDirAuthority,
914 old_options->AlternateDirAuthority) ||
915 !config_lines_eq(options->AlternateHSAuthority,
916 old_options->AlternateHSAuthority);
918 if (!need_to_update)
919 return 0; /* all done */
921 /* Start from a clean slate. */
922 clear_trusted_dir_servers();
924 if (!options->DirServers) {
925 /* then we may want some of the defaults */
926 authority_type_t type = NO_AUTHORITY;
927 if (!options->AlternateBridgeAuthority)
928 type |= BRIDGE_AUTHORITY;
929 if (!options->AlternateDirAuthority)
930 type |= V1_AUTHORITY | V2_AUTHORITY | V3_AUTHORITY;
931 if (!options->AlternateHSAuthority)
932 type |= HIDSERV_AUTHORITY;
933 add_default_trusted_dir_authorities(type);
936 for (cl = options->DirServers; cl; cl = cl->next)
937 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
938 return -1;
939 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
940 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
941 return -1;
942 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
943 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
944 return -1;
945 for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
946 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
947 return -1;
948 return 0;
951 /** Fetch the active option list, and take actions based on it. All of the
952 * things we do should survive being done repeatedly. If present,
953 * <b>old_options</b> contains the previous value of the options.
955 * Return 0 if all goes well, return -1 if things went badly.
957 static int
958 options_act_reversible(or_options_t *old_options, char **msg)
960 smartlist_t *new_listeners = smartlist_create();
961 smartlist_t *replaced_listeners = smartlist_create();
962 static int libevent_initialized = 0;
963 or_options_t *options = get_options();
964 int running_tor = options->command == CMD_RUN_TOR;
965 int set_conn_limit = 0;
966 int r = -1;
967 int logs_marked = 0;
969 /* Daemonize _first_, since we only want to open most of this stuff in
970 * the subprocess. Libevent bases can't be reliably inherited across
971 * processes. */
972 if (running_tor && options->RunAsDaemon) {
973 /* No need to roll back, since you can't change the value. */
974 start_daemon();
977 #ifndef HAVE_SYS_UN_H
978 if (options->ControlSocket) {
979 *msg = tor_strdup("Unix domain sockets (ControlSocket) not supported"
980 " on this OS/with this build.");
981 goto rollback;
983 #endif
985 if (running_tor) {
986 /* We need to set the connection limit before we can open the listeners. */
987 options->_ConnLimit =
988 set_max_file_descriptors((unsigned)options->ConnLimit, MAXCONNECTIONS);
989 if (options->_ConnLimit < 0) {
990 *msg = tor_strdup("Problem with ConnLimit value. See logs for details.");
991 goto rollback;
993 set_conn_limit = 1;
995 /* Set up libevent. (We need to do this before we can register the
996 * listeners as listeners.) */
997 if (running_tor && !libevent_initialized) {
998 init_libevent();
999 libevent_initialized = 1;
1002 /* Launch the listeners. (We do this before we setuid, so we can bind to
1003 * ports under 1024.) */
1004 if (retry_all_listeners(replaced_listeners, new_listeners) < 0) {
1005 *msg = tor_strdup("Failed to bind one of the listener ports.");
1006 goto rollback;
1010 /* Setuid/setgid as appropriate */
1011 if (options->User || options->Group) {
1012 if (switch_id(options->User, options->Group) != 0) {
1013 /* No need to roll back, since you can't change the value. */
1014 *msg = tor_strdup("Problem with User or Group value. "
1015 "See logs for details.");
1016 goto done;
1020 /* Ensure data directory is private; create if possible. */
1021 if (check_private_dir(options->DataDirectory,
1022 running_tor ? CPD_CREATE : CPD_CHECK)<0) {
1023 char buf[1024];
1024 int tmp = tor_snprintf(buf, sizeof(buf),
1025 "Couldn't access/create private data directory \"%s\"",
1026 options->DataDirectory);
1027 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1028 goto done;
1029 /* No need to roll back, since you can't change the value. */
1032 /* Bail out at this point if we're not going to be a client or server:
1033 * we don't run Tor itself. */
1034 if (!running_tor)
1035 goto commit;
1037 mark_logs_temp(); /* Close current logs once new logs are open. */
1038 logs_marked = 1;
1039 if (options_init_logs(options, 0)<0) { /* Configure the log(s) */
1040 *msg = tor_strdup("Failed to init Log options. See logs for details.");
1041 goto rollback;
1044 commit:
1045 r = 0;
1046 if (logs_marked) {
1047 close_temp_logs();
1048 add_callback_log(LOG_ERR, LOG_ERR, control_event_logmsg);
1049 control_adjust_event_log_severity();
1051 SMARTLIST_FOREACH(replaced_listeners, connection_t *, conn,
1053 log_notice(LD_NET, "Closing old %s on %s:%d",
1054 conn_type_to_string(conn->type), conn->address, conn->port);
1055 connection_close_immediate(conn);
1056 connection_mark_for_close(conn);
1058 goto done;
1060 rollback:
1061 r = -1;
1062 tor_assert(*msg);
1064 if (logs_marked) {
1065 rollback_log_changes();
1066 control_adjust_event_log_severity();
1069 if (set_conn_limit && old_options)
1070 set_max_file_descriptors((unsigned)old_options->ConnLimit,MAXCONNECTIONS);
1072 SMARTLIST_FOREACH(new_listeners, connection_t *, conn,
1074 log_notice(LD_NET, "Closing partially-constructed listener %s on %s:%d",
1075 conn_type_to_string(conn->type), conn->address, conn->port);
1076 connection_close_immediate(conn);
1077 connection_mark_for_close(conn);
1080 done:
1081 smartlist_free(new_listeners);
1082 smartlist_free(replaced_listeners);
1083 return r;
1086 /** Fetch the active option list, and take actions based on it. All of the
1087 * things we do should survive being done repeatedly. If present,
1088 * <b>old_options</b> contains the previous value of the options.
1090 * Return 0 if all goes well, return -1 if it's time to die.
1092 * Note: We haven't moved all the "act on new configuration" logic
1093 * here yet. Some is still in do_hup() and other places.
1095 static int
1096 options_act(or_options_t *old_options)
1098 config_line_t *cl;
1099 char *fn;
1100 size_t len;
1101 or_options_t *options = get_options();
1102 int running_tor = options->command == CMD_RUN_TOR;
1103 char *msg;
1105 if (consider_adding_dir_authorities(options, old_options) < 0)
1106 return -1;
1108 if (options->Bridges) {
1109 clear_bridge_list();
1110 for (cl = options->Bridges; cl; cl = cl->next) {
1111 if (parse_bridge_line(cl->value, 0)<0) {
1112 log_warn(LD_BUG,
1113 "Previously validated Bridge line could not be added!");
1114 return -1;
1119 if (running_tor && rend_config_services(options, 0)<0) {
1120 log_warn(LD_BUG,
1121 "Previously validated hidden services line could not be added!");
1122 return -1;
1125 if (running_tor && directory_caches_v2_dir_info(options)) {
1126 len = strlen(options->DataDirectory)+32;
1127 fn = tor_malloc(len);
1128 tor_snprintf(fn, len, "%s"PATH_SEPARATOR"cached-status",
1129 options->DataDirectory);
1130 if (check_private_dir(fn, CPD_CREATE) != 0) {
1131 log_warn(LD_CONFIG,
1132 "Couldn't access/create private data directory \"%s\"", fn);
1133 tor_free(fn);
1134 return -1;
1136 tor_free(fn);
1139 /* Load state */
1140 if (! global_state && options->command == CMD_RUN_TOR) {
1141 if (or_state_load())
1142 return -1;
1143 rep_hist_load_mtbf_data(time(NULL));
1146 /* Bail out at this point if we're not going to be a client or server:
1147 * we want to not fork, and to log stuff to stderr. */
1148 if (!running_tor)
1149 return 0;
1152 smartlist_t *sl = smartlist_create();
1153 char *errmsg = NULL;
1154 for (cl = options->RedirectExit; cl; cl = cl->next) {
1155 if (parse_redirect_line(sl, cl, &errmsg)<0) {
1156 log_warn(LD_CONFIG, "%s", errmsg);
1157 tor_free(errmsg);
1158 SMARTLIST_FOREACH(sl, exit_redirect_t *, er, tor_free(er));
1159 smartlist_free(sl);
1160 return -1;
1163 set_exit_redirects(sl);
1166 /* Finish backgrounding the process */
1167 if (running_tor && options->RunAsDaemon) {
1168 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
1169 finish_daemon(options->DataDirectory);
1172 /* Write our pid to the pid file. If we do not have write permissions we
1173 * will log a warning */
1174 if (running_tor && options->PidFile)
1175 write_pidfile(options->PidFile);
1177 /* Register addressmap directives */
1178 config_register_addressmaps(options);
1179 parse_virtual_addr_network(options->VirtualAddrNetwork, 0, &msg);
1181 /* Update address policies. */
1182 policies_parse_from_options(options);
1184 if (init_cookie_authentication(options->CookieAuthentication) < 0) {
1185 log_warn(LD_CONFIG,"Error creating cookie authentication file.");
1186 return -1;
1189 /* reload keys as needed for rendezvous services. */
1190 if (rend_service_load_keys()<0) {
1191 log_warn(LD_GENERAL,"Error loading rendezvous service keys");
1192 return -1;
1195 /* Set up accounting */
1196 if (accounting_parse_options(options, 0)<0) {
1197 log_warn(LD_CONFIG,"Error in accounting options");
1198 return -1;
1200 if (accounting_is_enabled(options))
1201 configure_accounting(time(NULL));
1203 /* Check for transitions that need action. */
1204 if (old_options) {
1205 if (options->UseEntryGuards && !old_options->UseEntryGuards) {
1206 log_info(LD_CIRC,
1207 "Switching to entry guards; abandoning previous circuits");
1208 circuit_mark_all_unused_circs();
1209 circuit_expire_all_dirty_circs();
1212 if (options_transition_affects_workers(old_options, options)) {
1213 log_info(LD_GENERAL,
1214 "Worker-related options changed. Rotating workers.");
1215 if (server_mode(options) && !server_mode(old_options)) {
1216 if (init_keys() < 0) {
1217 log_warn(LD_BUG,"Error initializing keys; exiting");
1218 return -1;
1220 ip_address_changed(0);
1221 if (has_completed_circuit || !any_predicted_circuits(time(NULL)))
1222 inform_testing_reachability();
1224 cpuworkers_rotate();
1225 if (dns_reset())
1226 return -1;
1227 } else {
1228 if (dns_reset())
1229 return -1;
1232 if (options->V3AuthoritativeDir && !old_options->V3AuthoritativeDir)
1233 init_keys();
1236 /* Maybe load geoip file */
1237 if (options->GeoIPFile &&
1238 ((!old_options || !opt_streq(old_options->GeoIPFile, options->GeoIPFile))
1239 || !geoip_is_loaded())) {
1240 geoip_load_file(options->GeoIPFile);
1242 /* Check if we need to parse and add the EntryNodes config option. */
1243 if (options->EntryNodes &&
1244 (!old_options ||
1245 !opt_streq(old_options->EntryNodes, options->EntryNodes)))
1246 entry_nodes_should_be_added();
1248 /* Since our options changed, we might need to regenerate and upload our
1249 * server descriptor.
1251 if (!old_options ||
1252 options_transition_affects_descriptor(old_options, options))
1253 mark_my_descriptor_dirty();
1255 /* We may need to reschedule some directory stuff if our status changed. */
1256 if (old_options) {
1257 if (authdir_mode_v3(options) && !authdir_mode_v3(old_options))
1258 dirvote_recalculate_timing(options, time(NULL));
1259 if (!bool_eq(directory_fetches_dir_info_early(options),
1260 directory_fetches_dir_info_early(old_options)) ||
1261 !bool_eq(directory_fetches_dir_info_later(options),
1262 directory_fetches_dir_info_later(old_options))) {
1263 /* Make sure update_router_have_min_dir_info gets called. */
1264 router_dir_info_changed();
1265 /* We might need to download a new consensus status later or sooner than
1266 * we had expected. */
1267 update_consensus_networkstatus_fetch_time(time(NULL));
1271 return 0;
1275 * Functions to parse config options
1278 /** If <b>option</b> is an official abbreviation for a longer option,
1279 * return the longer option. Otherwise return <b>option</b>.
1280 * If <b>command_line</b> is set, apply all abbreviations. Otherwise, only
1281 * apply abbreviations that work for the config file and the command line.
1282 * If <b>warn_obsolete</b> is set, warn about deprecated names. */
1283 static const char *
1284 expand_abbrev(config_format_t *fmt, const char *option, int command_line,
1285 int warn_obsolete)
1287 int i;
1288 if (! fmt->abbrevs)
1289 return option;
1290 for (i=0; fmt->abbrevs[i].abbreviated; ++i) {
1291 /* Abbreviations are casei. */
1292 if (!strcasecmp(option,fmt->abbrevs[i].abbreviated) &&
1293 (command_line || !fmt->abbrevs[i].commandline_only)) {
1294 if (warn_obsolete && fmt->abbrevs[i].warn) {
1295 log_warn(LD_CONFIG,
1296 "The configuration option '%s' is deprecated; "
1297 "use '%s' instead.",
1298 fmt->abbrevs[i].abbreviated,
1299 fmt->abbrevs[i].full);
1301 return fmt->abbrevs[i].full;
1304 return option;
1307 /** Helper: Read a list of configuration options from the command line.
1308 * If successful, put them in *<b>result</b> and return 0, and return
1309 * -1 and leave *<b>result</b> alone. */
1310 static int
1311 config_get_commandlines(int argc, char **argv, config_line_t **result)
1313 config_line_t *front = NULL;
1314 config_line_t **new = &front;
1315 char *s;
1316 int i = 1;
1318 while (i < argc) {
1319 if (!strcmp(argv[i],"-f") ||
1320 !strcmp(argv[i],"--hash-password")) {
1321 i += 2; /* command-line option with argument. ignore them. */
1322 continue;
1323 } else if (!strcmp(argv[i],"--list-fingerprint") ||
1324 !strcmp(argv[i],"--verify-config") ||
1325 !strcmp(argv[i],"--ignore-missing-torrc") ||
1326 !strcmp(argv[i],"--quiet")) {
1327 i += 1; /* command-line option. ignore it. */
1328 continue;
1329 } else if (!strcmp(argv[i],"--nt-service") ||
1330 !strcmp(argv[i],"-nt-service")) {
1331 i += 1;
1332 continue;
1335 if (i == argc-1) {
1336 log_warn(LD_CONFIG,"Command-line option '%s' with no value. Failing.",
1337 argv[i]);
1338 config_free_lines(front);
1339 return -1;
1342 *new = tor_malloc_zero(sizeof(config_line_t));
1343 s = argv[i];
1345 while (*s == '-')
1346 s++;
1348 (*new)->key = tor_strdup(expand_abbrev(&options_format, s, 1, 1));
1349 (*new)->value = tor_strdup(argv[i+1]);
1350 (*new)->next = NULL;
1351 log(LOG_DEBUG, LD_CONFIG, "Commandline: parsed keyword '%s', value '%s'",
1352 (*new)->key, (*new)->value);
1354 new = &((*new)->next);
1355 i += 2;
1357 *result = front;
1358 return 0;
1361 /** Helper: allocate a new configuration option mapping 'key' to 'val',
1362 * append it to *<b>lst</b>. */
1363 static void
1364 config_line_append(config_line_t **lst,
1365 const char *key,
1366 const char *val)
1368 config_line_t *newline;
1370 newline = tor_malloc(sizeof(config_line_t));
1371 newline->key = tor_strdup(key);
1372 newline->value = tor_strdup(val);
1373 newline->next = NULL;
1374 while (*lst)
1375 lst = &((*lst)->next);
1377 (*lst) = newline;
1380 /** Helper: parse the config string and strdup into key/value
1381 * strings. Set *result to the list, or NULL if parsing the string
1382 * failed. Return 0 on success, -1 on failure. Warn and ignore any
1383 * misformatted lines. */
1385 config_get_lines(const char *string, config_line_t **result)
1387 config_line_t *list = NULL, **next;
1388 char *k, *v;
1390 next = &list;
1391 do {
1392 string = parse_config_line_from_str(string, &k, &v);
1393 if (!string) {
1394 config_free_lines(list);
1395 return -1;
1397 if (k && v) {
1398 /* This list can get long, so we keep a pointer to the end of it
1399 * rather than using config_line_append over and over and getting
1400 * n^2 performance. */
1401 *next = tor_malloc(sizeof(config_line_t));
1402 (*next)->key = k;
1403 (*next)->value = v;
1404 (*next)->next = NULL;
1405 next = &((*next)->next);
1406 } else {
1407 tor_free(k);
1408 tor_free(v);
1410 } while (*string);
1412 *result = list;
1413 return 0;
1417 * Free all the configuration lines on the linked list <b>front</b>.
1419 void
1420 config_free_lines(config_line_t *front)
1422 config_line_t *tmp;
1424 while (front) {
1425 tmp = front;
1426 front = tmp->next;
1428 tor_free(tmp->key);
1429 tor_free(tmp->value);
1430 tor_free(tmp);
1434 /** Return the description for a given configuration variable, or NULL if no
1435 * description exists. */
1436 static const char *
1437 config_find_description(config_format_t *fmt, const char *name)
1439 int i;
1440 for (i=0; fmt->descriptions[i].name; ++i) {
1441 if (!strcasecmp(name, fmt->descriptions[i].name))
1442 return fmt->descriptions[i].description;
1444 return NULL;
1447 /** If <b>key</b> is a configuration option, return the corresponding
1448 * config_var_t. Otherwise, if <b>key</b> is a non-standard abbreviation,
1449 * warn, and return the corresponding config_var_t. Otherwise return NULL.
1451 static config_var_t *
1452 config_find_option(config_format_t *fmt, const char *key)
1454 int i;
1455 size_t keylen = strlen(key);
1456 if (!keylen)
1457 return NULL; /* if they say "--" on the commandline, it's not an option */
1458 /* First, check for an exact (case-insensitive) match */
1459 for (i=0; fmt->vars[i].name; ++i) {
1460 if (!strcasecmp(key, fmt->vars[i].name)) {
1461 return &fmt->vars[i];
1464 /* If none, check for an abbreviated match */
1465 for (i=0; fmt->vars[i].name; ++i) {
1466 if (!strncasecmp(key, fmt->vars[i].name, keylen)) {
1467 log_warn(LD_CONFIG, "The abbreviation '%s' is deprecated. "
1468 "Please use '%s' instead",
1469 key, fmt->vars[i].name);
1470 return &fmt->vars[i];
1473 /* Okay, unrecognized option */
1474 return NULL;
1478 * Functions to assign config options.
1481 /** <b>c</b>-\>key is known to be a real key. Update <b>options</b>
1482 * with <b>c</b>-\>value and return 0, or return -1 if bad value.
1484 * Called from config_assign_line() and option_reset().
1486 static int
1487 config_assign_value(config_format_t *fmt, or_options_t *options,
1488 config_line_t *c, char **msg)
1490 int i, r, ok;
1491 char buf[1024];
1492 config_var_t *var;
1493 void *lvalue;
1495 CHECK(fmt, options);
1497 var = config_find_option(fmt, c->key);
1498 tor_assert(var);
1500 lvalue = STRUCT_VAR_P(options, var->var_offset);
1502 switch (var->type) {
1504 case CONFIG_TYPE_UINT:
1505 i = tor_parse_long(c->value, 10, 0, INT_MAX, &ok, NULL);
1506 if (!ok) {
1507 r = tor_snprintf(buf, sizeof(buf),
1508 "Int keyword '%s %s' is malformed or out of bounds.",
1509 c->key, c->value);
1510 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1511 return -1;
1513 *(int *)lvalue = i;
1514 break;
1516 case CONFIG_TYPE_INTERVAL: {
1517 i = config_parse_interval(c->value, &ok);
1518 if (!ok) {
1519 r = tor_snprintf(buf, sizeof(buf),
1520 "Interval '%s %s' is malformed or out of bounds.",
1521 c->key, c->value);
1522 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1523 return -1;
1525 *(int *)lvalue = i;
1526 break;
1529 case CONFIG_TYPE_MEMUNIT: {
1530 uint64_t u64 = config_parse_memunit(c->value, &ok);
1531 if (!ok) {
1532 r = tor_snprintf(buf, sizeof(buf),
1533 "Value '%s %s' is malformed or out of bounds.",
1534 c->key, c->value);
1535 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1536 return -1;
1538 *(uint64_t *)lvalue = u64;
1539 break;
1542 case CONFIG_TYPE_BOOL:
1543 i = tor_parse_long(c->value, 10, 0, 1, &ok, NULL);
1544 if (!ok) {
1545 r = tor_snprintf(buf, sizeof(buf),
1546 "Boolean '%s %s' expects 0 or 1.",
1547 c->key, c->value);
1548 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1549 return -1;
1551 *(int *)lvalue = i;
1552 break;
1554 case CONFIG_TYPE_STRING:
1555 tor_free(*(char **)lvalue);
1556 *(char **)lvalue = tor_strdup(c->value);
1557 break;
1559 case CONFIG_TYPE_DOUBLE:
1560 *(double *)lvalue = atof(c->value);
1561 break;
1563 case CONFIG_TYPE_ISOTIME:
1564 if (parse_iso_time(c->value, (time_t *)lvalue)) {
1565 r = tor_snprintf(buf, sizeof(buf),
1566 "Invalid time '%s' for keyword '%s'", c->value, c->key);
1567 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1568 return -1;
1570 break;
1572 case CONFIG_TYPE_CSV:
1573 if (*(smartlist_t**)lvalue) {
1574 SMARTLIST_FOREACH(*(smartlist_t**)lvalue, char *, cp, tor_free(cp));
1575 smartlist_clear(*(smartlist_t**)lvalue);
1576 } else {
1577 *(smartlist_t**)lvalue = smartlist_create();
1580 smartlist_split_string(*(smartlist_t**)lvalue, c->value, ",",
1581 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1582 break;
1584 case CONFIG_TYPE_LINELIST:
1585 case CONFIG_TYPE_LINELIST_S:
1586 config_line_append((config_line_t**)lvalue, c->key, c->value);
1587 break;
1589 case CONFIG_TYPE_OBSOLETE:
1590 log_warn(LD_CONFIG, "Skipping obsolete configuration option '%s'", c->key);
1591 break;
1592 case CONFIG_TYPE_LINELIST_V:
1593 r = tor_snprintf(buf, sizeof(buf),
1594 "You may not provide a value for virtual option '%s'", c->key);
1595 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1596 return -1;
1597 default:
1598 tor_assert(0);
1599 break;
1601 return 0;
1604 /** If <b>c</b> is a syntactically valid configuration line, update
1605 * <b>options</b> with its value and return 0. Otherwise return -1 for bad
1606 * key, -2 for bad value.
1608 * If <b>clear_first</b> is set, clear the value first. Then if
1609 * <b>use_defaults</b> is set, set the value to the default.
1611 * Called from config_assign().
1613 static int
1614 config_assign_line(config_format_t *fmt, or_options_t *options,
1615 config_line_t *c, int use_defaults,
1616 int clear_first, char **msg)
1618 config_var_t *var;
1620 CHECK(fmt, options);
1622 var = config_find_option(fmt, c->key);
1623 if (!var) {
1624 if (fmt->extra) {
1625 void *lvalue = STRUCT_VAR_P(options, fmt->extra->var_offset);
1626 log_info(LD_CONFIG,
1627 "Found unrecognized option '%s'; saving it.", c->key);
1628 config_line_append((config_line_t**)lvalue, c->key, c->value);
1629 return 0;
1630 } else {
1631 char buf[1024];
1632 int tmp = tor_snprintf(buf, sizeof(buf),
1633 "Unknown option '%s'. Failing.", c->key);
1634 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1635 return -1;
1638 /* Put keyword into canonical case. */
1639 if (strcmp(var->name, c->key)) {
1640 tor_free(c->key);
1641 c->key = tor_strdup(var->name);
1644 if (!strlen(c->value)) {
1645 /* reset or clear it, then return */
1646 if (!clear_first) {
1647 if (var->type == CONFIG_TYPE_LINELIST ||
1648 var->type == CONFIG_TYPE_LINELIST_S) {
1649 /* We got an empty linelist from the torrc or commandline.
1650 As a special case, call this an error. Warn and ignore. */
1651 log_warn(LD_CONFIG,
1652 "Linelist option '%s' has no value. Skipping.", c->key);
1653 } else { /* not already cleared */
1654 option_reset(fmt, options, var, use_defaults);
1657 return 0;
1660 if (config_assign_value(fmt, options, c, msg) < 0)
1661 return -2;
1662 return 0;
1665 /** Restore the option named <b>key</b> in options to its default value.
1666 * Called from config_assign(). */
1667 static void
1668 config_reset_line(config_format_t *fmt, or_options_t *options,
1669 const char *key, int use_defaults)
1671 config_var_t *var;
1673 CHECK(fmt, options);
1675 var = config_find_option(fmt, key);
1676 if (!var)
1677 return; /* give error on next pass. */
1679 option_reset(fmt, options, var, use_defaults);
1682 /** Return true iff key is a valid configuration option. */
1684 option_is_recognized(const char *key)
1686 config_var_t *var = config_find_option(&options_format, key);
1687 return (var != NULL);
1690 /** Return the canonical name of a configuration option, or NULL
1691 * if no such option exists. */
1692 const char *
1693 option_get_canonical_name(const char *key)
1695 config_var_t *var = config_find_option(&options_format, key);
1696 return var ? var->name : NULL;
1699 /** Return a canonicalized list of the options assigned for key.
1701 config_line_t *
1702 option_get_assignment(or_options_t *options, const char *key)
1704 return get_assigned_option(&options_format, options, key, 1);
1707 /** Return true iff value needs to be quoted and escaped to be used in
1708 * a configuration file. */
1709 static int
1710 config_value_needs_escape(const char *value)
1712 if (*value == '\"')
1713 return 1;
1714 while (*value) {
1715 switch (*value)
1717 case '\r':
1718 case '\n':
1719 case '#':
1720 /* Note: quotes and backspaces need special handling when we are using
1721 * quotes, not otherwise, so they don't trigger escaping on their
1722 * own. */
1723 return 1;
1724 default:
1725 if (!TOR_ISPRINT(*value))
1726 return 1;
1728 ++value;
1730 return 0;
1733 /** Return a newly allocated deep copy of the lines in <b>inp</b>. */
1734 static config_line_t *
1735 config_lines_dup(const config_line_t *inp)
1737 config_line_t *result = NULL;
1738 config_line_t **next_out = &result;
1739 while (inp) {
1740 *next_out = tor_malloc(sizeof(config_line_t));
1741 (*next_out)->key = tor_strdup(inp->key);
1742 (*next_out)->value = tor_strdup(inp->value);
1743 inp = inp->next;
1744 next_out = &((*next_out)->next);
1746 (*next_out) = NULL;
1747 return result;
1750 /** Return newly allocated line or lines corresponding to <b>key</b> in the
1751 * configuration <b>options</b>. If <b>escape_val</b> is true and a
1752 * value needs to be quoted before it's put in a config file, quote and
1753 * escape that value. Return NULL if no such key exists. */
1754 static config_line_t *
1755 get_assigned_option(config_format_t *fmt, or_options_t *options,
1756 const char *key, int escape_val)
1757 /* XXXX argument is options, but fmt is provided. Inconsistent. */
1759 config_var_t *var;
1760 const void *value;
1761 char buf[32];
1762 config_line_t *result;
1763 tor_assert(options && key);
1765 CHECK(fmt, options);
1767 var = config_find_option(fmt, key);
1768 if (!var) {
1769 log_warn(LD_CONFIG, "Unknown option '%s'. Failing.", key);
1770 return NULL;
1772 value = STRUCT_VAR_P(options, var->var_offset);
1774 result = tor_malloc_zero(sizeof(config_line_t));
1775 result->key = tor_strdup(var->name);
1776 switch (var->type)
1778 case CONFIG_TYPE_STRING:
1779 if (*(char**)value) {
1780 result->value = tor_strdup(*(char**)value);
1781 } else {
1782 tor_free(result->key);
1783 tor_free(result);
1784 return NULL;
1786 break;
1787 case CONFIG_TYPE_ISOTIME:
1788 if (*(time_t*)value) {
1789 result->value = tor_malloc(ISO_TIME_LEN+1);
1790 format_iso_time(result->value, *(time_t*)value);
1791 } else {
1792 tor_free(result->key);
1793 tor_free(result);
1795 escape_val = 0; /* Can't need escape. */
1796 break;
1797 case CONFIG_TYPE_INTERVAL:
1798 case CONFIG_TYPE_UINT:
1799 /* This means every or_options_t uint or bool element
1800 * needs to be an int. Not, say, a uint16_t or char. */
1801 tor_snprintf(buf, sizeof(buf), "%d", *(int*)value);
1802 result->value = tor_strdup(buf);
1803 escape_val = 0; /* Can't need escape. */
1804 break;
1805 case CONFIG_TYPE_MEMUNIT:
1806 tor_snprintf(buf, sizeof(buf), U64_FORMAT,
1807 U64_PRINTF_ARG(*(uint64_t*)value));
1808 result->value = tor_strdup(buf);
1809 escape_val = 0; /* Can't need escape. */
1810 break;
1811 case CONFIG_TYPE_DOUBLE:
1812 tor_snprintf(buf, sizeof(buf), "%f", *(double*)value);
1813 result->value = tor_strdup(buf);
1814 escape_val = 0; /* Can't need escape. */
1815 break;
1816 case CONFIG_TYPE_BOOL:
1817 result->value = tor_strdup(*(int*)value ? "1" : "0");
1818 escape_val = 0; /* Can't need escape. */
1819 break;
1820 case CONFIG_TYPE_CSV:
1821 if (*(smartlist_t**)value)
1822 result->value =
1823 smartlist_join_strings(*(smartlist_t**)value, ",", 0, NULL);
1824 else
1825 result->value = tor_strdup("");
1826 break;
1827 case CONFIG_TYPE_OBSOLETE:
1828 log_warn(LD_CONFIG,
1829 "You asked me for the value of an obsolete config option '%s'.",
1830 key);
1831 tor_free(result->key);
1832 tor_free(result);
1833 return NULL;
1834 case CONFIG_TYPE_LINELIST_S:
1835 log_warn(LD_CONFIG,
1836 "Can't return context-sensitive '%s' on its own", key);
1837 tor_free(result->key);
1838 tor_free(result);
1839 return NULL;
1840 case CONFIG_TYPE_LINELIST:
1841 case CONFIG_TYPE_LINELIST_V:
1842 tor_free(result->key);
1843 tor_free(result);
1844 result = config_lines_dup(*(const config_line_t**)value);
1845 break;
1846 default:
1847 tor_free(result->key);
1848 tor_free(result);
1849 log_warn(LD_BUG,"Unknown type %d for known key '%s'",
1850 var->type, key);
1851 return NULL;
1854 if (escape_val) {
1855 config_line_t *line;
1856 for (line = result; line; line = line->next) {
1857 if (line->value && config_value_needs_escape(line->value)) {
1858 char *newval = esc_for_log(line->value);
1859 tor_free(line->value);
1860 line->value = newval;
1865 return result;
1868 /** Iterate through the linked list of requested options <b>list</b>.
1869 * For each item, convert as appropriate and assign to <b>options</b>.
1870 * If an item is unrecognized, set *msg and return -1 immediately,
1871 * else return 0 for success.
1873 * If <b>clear_first</b>, interpret config options as replacing (not
1874 * extending) their previous values. If <b>clear_first</b> is set,
1875 * then <b>use_defaults</b> to decide if you set to defaults after
1876 * clearing, or make the value 0 or NULL.
1878 * Here are the use cases:
1879 * 1. A non-empty AllowInvalid line in your torrc. Appends to current
1880 * if linelist, replaces current if csv.
1881 * 2. An empty AllowInvalid line in your torrc. Should clear it.
1882 * 3. "RESETCONF AllowInvalid" sets it to default.
1883 * 4. "SETCONF AllowInvalid" makes it NULL.
1884 * 5. "SETCONF AllowInvalid=foo" clears it and sets it to "foo".
1886 * Use_defaults Clear_first
1887 * 0 0 "append"
1888 * 1 0 undefined, don't use
1889 * 0 1 "set to null first"
1890 * 1 1 "set to defaults first"
1891 * Return 0 on success, -1 on bad key, -2 on bad value.
1893 * As an additional special case, if a LINELIST config option has
1894 * no value and clear_first is 0, then warn and ignore it.
1898 There are three call cases for config_assign() currently.
1900 Case one: Torrc entry
1901 options_init_from_torrc() calls config_assign(0, 0)
1902 calls config_assign_line(0, 0).
1903 if value is empty, calls option_reset(0) and returns.
1904 calls config_assign_value(), appends.
1906 Case two: setconf
1907 options_trial_assign() calls config_assign(0, 1)
1908 calls config_reset_line(0)
1909 calls option_reset(0)
1910 calls option_clear().
1911 calls config_assign_line(0, 1).
1912 if value is empty, returns.
1913 calls config_assign_value(), appends.
1915 Case three: resetconf
1916 options_trial_assign() calls config_assign(1, 1)
1917 calls config_reset_line(1)
1918 calls option_reset(1)
1919 calls option_clear().
1920 calls config_assign_value(default)
1921 calls config_assign_line(1, 1).
1922 returns.
1924 static int
1925 config_assign(config_format_t *fmt, void *options, config_line_t *list,
1926 int use_defaults, int clear_first, char **msg)
1928 config_line_t *p;
1930 CHECK(fmt, options);
1932 /* pass 1: normalize keys */
1933 for (p = list; p; p = p->next) {
1934 const char *full = expand_abbrev(fmt, p->key, 0, 1);
1935 if (strcmp(full,p->key)) {
1936 tor_free(p->key);
1937 p->key = tor_strdup(full);
1941 /* pass 2: if we're reading from a resetting source, clear all
1942 * mentioned config options, and maybe set to their defaults. */
1943 if (clear_first) {
1944 for (p = list; p; p = p->next)
1945 config_reset_line(fmt, options, p->key, use_defaults);
1948 /* pass 3: assign. */
1949 while (list) {
1950 int r;
1951 if ((r=config_assign_line(fmt, options, list, use_defaults,
1952 clear_first, msg)))
1953 return r;
1954 list = list->next;
1956 return 0;
1959 /** Try assigning <b>list</b> to the global options. You do this by duping
1960 * options, assigning list to the new one, then validating it. If it's
1961 * ok, then throw out the old one and stick with the new one. Else,
1962 * revert to old and return failure. Return 0 on success, -1 on bad
1963 * keys, -2 on bad values, -3 on bad transition, and -4 on failed-to-set.
1965 * If not success, point *<b>msg</b> to a newly allocated string describing
1966 * what went wrong.
1969 options_trial_assign(config_line_t *list, int use_defaults,
1970 int clear_first, char **msg)
1972 int r;
1973 or_options_t *trial_options = options_dup(&options_format, get_options());
1975 if ((r=config_assign(&options_format, trial_options,
1976 list, use_defaults, clear_first, msg)) < 0) {
1977 config_free(&options_format, trial_options);
1978 return r;
1981 if (options_validate(get_options(), trial_options, 1, msg) < 0) {
1982 config_free(&options_format, trial_options);
1983 return -2;
1986 if (options_transition_allowed(get_options(), trial_options, msg) < 0) {
1987 config_free(&options_format, trial_options);
1988 return -3;
1991 if (set_options(trial_options, msg)<0) {
1992 config_free(&options_format, trial_options);
1993 return -4;
1996 /* we liked it. put it in place. */
1997 return 0;
2000 /** Reset config option <b>var</b> to 0, 0.0, NULL, or the equivalent.
2001 * Called from option_reset() and config_free(). */
2002 static void
2003 option_clear(config_format_t *fmt, or_options_t *options, config_var_t *var)
2005 void *lvalue = STRUCT_VAR_P(options, var->var_offset);
2006 (void)fmt; /* unused */
2007 switch (var->type) {
2008 case CONFIG_TYPE_STRING:
2009 tor_free(*(char**)lvalue);
2010 break;
2011 case CONFIG_TYPE_DOUBLE:
2012 *(double*)lvalue = 0.0;
2013 break;
2014 case CONFIG_TYPE_ISOTIME:
2015 *(time_t*)lvalue = 0;
2016 case CONFIG_TYPE_INTERVAL:
2017 case CONFIG_TYPE_UINT:
2018 case CONFIG_TYPE_BOOL:
2019 *(int*)lvalue = 0;
2020 break;
2021 case CONFIG_TYPE_MEMUNIT:
2022 *(uint64_t*)lvalue = 0;
2023 break;
2024 case CONFIG_TYPE_CSV:
2025 if (*(smartlist_t**)lvalue) {
2026 SMARTLIST_FOREACH(*(smartlist_t **)lvalue, char *, cp, tor_free(cp));
2027 smartlist_free(*(smartlist_t **)lvalue);
2028 *(smartlist_t **)lvalue = NULL;
2030 break;
2031 case CONFIG_TYPE_LINELIST:
2032 case CONFIG_TYPE_LINELIST_S:
2033 config_free_lines(*(config_line_t **)lvalue);
2034 *(config_line_t **)lvalue = NULL;
2035 break;
2036 case CONFIG_TYPE_LINELIST_V:
2037 /* handled by linelist_s. */
2038 break;
2039 case CONFIG_TYPE_OBSOLETE:
2040 break;
2044 /** Clear the option indexed by <b>var</b> in <b>options</b>. Then if
2045 * <b>use_defaults</b>, set it to its default value.
2046 * Called by config_init() and option_reset_line() and option_assign_line(). */
2047 static void
2048 option_reset(config_format_t *fmt, or_options_t *options,
2049 config_var_t *var, int use_defaults)
2051 config_line_t *c;
2052 char *msg = NULL;
2053 CHECK(fmt, options);
2054 option_clear(fmt, options, var); /* clear it first */
2055 if (!use_defaults)
2056 return; /* all done */
2057 if (var->initvalue) {
2058 c = tor_malloc_zero(sizeof(config_line_t));
2059 c->key = tor_strdup(var->name);
2060 c->value = tor_strdup(var->initvalue);
2061 if (config_assign_value(fmt, options, c, &msg) < 0) {
2062 log_warn(LD_BUG, "Failed to assign default: %s", msg);
2063 tor_free(msg); /* if this happens it's a bug */
2065 config_free_lines(c);
2069 /** Print a usage message for tor. */
2070 static void
2071 print_usage(void)
2073 printf(
2074 "Copyright 2001-2007 Roger Dingledine, Nick Mathewson.\n\n"
2075 "tor -f <torrc> [args]\n"
2076 "See man page for options, or https://www.torproject.org/ for "
2077 "documentation.\n");
2080 /** Print all non-obsolete torrc options. */
2081 static void
2082 list_torrc_options(void)
2084 int i;
2085 smartlist_t *lines = smartlist_create();
2086 for (i = 0; _option_vars[i].name; ++i) {
2087 config_var_t *var = &_option_vars[i];
2088 const char *desc;
2089 if (var->type == CONFIG_TYPE_OBSOLETE ||
2090 var->type == CONFIG_TYPE_LINELIST_V)
2091 continue;
2092 desc = config_find_description(&options_format, var->name);
2093 printf("%s\n", var->name);
2094 if (desc) {
2095 wrap_string(lines, desc, 76, " ", " ");
2096 SMARTLIST_FOREACH(lines, char *, cp, {
2097 printf("%s", cp);
2098 tor_free(cp);
2100 smartlist_clear(lines);
2103 smartlist_free(lines);
2106 /** Last value actually set by resolve_my_address. */
2107 static uint32_t last_resolved_addr = 0;
2109 * Based on <b>options-\>Address</b>, guess our public IP address and put it
2110 * (in host order) into *<b>addr_out</b>. If <b>hostname_out</b> is provided,
2111 * set *<b>hostname_out</b> to a new string holding the hostname we used to
2112 * get the address. Return 0 if all is well, or -1 if we can't find a suitable
2113 * public IP address.
2116 resolve_my_address(int warn_severity, or_options_t *options,
2117 uint32_t *addr_out, char **hostname_out)
2119 struct in_addr in;
2120 struct hostent *rent;
2121 char hostname[256];
2122 int explicit_ip=1;
2123 int explicit_hostname=1;
2124 int from_interface=0;
2125 char tmpbuf[INET_NTOA_BUF_LEN];
2126 const char *address = options->Address;
2127 int notice_severity = warn_severity <= LOG_NOTICE ?
2128 LOG_NOTICE : warn_severity;
2130 tor_assert(addr_out);
2132 if (address && *address) {
2133 strlcpy(hostname, address, sizeof(hostname));
2134 } else { /* then we need to guess our address */
2135 explicit_ip = 0; /* it's implicit */
2136 explicit_hostname = 0; /* it's implicit */
2138 if (gethostname(hostname, sizeof(hostname)) < 0) {
2139 log_fn(warn_severity, LD_NET,"Error obtaining local hostname");
2140 return -1;
2142 log_debug(LD_CONFIG,"Guessed local host name as '%s'",hostname);
2145 /* now we know hostname. resolve it and keep only the IP address */
2147 if (tor_inet_aton(hostname, &in) == 0) {
2148 /* then we have to resolve it */
2149 explicit_ip = 0;
2150 rent = (struct hostent *)gethostbyname(hostname);
2151 if (!rent) {
2152 uint32_t interface_ip;
2154 if (explicit_hostname) {
2155 log_fn(warn_severity, LD_CONFIG,
2156 "Could not resolve local Address '%s'. Failing.", hostname);
2157 return -1;
2159 log_fn(notice_severity, LD_CONFIG,
2160 "Could not resolve guessed local hostname '%s'. "
2161 "Trying something else.", hostname);
2162 if (get_interface_address(warn_severity, &interface_ip)) {
2163 log_fn(warn_severity, LD_CONFIG,
2164 "Could not get local interface IP address. Failing.");
2165 return -1;
2167 from_interface = 1;
2168 in.s_addr = htonl(interface_ip);
2169 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2170 log_fn(notice_severity, LD_CONFIG, "Learned IP address '%s' for "
2171 "local interface. Using that.", tmpbuf);
2172 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2173 } else {
2174 tor_assert(rent->h_length == 4);
2175 memcpy(&in.s_addr, rent->h_addr, rent->h_length);
2177 if (!explicit_hostname &&
2178 is_internal_IP(ntohl(in.s_addr), 0)) {
2179 uint32_t interface_ip;
2181 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2182 log_fn(notice_severity, LD_CONFIG, "Guessed local hostname '%s' "
2183 "resolves to a private IP address (%s). Trying something "
2184 "else.", hostname, tmpbuf);
2186 if (get_interface_address(warn_severity, &interface_ip)) {
2187 log_fn(warn_severity, LD_CONFIG,
2188 "Could not get local interface IP address. Too bad.");
2189 } else if (is_internal_IP(interface_ip, 0)) {
2190 struct in_addr in2;
2191 in2.s_addr = htonl(interface_ip);
2192 tor_inet_ntoa(&in2,tmpbuf,sizeof(tmpbuf));
2193 log_fn(notice_severity, LD_CONFIG,
2194 "Interface IP address '%s' is a private address too. "
2195 "Ignoring.", tmpbuf);
2196 } else {
2197 from_interface = 1;
2198 in.s_addr = htonl(interface_ip);
2199 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2200 log_fn(notice_severity, LD_CONFIG,
2201 "Learned IP address '%s' for local interface."
2202 " Using that.", tmpbuf);
2203 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2209 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2210 if (is_internal_IP(ntohl(in.s_addr), 0) &&
2211 options->_PublishServerDescriptor) {
2212 /* make sure we're ok with publishing an internal IP */
2213 if (!options->DirServers && !options->AlternateDirAuthority) {
2214 /* if they are using the default dirservers, disallow internal IPs
2215 * always. */
2216 log_fn(warn_severity, LD_CONFIG,
2217 "Address '%s' resolves to private IP address '%s'. "
2218 "Tor servers that use the default DirServers must have public "
2219 "IP addresses.", hostname, tmpbuf);
2220 return -1;
2222 if (!explicit_ip) {
2223 /* even if they've set their own dirservers, require an explicit IP if
2224 * they're using an internal address. */
2225 log_fn(warn_severity, LD_CONFIG, "Address '%s' resolves to private "
2226 "IP address '%s'. Please set the Address config option to be "
2227 "the IP address you want to use.", hostname, tmpbuf);
2228 return -1;
2232 log_debug(LD_CONFIG, "Resolved Address to '%s'.", tmpbuf);
2233 *addr_out = ntohl(in.s_addr);
2234 if (last_resolved_addr && last_resolved_addr != *addr_out) {
2235 /* Leave this as a notice, regardless of the requested severity,
2236 * at least until dynamic IP address support becomes bulletproof. */
2237 log_notice(LD_NET,
2238 "Your IP address seems to have changed to %s. Updating.",
2239 tmpbuf);
2240 ip_address_changed(0);
2242 if (last_resolved_addr != *addr_out) {
2243 const char *method;
2244 const char *h = hostname;
2245 if (explicit_ip) {
2246 method = "CONFIGURED";
2247 h = NULL;
2248 } else if (explicit_hostname) {
2249 method = "RESOLVED";
2250 } else if (from_interface) {
2251 method = "INTERFACE";
2252 h = NULL;
2253 } else {
2254 method = "GETHOSTNAME";
2256 control_event_server_status(LOG_NOTICE,
2257 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s %s%s",
2258 tmpbuf, method, h?"HOSTNAME=":"", h);
2260 last_resolved_addr = *addr_out;
2261 if (hostname_out)
2262 *hostname_out = tor_strdup(hostname);
2263 return 0;
2266 /** Return true iff <b>ip</b> (in host order) is judged to be on the
2267 * same network as us, or on a private network.
2270 is_local_IP(uint32_t ip)
2272 if (is_internal_IP(ip, 0))
2273 return 1;
2274 /* Check whether ip is on the same /24 as we are. */
2275 if (get_options()->EnforceDistinctSubnets == 0)
2276 return 0;
2277 /* It's possible that this next check will hit before the first time
2278 * resolve_my_address actually succeeds. (For clients, it is likely that
2279 * resolve_my_address will never be called at all). In those cases,
2280 * last_resolved_addr will be 0, and so checking to see whether ip is on the
2281 * same /24 as last_resolved_addr will be the same as checking whether it
2282 * was on net 0, which is already done by is_internal_IP.
2284 if ((last_resolved_addr & 0xffffff00ul) == (ip & 0xffffff00ul))
2285 return 1;
2286 return 0;
2289 /** Called when we don't have a nickname set. Try to guess a good nickname
2290 * based on the hostname, and return it in a newly allocated string. If we
2291 * can't, return NULL and let the caller warn if it wants to. */
2292 static char *
2293 get_default_nickname(void)
2295 static const char * const bad_default_nicknames[] = {
2296 "localhost",
2297 NULL,
2299 char localhostname[256];
2300 char *cp, *out, *outp;
2301 int i;
2303 if (gethostname(localhostname, sizeof(localhostname)) < 0)
2304 return NULL;
2306 /* Put it in lowercase; stop at the first dot. */
2307 if ((cp = strchr(localhostname, '.')))
2308 *cp = '\0';
2309 tor_strlower(localhostname);
2311 /* Strip invalid characters. */
2312 cp = localhostname;
2313 out = outp = tor_malloc(strlen(localhostname) + 1);
2314 while (*cp) {
2315 if (strchr(LEGAL_NICKNAME_CHARACTERS, *cp))
2316 *outp++ = *cp++;
2317 else
2318 cp++;
2320 *outp = '\0';
2322 /* Enforce length. */
2323 if (strlen(out) > MAX_NICKNAME_LEN)
2324 out[MAX_NICKNAME_LEN]='\0';
2326 /* Check for dumb names. */
2327 for (i = 0; bad_default_nicknames[i]; ++i) {
2328 if (!strcmp(out, bad_default_nicknames[i])) {
2329 tor_free(out);
2330 return NULL;
2334 return out;
2337 /** Release storage held by <b>options</b>. */
2338 static void
2339 config_free(config_format_t *fmt, void *options)
2341 int i;
2343 tor_assert(options);
2345 for (i=0; fmt->vars[i].name; ++i)
2346 option_clear(fmt, options, &(fmt->vars[i]));
2347 if (fmt->extra) {
2348 config_line_t **linep = STRUCT_VAR_P(options, fmt->extra->var_offset);
2349 config_free_lines(*linep);
2350 *linep = NULL;
2352 tor_free(options);
2355 /** Return true iff a and b contain identical keys and values in identical
2356 * order. */
2357 static int
2358 config_lines_eq(config_line_t *a, config_line_t *b)
2360 while (a && b) {
2361 if (strcasecmp(a->key, b->key) || strcmp(a->value, b->value))
2362 return 0;
2363 a = a->next;
2364 b = b->next;
2366 if (a || b)
2367 return 0;
2368 return 1;
2371 /** Return true iff the option <b>name</b> has the same value in <b>o1</b>
2372 * and <b>o2</b>. Must not be called for LINELIST_S or OBSOLETE options.
2374 static int
2375 option_is_same(config_format_t *fmt,
2376 or_options_t *o1, or_options_t *o2, const char *name)
2378 config_line_t *c1, *c2;
2379 int r = 1;
2380 CHECK(fmt, o1);
2381 CHECK(fmt, o2);
2383 c1 = get_assigned_option(fmt, o1, name, 0);
2384 c2 = get_assigned_option(fmt, o2, name, 0);
2385 r = config_lines_eq(c1, c2);
2386 config_free_lines(c1);
2387 config_free_lines(c2);
2388 return r;
2391 /** Copy storage held by <b>old</b> into a new or_options_t and return it. */
2392 static or_options_t *
2393 options_dup(config_format_t *fmt, or_options_t *old)
2395 or_options_t *newopts;
2396 int i;
2397 config_line_t *line;
2399 newopts = config_alloc(fmt);
2400 for (i=0; fmt->vars[i].name; ++i) {
2401 if (fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
2402 continue;
2403 if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE)
2404 continue;
2405 line = get_assigned_option(fmt, old, fmt->vars[i].name, 0);
2406 if (line) {
2407 char *msg = NULL;
2408 if (config_assign(fmt, newopts, line, 0, 0, &msg) < 0) {
2409 log_err(LD_BUG, "Config_get_assigned_option() generated "
2410 "something we couldn't config_assign(): %s", msg);
2411 tor_free(msg);
2412 tor_assert(0);
2415 config_free_lines(line);
2417 return newopts;
2420 /** Return a new empty or_options_t. Used for testing. */
2421 or_options_t *
2422 options_new(void)
2424 return config_alloc(&options_format);
2427 /** Set <b>options</b> to hold reasonable defaults for most options.
2428 * Each option defaults to zero. */
2429 void
2430 options_init(or_options_t *options)
2432 config_init(&options_format, options);
2435 /* Set all vars in the configuration object 'options' to their default
2436 * values. */
2437 static void
2438 config_init(config_format_t *fmt, void *options)
2440 int i;
2441 config_var_t *var;
2442 CHECK(fmt, options);
2444 for (i=0; fmt->vars[i].name; ++i) {
2445 var = &fmt->vars[i];
2446 if (!var->initvalue)
2447 continue; /* defaults to NULL or 0 */
2448 option_reset(fmt, options, var, 1);
2452 /** Allocate and return a new string holding the written-out values of the vars
2453 * in 'options'. If 'minimal', do not write out any default-valued vars.
2454 * Else, if comment_defaults, write default values as comments.
2456 static char *
2457 config_dump(config_format_t *fmt, void *options, int minimal,
2458 int comment_defaults)
2460 smartlist_t *elements;
2461 or_options_t *defaults;
2462 config_line_t *line, *assigned;
2463 char *result;
2464 int i;
2465 const char *desc;
2466 char *msg = NULL;
2468 defaults = config_alloc(fmt);
2469 config_init(fmt, defaults);
2471 /* XXX use a 1 here so we don't add a new log line while dumping */
2472 if (fmt->validate_fn(NULL,defaults, 1, &msg) < 0) {
2473 log_err(LD_BUG, "Failed to validate default config.");
2474 tor_free(msg);
2475 tor_assert(0);
2478 elements = smartlist_create();
2479 for (i=0; fmt->vars[i].name; ++i) {
2480 int comment_option = 0;
2481 if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE ||
2482 fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
2483 continue;
2484 /* Don't save 'hidden' control variables. */
2485 if (!strcmpstart(fmt->vars[i].name, "__"))
2486 continue;
2487 if (minimal && option_is_same(fmt, options, defaults, fmt->vars[i].name))
2488 continue;
2489 else if (comment_defaults &&
2490 option_is_same(fmt, options, defaults, fmt->vars[i].name))
2491 comment_option = 1;
2493 desc = config_find_description(fmt, fmt->vars[i].name);
2494 line = assigned = get_assigned_option(fmt, options, fmt->vars[i].name, 1);
2496 if (line && desc) {
2497 /* Only dump the description if there's something to describe. */
2498 wrap_string(elements, desc, 78, "# ", "# ");
2501 for (; line; line = line->next) {
2502 size_t len = strlen(line->key) + strlen(line->value) + 5;
2503 char *tmp;
2504 tmp = tor_malloc(len);
2505 if (tor_snprintf(tmp, len, "%s%s %s\n",
2506 comment_option ? "# " : "",
2507 line->key, line->value)<0) {
2508 log_err(LD_BUG,"Internal error writing option value");
2509 tor_assert(0);
2511 smartlist_add(elements, tmp);
2513 config_free_lines(assigned);
2516 if (fmt->extra) {
2517 line = *(config_line_t**)STRUCT_VAR_P(options, fmt->extra->var_offset);
2518 for (; line; line = line->next) {
2519 size_t len = strlen(line->key) + strlen(line->value) + 3;
2520 char *tmp;
2521 tmp = tor_malloc(len);
2522 if (tor_snprintf(tmp, len, "%s %s\n", line->key, line->value)<0) {
2523 log_err(LD_BUG,"Internal error writing option value");
2524 tor_assert(0);
2526 smartlist_add(elements, tmp);
2530 result = smartlist_join_strings(elements, "", 0, NULL);
2531 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
2532 smartlist_free(elements);
2533 config_free(fmt, defaults);
2534 return result;
2537 /** Return a string containing a possible configuration file that would give
2538 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
2539 * include options that are the same as Tor's defaults.
2541 static char *
2542 options_dump(or_options_t *options, int minimal)
2544 return config_dump(&options_format, options, minimal, 0);
2547 /** Return 0 if every element of sl is a string holding a decimal
2548 * representation of a port number, or if sl is NULL.
2549 * Otherwise set *msg and return -1. */
2550 static int
2551 validate_ports_csv(smartlist_t *sl, const char *name, char **msg)
2553 int i;
2554 char buf[1024];
2555 tor_assert(name);
2557 if (!sl)
2558 return 0;
2560 SMARTLIST_FOREACH(sl, const char *, cp,
2562 i = atoi(cp);
2563 if (i < 1 || i > 65535) {
2564 int r = tor_snprintf(buf, sizeof(buf),
2565 "Port '%s' out of range in %s", cp, name);
2566 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2567 return -1;
2570 return 0;
2573 /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
2574 * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
2575 * Else return 0.
2577 static int
2578 ensure_bandwidth_cap(uint64_t *value, const char *desc, char **msg)
2580 int r;
2581 char buf[1024];
2582 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2583 /* This handles an understandable special case where somebody says "2gb"
2584 * whereas our actual maximum is 2gb-1 (INT_MAX) */
2585 --*value;
2587 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2588 r = tor_snprintf(buf, sizeof(buf), "%s ("U64_FORMAT") must be at most %d",
2589 desc, U64_PRINTF_ARG(*value),
2590 ROUTER_MAX_DECLARED_BANDWIDTH);
2591 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2592 return -1;
2594 return 0;
2597 /** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
2598 * and write it to <b>options</b>-\>_PublishServerDescriptor. Treat "1"
2599 * as "v2,v3" unless BridgeRelay is 1, in which case treat it as "bridge".
2600 * Treat "0" as "".
2601 * Return 0 on success or -1 if not a recognized authority type (in which
2602 * case the value of _PublishServerDescriptor is undefined). */
2603 static int
2604 compute_publishserverdescriptor(or_options_t *options)
2606 smartlist_t *list = options->PublishServerDescriptor;
2607 authority_type_t *auth = &options->_PublishServerDescriptor;
2608 *auth = NO_AUTHORITY;
2609 if (!list) /* empty list, answer is none */
2610 return 0;
2611 SMARTLIST_FOREACH(list, const char *, string, {
2612 if (!strcasecmp(string, "v1"))
2613 *auth |= V1_AUTHORITY;
2614 else if (!strcmp(string, "1"))
2615 if (options->BridgeRelay)
2616 *auth |= BRIDGE_AUTHORITY;
2617 else
2618 *auth |= V2_AUTHORITY | V3_AUTHORITY;
2619 else if (!strcasecmp(string, "v2"))
2620 *auth |= V2_AUTHORITY;
2621 else if (!strcasecmp(string, "v3"))
2622 *auth |= V3_AUTHORITY;
2623 else if (!strcasecmp(string, "bridge"))
2624 *auth |= BRIDGE_AUTHORITY;
2625 else if (!strcasecmp(string, "hidserv"))
2626 *auth |= HIDSERV_AUTHORITY;
2627 else if (!strcasecmp(string, "") || !strcmp(string, "0"))
2628 /* no authority */;
2629 else
2630 return -1;
2632 return 0;
2635 /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
2636 * services can overload the directory system. */
2637 #define MIN_REND_POST_PERIOD (10*60)
2639 /** Highest allowable value for RendPostPeriod. */
2640 #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
2642 /** Return 0 if every setting in <b>options</b> is reasonable, and a
2643 * permissible transition from <b>old_options</b>. Else return -1.
2644 * Should have no side effects, except for normalizing the contents of
2645 * <b>options</b>.
2647 * On error, tor_strdup an error explanation into *<b>msg</b>.
2649 * XXX
2650 * If <b>from_setconf</b>, we were called by the controller, and our
2651 * Log line should stay empty. If it's 0, then give us a default log
2652 * if there are no logs defined.
2654 static int
2655 options_validate(or_options_t *old_options, or_options_t *options,
2656 int from_setconf, char **msg)
2658 int i, r;
2659 config_line_t *cl;
2660 const char *uname = get_uname();
2661 char buf[1024];
2662 #define REJECT(arg) \
2663 STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
2664 #define COMPLAIN(arg) STMT_BEGIN log(LOG_WARN, LD_CONFIG, arg); STMT_END
2666 tor_assert(msg);
2667 *msg = NULL;
2669 if (options->ORPort < 0 || options->ORPort > 65535)
2670 REJECT("ORPort option out of bounds.");
2672 if (server_mode(options) &&
2673 (!strcmpstart(uname, "Windows 95") ||
2674 !strcmpstart(uname, "Windows 98") ||
2675 !strcmpstart(uname, "Windows Me"))) {
2676 log(LOG_WARN, LD_CONFIG, "Tor is running as a server, but you are "
2677 "running %s; this probably won't work. See "
2678 "http://wiki.noreply.org/noreply/TheOnionRouter/TorFAQ#ServerOS "
2679 "for details.", uname);
2682 if (options->ORPort == 0 && options->ORListenAddress != NULL)
2683 REJECT("ORPort must be defined if ORListenAddress is defined.");
2685 if (options->DirPort == 0 && options->DirListenAddress != NULL)
2686 REJECT("DirPort must be defined if DirListenAddress is defined.");
2688 if (options->DNSPort == 0 && options->DNSListenAddress != NULL)
2689 REJECT("DNSPort must be defined if DNSListenAddress is defined.");
2691 if (options->ControlPort == 0 && options->ControlListenAddress != NULL)
2692 REJECT("ControlPort must be defined if ControlListenAddress is defined.");
2694 if (options->TransPort == 0 && options->TransListenAddress != NULL)
2695 REJECT("TransPort must be defined if TransListenAddress is defined.");
2697 if (options->NatdPort == 0 && options->NatdListenAddress != NULL)
2698 REJECT("NatdPort must be defined if NatdListenAddress is defined.");
2700 /* Don't gripe about SocksPort 0 with SocksListenAddress set; a standard
2701 * configuration does this. */
2703 for (i = 0; i < 3; ++i) {
2704 int is_socks = i==0;
2705 int is_trans = i==1;
2706 config_line_t *line, *opt, *old;
2707 const char *tp;
2708 if (is_socks) {
2709 opt = options->SocksListenAddress;
2710 old = old_options ? old_options->SocksListenAddress : NULL;
2711 tp = "SOCKS proxy";
2712 } else if (is_trans) {
2713 opt = options->TransListenAddress;
2714 old = old_options ? old_options->TransListenAddress : NULL;
2715 tp = "transparent proxy";
2716 } else {
2717 opt = options->NatdListenAddress;
2718 old = old_options ? old_options->NatdListenAddress : NULL;
2719 tp = "natd proxy";
2722 for (line = opt; line; line = line->next) {
2723 char *address = NULL;
2724 uint16_t port;
2725 uint32_t addr;
2726 if (parse_addr_port(LOG_WARN, line->value, &address, &addr, &port)<0)
2727 continue; /* We'll warn about this later. */
2728 if (!is_internal_IP(addr, 1) &&
2729 (!old_options || !config_lines_eq(old, opt))) {
2730 log_warn(LD_CONFIG,
2731 "You specified a public address '%s' for a %s. Other "
2732 "people on the Internet might find your computer and use it as "
2733 "an open %s. Please don't allow this unless you have "
2734 "a good reason.", address, tp, tp);
2736 tor_free(address);
2740 if (validate_data_directory(options)<0)
2741 REJECT("Invalid DataDirectory");
2743 if (options->Nickname == NULL) {
2744 if (server_mode(options)) {
2745 if (!(options->Nickname = get_default_nickname())) {
2746 log_notice(LD_CONFIG, "Couldn't pick a nickname based on "
2747 "our hostname; using %s instead.", UNNAMED_ROUTER_NICKNAME);
2748 options->Nickname = tor_strdup(UNNAMED_ROUTER_NICKNAME);
2749 } else {
2750 log_notice(LD_CONFIG, "Choosing default nickname '%s'",
2751 options->Nickname);
2754 } else {
2755 if (!is_legal_nickname(options->Nickname)) {
2756 r = tor_snprintf(buf, sizeof(buf),
2757 "Nickname '%s' is wrong length or contains illegal characters.",
2758 options->Nickname);
2759 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2760 return -1;
2764 if (server_mode(options) && !options->ContactInfo)
2765 log(LOG_NOTICE, LD_CONFIG, "Your ContactInfo config option is not set. "
2766 "Please consider setting it, so we can contact you if your server is "
2767 "misconfigured or something else goes wrong.");
2769 /* Special case on first boot if no Log options are given. */
2770 if (!options->Logs && !options->RunAsDaemon && !from_setconf)
2771 config_line_append(&options->Logs, "Log", "notice stdout");
2773 if (options_init_logs(options, 1)<0) /* Validate the log(s) */
2774 REJECT("Failed to validate Log options. See logs for details.");
2776 if (options->NoPublish) {
2777 log(LOG_WARN, LD_CONFIG,
2778 "NoPublish is obsolete. Use PublishServerDescriptor instead.");
2779 SMARTLIST_FOREACH(options->PublishServerDescriptor, char *, s,
2780 tor_free(s));
2781 smartlist_clear(options->PublishServerDescriptor);
2784 if (authdir_mode(options)) {
2785 /* confirm that our address isn't broken, so we can complain now */
2786 uint32_t tmp;
2787 if (resolve_my_address(LOG_WARN, options, &tmp, NULL) < 0)
2788 REJECT("Failed to resolve/guess local address. See logs for details.");
2791 #ifndef MS_WINDOWS
2792 if (options->RunAsDaemon && torrc_fname && path_is_relative(torrc_fname))
2793 REJECT("Can't use a relative path to torrc when RunAsDaemon is set.");
2794 #endif
2796 if (options->SocksPort < 0 || options->SocksPort > 65535)
2797 REJECT("SocksPort option out of bounds.");
2799 if (options->DNSPort < 0 || options->DNSPort > 65535)
2800 REJECT("DNSPort option out of bounds.");
2802 if (options->TransPort < 0 || options->TransPort > 65535)
2803 REJECT("TransPort option out of bounds.");
2805 if (options->NatdPort < 0 || options->NatdPort > 65535)
2806 REJECT("NatdPort option out of bounds.");
2808 if (options->SocksPort == 0 && options->TransPort == 0 &&
2809 options->NatdPort == 0 && options->ORPort == 0 &&
2810 options->DNSPort == 0 && !options->RendConfigLines)
2811 log(LOG_WARN, LD_CONFIG,
2812 "SocksPort, TransPort, NatdPort, DNSPort, and ORPort are all "
2813 "undefined, and there aren't any hidden services configured. "
2814 "Tor will still run, but probably won't do anything.");
2816 if (options->ControlPort < 0 || options->ControlPort > 65535)
2817 REJECT("ControlPort option out of bounds.");
2819 if (options->DirPort < 0 || options->DirPort > 65535)
2820 REJECT("DirPort option out of bounds.");
2822 #ifndef USE_TRANSPARENT
2823 if (options->TransPort || options->TransListenAddress)
2824 REJECT("TransPort and TransListenAddress are disabled in this build.");
2825 #endif
2827 if (options->StrictExitNodes &&
2828 (!options->ExitNodes || !strlen(options->ExitNodes)) &&
2829 (!old_options ||
2830 (old_options->StrictExitNodes != options->StrictExitNodes) ||
2831 (!opt_streq(old_options->ExitNodes, options->ExitNodes))))
2832 COMPLAIN("StrictExitNodes set, but no ExitNodes listed.");
2834 if (options->StrictEntryNodes &&
2835 (!options->EntryNodes || !strlen(options->EntryNodes)) &&
2836 (!old_options ||
2837 (old_options->StrictEntryNodes != options->StrictEntryNodes) ||
2838 (!opt_streq(old_options->EntryNodes, options->EntryNodes))))
2839 COMPLAIN("StrictEntryNodes set, but no EntryNodes listed.");
2841 if (options->AuthoritativeDir) {
2842 if (!options->ContactInfo)
2843 REJECT("Authoritative directory servers must set ContactInfo");
2844 if (options->V1AuthoritativeDir && !options->RecommendedVersions)
2845 REJECT("V1 auth dir servers must set RecommendedVersions.");
2846 if (!options->RecommendedClientVersions)
2847 options->RecommendedClientVersions =
2848 config_lines_dup(options->RecommendedVersions);
2849 if (!options->RecommendedServerVersions)
2850 options->RecommendedServerVersions =
2851 config_lines_dup(options->RecommendedVersions);
2852 if (options->VersioningAuthoritativeDir &&
2853 (!options->RecommendedClientVersions ||
2854 !options->RecommendedServerVersions))
2855 REJECT("Versioning auth dir servers must set Recommended*Versions.");
2856 if (options->UseEntryGuards) {
2857 log_info(LD_CONFIG, "Authoritative directory servers can't set "
2858 "UseEntryGuards. Disabling.");
2859 options->UseEntryGuards = 0;
2861 if (!options->DownloadExtraInfo && authdir_mode_any_main(options)) {
2862 log_info(LD_CONFIG, "Authoritative directories always try to download "
2863 "extra-info documents. Setting DownloadExtraInfo.");
2864 options->DownloadExtraInfo = 1;
2866 if (!(options->BridgeAuthoritativeDir || options->HSAuthoritativeDir ||
2867 options->V1AuthoritativeDir || options->V2AuthoritativeDir ||
2868 options->V3AuthoritativeDir))
2869 REJECT("AuthoritativeDir is set, but none of "
2870 "(Bridge/HS/V1/V2/V3)AuthoriativeDir is set.");
2873 if (options->AuthoritativeDir && !options->DirPort)
2874 REJECT("Running as authoritative directory, but no DirPort set.");
2876 if (options->AuthoritativeDir && !options->ORPort)
2877 REJECT("Running as authoritative directory, but no ORPort set.");
2879 if (options->AuthoritativeDir && options->ClientOnly)
2880 REJECT("Running as authoritative directory, but ClientOnly also set.");
2882 if (options->HSAuthorityRecordStats && !options->HSAuthoritativeDir)
2883 REJECT("HSAuthorityRecordStats is set but we're not running as "
2884 "a hidden service authority.");
2886 if (options->HidServDirectoryV2 && !options->DirPort)
2887 REJECT("Running as hidden service directory, but no DirPort set.");
2889 if (options->ConnLimit <= 0) {
2890 r = tor_snprintf(buf, sizeof(buf),
2891 "ConnLimit must be greater than 0, but was set to %d",
2892 options->ConnLimit);
2893 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2894 return -1;
2897 if (validate_ports_csv(options->FirewallPorts, "FirewallPorts", msg) < 0)
2898 return -1;
2900 if (validate_ports_csv(options->LongLivedPorts, "LongLivedPorts", msg) < 0)
2901 return -1;
2903 if (validate_ports_csv(options->RejectPlaintextPorts,
2904 "RejectPlaintextPorts", msg) < 0)
2905 return -1;
2907 if (validate_ports_csv(options->WarnPlaintextPorts,
2908 "WarnPlaintextPorts", msg) < 0)
2909 return -1;
2911 if (options->FascistFirewall && !options->ReachableAddresses) {
2912 if (options->FirewallPorts && smartlist_len(options->FirewallPorts)) {
2913 /* We already have firewall ports set, so migrate them to
2914 * ReachableAddresses, which will set ReachableORAddresses and
2915 * ReachableDirAddresses if they aren't set explicitly. */
2916 smartlist_t *instead = smartlist_create();
2917 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
2918 new_line->key = tor_strdup("ReachableAddresses");
2919 /* If we're configured with the old format, we need to prepend some
2920 * open ports. */
2921 SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
2923 int p = atoi(portno);
2924 char *s;
2925 if (p<0) continue;
2926 s = tor_malloc(16);
2927 tor_snprintf(s, 16, "*:%d", p);
2928 smartlist_add(instead, s);
2930 new_line->value = smartlist_join_strings(instead,",",0,NULL);
2931 /* These have been deprecated since 0.1.1.5-alpha-cvs */
2932 log(LOG_NOTICE, LD_CONFIG,
2933 "Converting FascistFirewall and FirewallPorts "
2934 "config options to new format: \"ReachableAddresses %s\"",
2935 new_line->value);
2936 options->ReachableAddresses = new_line;
2937 SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
2938 smartlist_free(instead);
2939 } else {
2940 /* We do not have FirewallPorts set, so add 80 to
2941 * ReachableDirAddresses, and 443 to ReachableORAddresses. */
2942 if (!options->ReachableDirAddresses) {
2943 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
2944 new_line->key = tor_strdup("ReachableDirAddresses");
2945 new_line->value = tor_strdup("*:80");
2946 options->ReachableDirAddresses = new_line;
2947 log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
2948 "to new format: \"ReachableDirAddresses *:80\"");
2950 if (!options->ReachableORAddresses) {
2951 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
2952 new_line->key = tor_strdup("ReachableORAddresses");
2953 new_line->value = tor_strdup("*:443");
2954 options->ReachableORAddresses = new_line;
2955 log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
2956 "to new format: \"ReachableORAddresses *:443\"");
2961 for (i=0; i<3; i++) {
2962 config_line_t **linep =
2963 (i==0) ? &options->ReachableAddresses :
2964 (i==1) ? &options->ReachableORAddresses :
2965 &options->ReachableDirAddresses;
2966 if (!*linep)
2967 continue;
2968 /* We need to end with a reject *:*, not an implicit accept *:* */
2969 for (;;) {
2970 if (!strcmp((*linep)->value, "reject *:*")) /* already there */
2971 break;
2972 linep = &((*linep)->next);
2973 if (!*linep) {
2974 *linep = tor_malloc_zero(sizeof(config_line_t));
2975 (*linep)->key = tor_strdup(
2976 (i==0) ? "ReachableAddresses" :
2977 (i==1) ? "ReachableORAddresses" :
2978 "ReachableDirAddresses");
2979 (*linep)->value = tor_strdup("reject *:*");
2980 break;
2985 if ((options->ReachableAddresses ||
2986 options->ReachableORAddresses ||
2987 options->ReachableDirAddresses) &&
2988 server_mode(options))
2989 REJECT("Servers must be able to freely connect to the rest "
2990 "of the Internet, so they must not set Reachable*Addresses "
2991 "or FascistFirewall.");
2993 if (options->UseBridges &&
2994 server_mode(options))
2995 REJECT("Servers must be able to freely connect to the rest "
2996 "of the Internet, so they must not set UseBridges.");
2998 options->_AllowInvalid = 0;
2999 if (options->AllowInvalidNodes) {
3000 SMARTLIST_FOREACH(options->AllowInvalidNodes, const char *, cp, {
3001 if (!strcasecmp(cp, "entry"))
3002 options->_AllowInvalid |= ALLOW_INVALID_ENTRY;
3003 else if (!strcasecmp(cp, "exit"))
3004 options->_AllowInvalid |= ALLOW_INVALID_EXIT;
3005 else if (!strcasecmp(cp, "middle"))
3006 options->_AllowInvalid |= ALLOW_INVALID_MIDDLE;
3007 else if (!strcasecmp(cp, "introduction"))
3008 options->_AllowInvalid |= ALLOW_INVALID_INTRODUCTION;
3009 else if (!strcasecmp(cp, "rendezvous"))
3010 options->_AllowInvalid |= ALLOW_INVALID_RENDEZVOUS;
3011 else {
3012 r = tor_snprintf(buf, sizeof(buf),
3013 "Unrecognized value '%s' in AllowInvalidNodes", cp);
3014 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3015 return -1;
3020 if (compute_publishserverdescriptor(options) < 0) {
3021 r = tor_snprintf(buf, sizeof(buf),
3022 "Unrecognized value in PublishServerDescriptor");
3023 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3024 return -1;
3027 if (options->MinUptimeHidServDirectoryV2 < 0) {
3028 log_warn(LD_CONFIG, "MinUptimeHidServDirectoryV2 option must be at "
3029 "least 0 seconds. Changing to 0.");
3030 options->MinUptimeHidServDirectoryV2 = 0;
3033 if (options->RendPostPeriod < MIN_REND_POST_PERIOD) {
3034 log(LOG_WARN,LD_CONFIG,"RendPostPeriod option must be at least %d seconds."
3035 " Clipping.", MIN_REND_POST_PERIOD);
3036 options->RendPostPeriod = MIN_REND_POST_PERIOD;
3039 if (options->RendPostPeriod > MAX_DIR_PERIOD) {
3040 log(LOG_WARN, LD_CONFIG, "RendPostPeriod is too large; clipping to %ds.",
3041 MAX_DIR_PERIOD);
3042 options->RendPostPeriod = MAX_DIR_PERIOD;
3045 if (options->KeepalivePeriod < 1)
3046 REJECT("KeepalivePeriod option must be positive.");
3048 if (ensure_bandwidth_cap(&options->BandwidthRate,
3049 "BandwidthRate", msg) < 0)
3050 return -1;
3051 if (ensure_bandwidth_cap(&options->BandwidthBurst,
3052 "BandwidthBurst", msg) < 0)
3053 return -1;
3054 if (ensure_bandwidth_cap(&options->MaxAdvertisedBandwidth,
3055 "MaxAdvertisedBandwidth", msg) < 0)
3056 return -1;
3057 if (ensure_bandwidth_cap(&options->RelayBandwidthRate,
3058 "RelayBandwidthRate", msg) < 0)
3059 return -1;
3060 if (ensure_bandwidth_cap(&options->RelayBandwidthBurst,
3061 "RelayBandwidthBurst", msg) < 0)
3062 return -1;
3064 if (server_mode(options)) {
3065 if (options->BandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH*2) {
3066 r = tor_snprintf(buf, sizeof(buf),
3067 "BandwidthRate is set to %d bytes/second. "
3068 "For servers, it must be at least %d.",
3069 (int)options->BandwidthRate,
3070 ROUTER_REQUIRED_MIN_BANDWIDTH*2);
3071 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3072 return -1;
3073 } else if (options->MaxAdvertisedBandwidth <
3074 ROUTER_REQUIRED_MIN_BANDWIDTH) {
3075 r = tor_snprintf(buf, sizeof(buf),
3076 "MaxAdvertisedBandwidth is set to %d bytes/second. "
3077 "For servers, it must be at least %d.",
3078 (int)options->MaxAdvertisedBandwidth,
3079 ROUTER_REQUIRED_MIN_BANDWIDTH);
3080 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3081 return -1;
3083 if (options->RelayBandwidthRate &&
3084 options->RelayBandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
3085 r = tor_snprintf(buf, sizeof(buf),
3086 "RelayBandwidthRate is set to %d bytes/second. "
3087 "For servers, it must be at least %d.",
3088 (int)options->RelayBandwidthRate,
3089 ROUTER_REQUIRED_MIN_BANDWIDTH);
3090 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3091 return -1;
3095 if (options->RelayBandwidthRate && !options->RelayBandwidthBurst)
3096 options->RelayBandwidthBurst = options->RelayBandwidthRate;
3098 if (options->RelayBandwidthRate > options->RelayBandwidthBurst)
3099 REJECT("RelayBandwidthBurst must be at least equal "
3100 "to RelayBandwidthRate.");
3102 if (options->BandwidthRate > options->BandwidthBurst)
3103 REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
3105 if (accounting_parse_options(options, 1)<0)
3106 REJECT("Failed to parse accounting options. See logs for details.");
3108 if (options->HttpProxy) { /* parse it now */
3109 if (parse_addr_port(LOG_WARN, options->HttpProxy, NULL,
3110 &options->HttpProxyAddr, &options->HttpProxyPort) < 0)
3111 REJECT("HttpProxy failed to parse or resolve. Please fix.");
3112 if (options->HttpProxyPort == 0) { /* give it a default */
3113 options->HttpProxyPort = 80;
3117 if (options->HttpProxyAuthenticator) {
3118 if (strlen(options->HttpProxyAuthenticator) >= 48)
3119 REJECT("HttpProxyAuthenticator is too long (>= 48 chars).");
3122 if (options->HttpsProxy) { /* parse it now */
3123 if (parse_addr_port(LOG_WARN, options->HttpsProxy, NULL,
3124 &options->HttpsProxyAddr, &options->HttpsProxyPort) <0)
3125 REJECT("HttpsProxy failed to parse or resolve. Please fix.");
3126 if (options->HttpsProxyPort == 0) { /* give it a default */
3127 options->HttpsProxyPort = 443;
3131 if (options->HttpsProxyAuthenticator) {
3132 if (strlen(options->HttpsProxyAuthenticator) >= 48)
3133 REJECT("HttpsProxyAuthenticator is too long (>= 48 chars).");
3136 if (options->HashedControlPassword) {
3137 smartlist_t *sl = decode_hashed_passwords(options->HashedControlPassword);
3138 if (!sl) {
3139 REJECT("Bad HashedControlPassword: wrong length or bad encoding");
3140 } else {
3141 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3142 smartlist_free(sl);
3146 if (options->ControlListenAddress) {
3147 int all_are_local = 1;
3148 config_line_t *ln;
3149 for (ln = options->ControlListenAddress; ln; ln = ln->next) {
3150 if (strcmpstart(ln->value, "127."))
3151 all_are_local = 0;
3153 if (!all_are_local) {
3154 if (!options->HashedControlPassword && !options->CookieAuthentication) {
3155 log_warn(LD_CONFIG, "You have a ControlListenAddress set to accept "
3156 "connections from a non-local address. This means that "
3157 "any program on the internet can reconfigure your Tor. "
3158 "That's so bad that I'm closing your ControlPort for you.");
3159 options->ControlPort = 0;
3160 } else {
3161 log_warn(LD_CONFIG, "You have a ControlListenAddress set to accept "
3162 "connections from a non-local address. This means that "
3163 "programs not running on your computer can reconfigure your "
3164 "Tor. That's pretty bad!");
3169 if (options->ControlPort && !options->HashedControlPassword &&
3170 !options->CookieAuthentication) {
3171 log_warn(LD_CONFIG, "ControlPort is open, but no authentication method "
3172 "has been configured. This means that any program on your "
3173 "computer can reconfigure your Tor. That's bad! You should "
3174 "upgrade your Tor controller as soon as possible.");
3177 if (options->UseEntryGuards && ! options->NumEntryGuards)
3178 REJECT("Cannot enable UseEntryGuards with NumEntryGuards set to 0");
3180 if (check_nickname_list(options->ExitNodes, "ExitNodes", msg))
3181 return -1;
3182 if (check_nickname_list(options->EntryNodes, "EntryNodes", msg))
3183 return -1;
3184 if (check_nickname_list(options->ExcludeNodes, "ExcludeNodes", msg))
3185 return -1;
3186 if (check_nickname_list(options->RendNodes, "RendNodes", msg))
3187 return -1;
3188 if (check_nickname_list(options->RendNodes, "RendExcludeNodes", msg))
3189 return -1;
3190 if (check_nickname_list(options->TestVia, "TestVia", msg))
3191 return -1;
3192 if (check_nickname_list(options->MyFamily, "MyFamily", msg))
3193 return -1;
3194 for (cl = options->NodeFamilies; cl; cl = cl->next) {
3195 if (check_nickname_list(cl->value, "NodeFamily", msg))
3196 return -1;
3199 if (validate_addr_policies(options, msg) < 0)
3200 return -1;
3202 for (cl = options->RedirectExit; cl; cl = cl->next) {
3203 if (parse_redirect_line(NULL, cl, msg)<0)
3204 return -1;
3207 if (validate_dir_authorities(options, old_options) < 0)
3208 REJECT("Directory authority line did not parse. See logs for details.");
3210 if (options->UseBridges && !options->Bridges)
3211 REJECT("If you set UseBridges, you must specify at least one bridge.");
3212 if (options->UseBridges && !options->TunnelDirConns)
3213 REJECT("If you set UseBridges, you must set TunnelDirConns.");
3214 if (options->Bridges) {
3215 for (cl = options->Bridges; cl; cl = cl->next) {
3216 if (parse_bridge_line(cl->value, 1)<0)
3217 REJECT("Bridge line did not parse. See logs for details.");
3221 if (options->ConstrainedSockets) {
3222 /* If the user wants to constrain socket buffer use, make sure the desired
3223 * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
3224 if (options->ConstrainedSockSize < MIN_CONSTRAINED_TCP_BUFFER ||
3225 options->ConstrainedSockSize > MAX_CONSTRAINED_TCP_BUFFER ||
3226 options->ConstrainedSockSize % 1024) {
3227 r = tor_snprintf(buf, sizeof(buf),
3228 "ConstrainedSockSize is invalid. Must be a value between %d and %d "
3229 "in 1024 byte increments.",
3230 MIN_CONSTRAINED_TCP_BUFFER, MAX_CONSTRAINED_TCP_BUFFER);
3231 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3232 return -1;
3234 if (options->DirPort) {
3235 /* Providing cached directory entries while system TCP buffers are scarce
3236 * will exacerbate the socket errors. Suggest that this be disabled. */
3237 COMPLAIN("You have requested constrained socket buffers while also "
3238 "serving directory entries via DirPort. It is strongly "
3239 "suggested that you disable serving directory requests when "
3240 "system TCP buffer resources are scarce.");
3244 if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
3245 options->V3AuthVotingInterval/2) {
3246 REJECT("V3AuthVoteDelay and V3AuthDistDelay must be no more than half "
3247 "V3AuthVotingInterval");
3249 if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS)
3250 REJECT("V3AuthVoteDelay is way too low.");
3251 if (options->V3AuthDistDelay < MIN_DIST_SECONDS)
3252 REJECT("V3AuthDistDelay is way too low.");
3254 if (options->V3AuthNIntervalsValid < 2)
3255 REJECT("V3AuthNIntervalsValid must be at least 2.");
3257 if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL) {
3258 REJECT("V3AuthVotingInterval is insanely low.");
3259 } else if (options->V3AuthVotingInterval > 24*60*60) {
3260 REJECT("V3AuthVotingInterval is insanely high.");
3261 } else if (((24*60*60) % options->V3AuthVotingInterval) != 0) {
3262 COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
3265 if (rend_config_services(options, 1) < 0)
3266 REJECT("Failed to configure rendezvous options. See logs for details.");
3268 if (parse_virtual_addr_network(options->VirtualAddrNetwork, 1, NULL)<0)
3269 return -1;
3271 if (options->PreferTunneledDirConns && !options->TunnelDirConns)
3272 REJECT("Must set TunnelDirConns if PreferTunneledDirConns is set.");
3274 if (options->AutomapHostsSuffixes) {
3275 SMARTLIST_FOREACH(options->AutomapHostsSuffixes, char *, suf,
3277 size_t len = strlen(suf);
3278 if (len && suf[len-1] == '.')
3279 suf[len-1] = '\0';
3283 return 0;
3284 #undef REJECT
3285 #undef COMPLAIN
3288 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
3289 * equal strings. */
3290 static int
3291 opt_streq(const char *s1, const char *s2)
3293 if (!s1 && !s2)
3294 return 1;
3295 else if (s1 && s2 && !strcmp(s1,s2))
3296 return 1;
3297 else
3298 return 0;
3301 /** Check if any of the previous options have changed but aren't allowed to. */
3302 static int
3303 options_transition_allowed(or_options_t *old, or_options_t *new_val,
3304 char **msg)
3306 if (!old)
3307 return 0;
3309 if (!opt_streq(old->PidFile, new_val->PidFile)) {
3310 *msg = tor_strdup("PidFile is not allowed to change.");
3311 return -1;
3314 if (old->RunAsDaemon != new_val->RunAsDaemon) {
3315 *msg = tor_strdup("While Tor is running, changing RunAsDaemon "
3316 "is not allowed.");
3317 return -1;
3320 if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
3321 char buf[1024];
3322 int r = tor_snprintf(buf, sizeof(buf),
3323 "While Tor is running, changing DataDirectory "
3324 "(\"%s\"->\"%s\") is not allowed.",
3325 old->DataDirectory, new_val->DataDirectory);
3326 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3327 return -1;
3330 if (!opt_streq(old->User, new_val->User)) {
3331 *msg = tor_strdup("While Tor is running, changing User is not allowed.");
3332 return -1;
3335 if (!opt_streq(old->Group, new_val->Group)) {
3336 *msg = tor_strdup("While Tor is running, changing Group is not allowed.");
3337 return -1;
3340 if (old->HardwareAccel != new_val->HardwareAccel) {
3341 *msg = tor_strdup("While Tor is running, changing HardwareAccel is "
3342 "not allowed.");
3343 return -1;
3346 return 0;
3349 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3350 * will require us to rotate the cpu and dns workers; else return 0. */
3351 static int
3352 options_transition_affects_workers(or_options_t *old_options,
3353 or_options_t *new_options)
3355 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
3356 old_options->NumCpus != new_options->NumCpus ||
3357 old_options->ORPort != new_options->ORPort ||
3358 old_options->ServerDNSSearchDomains !=
3359 new_options->ServerDNSSearchDomains ||
3360 old_options->SafeLogging != new_options->SafeLogging ||
3361 old_options->ClientOnly != new_options->ClientOnly ||
3362 !config_lines_eq(old_options->Logs, new_options->Logs))
3363 return 1;
3365 /* Check whether log options match. */
3367 /* Nothing that changed matters. */
3368 return 0;
3371 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3372 * will require us to generate a new descriptor; else return 0. */
3373 static int
3374 options_transition_affects_descriptor(or_options_t *old_options,
3375 or_options_t *new_options)
3377 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
3378 !opt_streq(old_options->Nickname,new_options->Nickname) ||
3379 !opt_streq(old_options->Address,new_options->Address) ||
3380 !config_lines_eq(old_options->ExitPolicy,new_options->ExitPolicy) ||
3381 old_options->ExitPolicyRejectPrivate !=
3382 new_options->ExitPolicyRejectPrivate ||
3383 old_options->ORPort != new_options->ORPort ||
3384 old_options->DirPort != new_options->DirPort ||
3385 old_options->ClientOnly != new_options->ClientOnly ||
3386 old_options->NoPublish != new_options->NoPublish ||
3387 old_options->_PublishServerDescriptor !=
3388 new_options->_PublishServerDescriptor ||
3389 old_options->BandwidthRate != new_options->BandwidthRate ||
3390 old_options->BandwidthBurst != new_options->BandwidthBurst ||
3391 !opt_streq(old_options->ContactInfo, new_options->ContactInfo) ||
3392 !opt_streq(old_options->MyFamily, new_options->MyFamily) ||
3393 !opt_streq(old_options->AccountingStart, new_options->AccountingStart) ||
3394 old_options->AccountingMax != new_options->AccountingMax)
3395 return 1;
3397 return 0;
3400 #ifdef MS_WINDOWS
3401 /** Return the directory on windows where we expect to find our application
3402 * data. */
3403 static char *
3404 get_windows_conf_root(void)
3406 static int is_set = 0;
3407 static char path[MAX_PATH+1];
3409 LPITEMIDLIST idl;
3410 IMalloc *m;
3411 HRESULT result;
3413 if (is_set)
3414 return path;
3416 /* Find X:\documents and settings\username\application data\ .
3417 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
3419 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, CSIDL_APPDATA,
3420 &idl))) {
3421 GetCurrentDirectory(MAX_PATH, path);
3422 is_set = 1;
3423 log_warn(LD_CONFIG,
3424 "I couldn't find your application data folder: are you "
3425 "running an ancient version of Windows 95? Defaulting to \"%s\"",
3426 path);
3427 return path;
3429 /* Convert the path from an "ID List" (whatever that is!) to a path. */
3430 result = SHGetPathFromIDList(idl, path);
3431 /* Now we need to free the */
3432 SHGetMalloc(&m);
3433 if (m) {
3434 m->lpVtbl->Free(m, idl);
3435 m->lpVtbl->Release(m);
3437 if (!SUCCEEDED(result)) {
3438 return NULL;
3440 strlcat(path,"\\tor",MAX_PATH);
3441 is_set = 1;
3442 return path;
3444 #endif
3446 /** Return the default location for our torrc file. */
3447 static const char *
3448 get_default_conf_file(void)
3450 #ifdef MS_WINDOWS
3451 static char path[MAX_PATH+1];
3452 strlcpy(path, get_windows_conf_root(), MAX_PATH);
3453 strlcat(path,"\\torrc",MAX_PATH);
3454 return path;
3455 #else
3456 return (CONFDIR "/torrc");
3457 #endif
3460 /** Verify whether lst is a string containing valid-looking space-separated
3461 * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
3463 static int
3464 check_nickname_list(const char *lst, const char *name, char **msg)
3466 int r = 0;
3467 smartlist_t *sl;
3469 if (!lst)
3470 return 0;
3471 sl = smartlist_create();
3472 smartlist_split_string(sl, lst, ",", SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
3473 SMARTLIST_FOREACH(sl, const char *, s,
3475 if (!is_legal_nickname_or_hexdigest(s)) {
3476 char buf[1024];
3477 int tmp = tor_snprintf(buf, sizeof(buf),
3478 "Invalid nickname '%s' in %s line", s, name);
3479 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
3480 r = -1;
3481 break;
3484 SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
3485 smartlist_free(sl);
3486 return r;
3489 /** Read a configuration file into <b>options</b>, finding the configuration
3490 * file location based on the command line. After loading the options,
3491 * validate them for consistency, then take actions based on them.
3492 * Return 0 if success, -1 if failure. */
3494 options_init_from_torrc(int argc, char **argv)
3496 or_options_t *oldoptions, *newoptions;
3497 config_line_t *cl;
3498 char *cf=NULL, *fname=NULL, *errmsg=NULL;
3499 int i, retval;
3500 int using_default_torrc;
3501 int ignore_missing_torrc;
3502 static char **backup_argv;
3503 static int backup_argc;
3505 if (argv) { /* first time we're called. save commandline args */
3506 backup_argv = argv;
3507 backup_argc = argc;
3508 oldoptions = NULL;
3509 } else { /* we're reloading. need to clean up old options first. */
3510 argv = backup_argv;
3511 argc = backup_argc;
3512 oldoptions = get_options();
3514 if (argc > 1 && (!strcmp(argv[1], "-h") || !strcmp(argv[1],"--help"))) {
3515 print_usage();
3516 exit(0);
3518 if (argc > 1 && !strcmp(argv[1], "--list-torrc-options")) {
3519 /* For documenting validating whether we've documented everything. */
3520 list_torrc_options();
3521 exit(0);
3524 if (argc > 1 && (!strcmp(argv[1],"--version"))) {
3525 printf("Tor version %s.\n",get_version());
3526 if (argc > 2 && (!strcmp(argv[2],"--version"))) {
3527 print_svn_version();
3529 exit(0);
3532 newoptions = tor_malloc_zero(sizeof(or_options_t));
3533 newoptions->_magic = OR_OPTIONS_MAGIC;
3534 options_init(newoptions);
3536 /* learn config file name */
3537 fname = NULL;
3538 using_default_torrc = 1;
3539 ignore_missing_torrc = 0;
3540 newoptions->command = CMD_RUN_TOR;
3541 for (i = 1; i < argc; ++i) {
3542 if (i < argc-1 && !strcmp(argv[i],"-f")) {
3543 if (fname) {
3544 log(LOG_WARN, LD_CONFIG, "Duplicate -f options on command line.");
3545 tor_free(fname);
3547 #ifdef MS_WINDOWS
3548 /* XXX one day we might want to extend expand_filename to work
3549 * under Windows as well. */
3550 fname = tor_strdup(argv[i+1]);
3551 #else
3552 fname = expand_filename(argv[i+1]);
3553 #endif
3554 using_default_torrc = 0;
3555 ++i;
3556 } else if (!strcmp(argv[i],"--ignore-missing-torrc")) {
3557 ignore_missing_torrc = 1;
3558 } else if (!strcmp(argv[i],"--list-fingerprint")) {
3559 newoptions->command = CMD_LIST_FINGERPRINT;
3560 } else if (!strcmp(argv[i],"--hash-password")) {
3561 newoptions->command = CMD_HASH_PASSWORD;
3562 newoptions->command_arg = tor_strdup( (i < argc-1) ? argv[i+1] : "");
3563 ++i;
3564 } else if (!strcmp(argv[i],"--verify-config")) {
3565 newoptions->command = CMD_VERIFY_CONFIG;
3568 if (using_default_torrc) {
3569 /* didn't find one, try CONFDIR */
3570 const char *dflt = get_default_conf_file();
3571 if (dflt && file_status(dflt) == FN_FILE) {
3572 fname = tor_strdup(dflt);
3573 } else {
3574 #ifndef MS_WINDOWS
3575 char *fn;
3576 fn = expand_filename("~/.torrc");
3577 if (fn && file_status(fn) == FN_FILE) {
3578 fname = fn;
3579 } else {
3580 tor_free(fn);
3581 fname = tor_strdup(dflt);
3583 #else
3584 fname = tor_strdup(dflt);
3585 #endif
3588 tor_assert(fname);
3589 log(LOG_DEBUG, LD_CONFIG, "Opening config file \"%s\"", fname);
3591 tor_free(torrc_fname);
3592 torrc_fname = fname;
3594 /* get config lines, assign them */
3595 if (file_status(fname) != FN_FILE ||
3596 !(cf = read_file_to_str(fname,0,NULL))) {
3597 if (using_default_torrc == 1 || ignore_missing_torrc ) {
3598 log(LOG_NOTICE, LD_CONFIG, "Configuration file \"%s\" not present, "
3599 "using reasonable defaults.", fname);
3600 tor_free(fname); /* sets fname to NULL */
3601 torrc_fname = NULL;
3602 } else {
3603 log(LOG_WARN, LD_CONFIG,
3604 "Unable to open configuration file \"%s\".", fname);
3605 goto err;
3607 } else { /* it opened successfully. use it. */
3608 retval = config_get_lines(cf, &cl);
3609 tor_free(cf);
3610 if (retval < 0)
3611 goto err;
3612 retval = config_assign(&options_format, newoptions, cl, 0, 0, &errmsg);
3613 config_free_lines(cl);
3614 if (retval < 0)
3615 goto err;
3618 /* Go through command-line variables too */
3619 if (config_get_commandlines(argc, argv, &cl) < 0)
3620 goto err;
3621 retval = config_assign(&options_format, newoptions, cl, 0, 0, &errmsg);
3622 config_free_lines(cl);
3623 if (retval < 0)
3624 goto err;
3626 /* Validate newoptions */
3627 if (options_validate(oldoptions, newoptions, 0, &errmsg) < 0)
3628 goto err;
3630 if (options_transition_allowed(oldoptions, newoptions, &errmsg) < 0)
3631 goto err;
3633 if (set_options(newoptions, &errmsg))
3634 goto err; /* frees and replaces old options */
3636 return 0;
3637 err:
3638 tor_free(fname);
3639 torrc_fname = NULL;
3640 config_free(&options_format, newoptions);
3641 if (errmsg) {
3642 log(LOG_WARN,LD_CONFIG,"Failed to parse/validate config: %s", errmsg);
3643 tor_free(errmsg);
3645 return -1;
3648 /** Return the location for our configuration file.
3650 const char *
3651 get_torrc_fname(void)
3653 if (torrc_fname)
3654 return torrc_fname;
3655 else
3656 return get_default_conf_file();
3659 /** Adjust the address map mased on the MapAddress elements in the
3660 * configuration <b>options</b>
3662 static void
3663 config_register_addressmaps(or_options_t *options)
3665 smartlist_t *elts;
3666 config_line_t *opt;
3667 char *from, *to;
3669 addressmap_clear_configured();
3670 elts = smartlist_create();
3671 for (opt = options->AddressMap; opt; opt = opt->next) {
3672 smartlist_split_string(elts, opt->value, NULL,
3673 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
3674 if (smartlist_len(elts) >= 2) {
3675 from = smartlist_get(elts,0);
3676 to = smartlist_get(elts,1);
3677 if (address_is_invalid_destination(to, 1)) {
3678 log_warn(LD_CONFIG,
3679 "Skipping invalid argument '%s' to MapAddress", to);
3680 } else {
3681 addressmap_register(from, tor_strdup(to), 0);
3682 if (smartlist_len(elts)>2) {
3683 log_warn(LD_CONFIG,"Ignoring extra arguments to MapAddress.");
3686 } else {
3687 log_warn(LD_CONFIG,"MapAddress '%s' has too few arguments. Ignoring.",
3688 opt->value);
3690 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
3691 smartlist_clear(elts);
3693 smartlist_free(elts);
3696 /** If <b>range</b> is of the form MIN-MAX, for MIN and MAX both
3697 * recognized log severity levels, set *<b>min_out</b> to MIN and
3698 * *<b>max_out</b> to MAX and return 0. Else, if <b>range</b> is of
3699 * the form MIN, act as if MIN-err had been specified. Else, warn and
3700 * return -1.
3702 static int
3703 parse_log_severity_range(const char *range, int *min_out, int *max_out)
3705 int levelMin, levelMax;
3706 const char *cp;
3707 cp = strchr(range, '-');
3708 if (cp) {
3709 if (cp == range) {
3710 levelMin = LOG_DEBUG;
3711 } else {
3712 char *tmp_sev = tor_strndup(range, cp - range);
3713 levelMin = parse_log_level(tmp_sev);
3714 if (levelMin < 0) {
3715 log_warn(LD_CONFIG, "Unrecognized minimum log severity '%s': must be "
3716 "one of err|warn|notice|info|debug", tmp_sev);
3717 tor_free(tmp_sev);
3718 return -1;
3720 tor_free(tmp_sev);
3722 if (!*(cp+1)) {
3723 levelMax = LOG_ERR;
3724 } else {
3725 levelMax = parse_log_level(cp+1);
3726 if (levelMax < 0) {
3727 log_warn(LD_CONFIG, "Unrecognized maximum log severity '%s': must be "
3728 "one of err|warn|notice|info|debug", cp+1);
3729 return -1;
3732 } else {
3733 levelMin = parse_log_level(range);
3734 if (levelMin < 0) {
3735 log_warn(LD_CONFIG, "Unrecognized log severity '%s': must be one of "
3736 "err|warn|notice|info|debug", range);
3737 return -1;
3739 levelMax = LOG_ERR;
3742 *min_out = levelMin;
3743 *max_out = levelMax;
3745 return 0;
3749 * Initialize the logs based on the configuration file.
3751 static int
3752 options_init_logs(or_options_t *options, int validate_only)
3754 config_line_t *opt;
3755 int ok;
3756 smartlist_t *elts;
3757 int daemon =
3758 #ifdef MS_WINDOWS
3760 #else
3761 options->RunAsDaemon;
3762 #endif
3764 ok = 1;
3765 elts = smartlist_create();
3767 for (opt = options->Logs; opt; opt = opt->next) {
3768 int levelMin=LOG_DEBUG, levelMax=LOG_ERR;
3769 smartlist_split_string(elts, opt->value, NULL,
3770 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 3);
3771 if (smartlist_len(elts) == 0) {
3772 log_warn(LD_CONFIG, "No arguments to Log option 'Log %s'", opt->value);
3773 ok = 0; goto cleanup;
3775 if (parse_log_severity_range(smartlist_get(elts,0), &levelMin,
3776 &levelMax)) {
3777 ok = 0; goto cleanup;
3779 if (smartlist_len(elts) < 2) { /* only loglevels were provided */
3780 if (!validate_only) {
3781 if (daemon) {
3782 log_warn(LD_CONFIG,
3783 "Can't log to stdout with RunAsDaemon set; skipping stdout");
3784 } else {
3785 add_stream_log(levelMin, levelMax, "<stdout>", stdout);
3788 goto cleanup;
3790 if (!strcasecmp(smartlist_get(elts,1), "file")) {
3791 if (smartlist_len(elts) != 3) {
3792 log_warn(LD_CONFIG, "Bad syntax on file Log option 'Log %s'",
3793 opt->value);
3794 ok = 0; goto cleanup;
3796 if (!validate_only) {
3797 if (add_file_log(levelMin, levelMax, smartlist_get(elts, 2)) < 0) {
3798 log_warn(LD_CONFIG, "Couldn't open file for 'Log %s'", opt->value);
3799 ok = 0;
3802 goto cleanup;
3804 if (smartlist_len(elts) != 2) {
3805 log_warn(LD_CONFIG, "Wrong number of arguments on Log option 'Log %s'",
3806 opt->value);
3807 ok = 0; goto cleanup;
3809 if (!strcasecmp(smartlist_get(elts,1), "stdout")) {
3810 if (daemon) {
3811 log_warn(LD_CONFIG, "Can't log to stdout with RunAsDaemon set.");
3812 ok = 0; goto cleanup;
3814 if (!validate_only) {
3815 add_stream_log(levelMin, levelMax, "<stdout>", stdout);
3817 } else if (!strcasecmp(smartlist_get(elts,1), "stderr")) {
3818 if (daemon) {
3819 log_warn(LD_CONFIG, "Can't log to stderr with RunAsDaemon set.");
3820 ok = 0; goto cleanup;
3822 if (!validate_only) {
3823 add_stream_log(levelMin, levelMax, "<stderr>", stderr);
3825 } else if (!strcasecmp(smartlist_get(elts,1), "syslog")) {
3826 #ifdef HAVE_SYSLOG_H
3827 if (!validate_only)
3828 add_syslog_log(levelMin, levelMax);
3829 #else
3830 log_warn(LD_CONFIG, "Syslog is not supported on this system. Sorry.");
3831 #endif
3832 } else {
3833 log_warn(LD_CONFIG, "Unrecognized log type %s",
3834 (const char*)smartlist_get(elts,1));
3835 if (strchr(smartlist_get(elts,1), '/') ||
3836 strchr(smartlist_get(elts,1), '\\')) {
3837 log_warn(LD_CONFIG, "Did you mean to say 'Log %s file %s' ?",
3838 (const char *)smartlist_get(elts,0),
3839 (const char *)smartlist_get(elts,1));
3841 ok = 0; goto cleanup;
3843 cleanup:
3844 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
3845 smartlist_clear(elts);
3847 smartlist_free(elts);
3849 return ok?0:-1;
3852 /** Parse a single RedirectExit line's contents from <b>line</b>. If
3853 * they are valid, and <b>result</b> is not NULL, add an element to
3854 * <b>result</b> and return 0. Else if they are valid, return 0.
3855 * Else set *msg and return -1. */
3856 static int
3857 parse_redirect_line(smartlist_t *result, config_line_t *line, char **msg)
3859 smartlist_t *elements = NULL;
3860 exit_redirect_t *r;
3862 tor_assert(line);
3864 r = tor_malloc_zero(sizeof(exit_redirect_t));
3865 elements = smartlist_create();
3866 smartlist_split_string(elements, line->value, NULL,
3867 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
3868 if (smartlist_len(elements) != 2) {
3869 *msg = tor_strdup("Wrong number of elements in RedirectExit line");
3870 goto err;
3872 if (parse_addr_and_port_range(smartlist_get(elements,0),&r->addr,
3873 &r->maskbits,&r->port_min,&r->port_max)) {
3874 *msg = tor_strdup("Error parsing source address in RedirectExit line");
3875 goto err;
3877 if (0==strcasecmp(smartlist_get(elements,1), "pass")) {
3878 r->is_redirect = 0;
3879 } else {
3880 if (parse_addr_port(LOG_WARN, smartlist_get(elements,1),NULL,
3881 &r->addr_dest, &r->port_dest)) {
3882 *msg = tor_strdup("Error parsing dest address in RedirectExit line");
3883 goto err;
3885 r->is_redirect = 1;
3888 goto done;
3889 err:
3890 tor_free(r);
3891 done:
3892 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
3893 smartlist_free(elements);
3894 if (r) {
3895 if (result)
3896 smartlist_add(result, r);
3897 else
3898 tor_free(r);
3899 return 0;
3900 } else {
3901 tor_assert(*msg);
3902 return -1;
3906 /** Read the contents of a Bridge line from <b>line</b>. Return 0
3907 * if the line is well-formed, and -1 if it isn't. If
3908 * <b>validate_only</b> is 0, and the line is well-formed, then add
3909 * the bridge described in the line to our internal bridge list. */
3910 static int
3911 parse_bridge_line(const char *line, int validate_only)
3913 smartlist_t *items = NULL;
3914 int r;
3915 char *addrport=NULL, *address=NULL, *fingerprint=NULL;
3916 uint32_t addr = 0;
3917 uint16_t port = 0;
3918 char digest[DIGEST_LEN];
3920 items = smartlist_create();
3921 smartlist_split_string(items, line, NULL,
3922 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
3923 if (smartlist_len(items) < 1) {
3924 log_warn(LD_CONFIG, "Too few arguments to Bridge line.");
3925 goto err;
3927 addrport = smartlist_get(items, 0);
3928 smartlist_del_keeporder(items, 0);
3929 if (parse_addr_port(LOG_WARN, addrport, &address, &addr, &port)<0) {
3930 log_warn(LD_CONFIG, "Error parsing Bridge address '%s'", addrport);
3931 goto err;
3933 if (!port) {
3934 log_warn(LD_CONFIG, "Missing port in Bridge address '%s'",addrport);
3935 goto err;
3938 if (smartlist_len(items)) {
3939 fingerprint = smartlist_join_strings(items, "", 0, NULL);
3940 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
3941 log_warn(LD_CONFIG, "Key digest for Bridge is wrong length.");
3942 goto err;
3944 if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
3945 log_warn(LD_CONFIG, "Unable to decode Bridge key digest.");
3946 goto err;
3950 if (!validate_only) {
3951 log_debug(LD_DIR, "Bridge at %s:%d (%s)", address,
3952 (int)port,
3953 fingerprint ? fingerprint : "no key listed");
3954 bridge_add_from_config(addr, port, fingerprint ? digest : NULL);
3957 r = 0;
3958 goto done;
3960 err:
3961 r = -1;
3963 done:
3964 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
3965 smartlist_free(items);
3966 tor_free(addrport);
3967 tor_free(address);
3968 tor_free(fingerprint);
3969 return r;
3972 /** Read the contents of a DirServer line from <b>line</b>. Return 0
3973 * if the line is well-formed, and -1 if it isn't. If
3974 * <b>validate_only</b> is 0, and the line is well-formed, and it
3975 * shares any bits with <b>required_type</b> or <b>required_type</b>
3976 * is 0, then add the dirserver described in the line (minus whatever
3977 * bits it's missing) as a valid authority. */
3978 static int
3979 parse_dir_server_line(const char *line, authority_type_t required_type,
3980 int validate_only)
3982 smartlist_t *items = NULL;
3983 int r;
3984 char *addrport=NULL, *address=NULL, *nickname=NULL, *fingerprint=NULL;
3985 uint16_t dir_port = 0, or_port = 0;
3986 char digest[DIGEST_LEN];
3987 char v3_digest[DIGEST_LEN];
3988 authority_type_t type = V2_AUTHORITY;
3989 int is_not_hidserv_authority = 0, is_not_v2_authority = 0;
3991 items = smartlist_create();
3992 smartlist_split_string(items, line, NULL,
3993 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
3994 if (smartlist_len(items) < 1) {
3995 log_warn(LD_CONFIG, "No arguments on DirServer line.");
3996 goto err;
3999 if (is_legal_nickname(smartlist_get(items, 0))) {
4000 nickname = smartlist_get(items, 0);
4001 smartlist_del_keeporder(items, 0);
4004 while (smartlist_len(items)) {
4005 char *flag = smartlist_get(items, 0);
4006 if (TOR_ISDIGIT(flag[0]))
4007 break;
4008 if (!strcasecmp(flag, "v1")) {
4009 type |= (V1_AUTHORITY | HIDSERV_AUTHORITY);
4010 } else if (!strcasecmp(flag, "hs")) {
4011 type |= HIDSERV_AUTHORITY;
4012 } else if (!strcasecmp(flag, "no-hs")) {
4013 is_not_hidserv_authority = 1;
4014 } else if (!strcasecmp(flag, "bridge")) {
4015 type |= BRIDGE_AUTHORITY;
4016 } else if (!strcasecmp(flag, "no-v2")) {
4017 is_not_v2_authority = 1;
4018 } else if (!strcasecmpstart(flag, "orport=")) {
4019 int ok;
4020 char *portstring = flag + strlen("orport=");
4021 or_port = (uint16_t) tor_parse_long(portstring, 10, 1, 65535, &ok, NULL);
4022 if (!ok)
4023 log_warn(LD_CONFIG, "Invalid orport '%s' on DirServer line.",
4024 portstring);
4025 } else if (!strcasecmpstart(flag, "v3ident=")) {
4026 char *idstr = flag + strlen("v3ident=");
4027 if (strlen(idstr) != HEX_DIGEST_LEN ||
4028 base16_decode(v3_digest, DIGEST_LEN, idstr, HEX_DIGEST_LEN)<0) {
4029 log_warn(LD_CONFIG, "Bad v3 identity digest '%s' on DirServer line",
4030 flag);
4031 } else {
4032 type |= V3_AUTHORITY;
4034 } else {
4035 log_warn(LD_CONFIG, "Unrecognized flag '%s' on DirServer line",
4036 flag);
4038 tor_free(flag);
4039 smartlist_del_keeporder(items, 0);
4041 if (is_not_hidserv_authority)
4042 type &= ~HIDSERV_AUTHORITY;
4043 if (is_not_v2_authority)
4044 type &= ~V2_AUTHORITY;
4046 if (smartlist_len(items) < 2) {
4047 log_warn(LD_CONFIG, "Too few arguments to DirServer line.");
4048 goto err;
4050 addrport = smartlist_get(items, 0);
4051 smartlist_del_keeporder(items, 0);
4052 if (parse_addr_port(LOG_WARN, addrport, &address, NULL, &dir_port)<0) {
4053 log_warn(LD_CONFIG, "Error parsing DirServer address '%s'", addrport);
4054 goto err;
4056 if (!dir_port) {
4057 log_warn(LD_CONFIG, "Missing port in DirServer address '%s'",addrport);
4058 goto err;
4061 fingerprint = smartlist_join_strings(items, "", 0, NULL);
4062 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
4063 log_warn(LD_CONFIG, "Key digest for DirServer is wrong length %d.",
4064 (int)strlen(fingerprint));
4065 goto err;
4067 if (!strcmp(fingerprint, "E623F7625FBE0C87820F11EC5F6D5377ED816294")) {
4068 /* a known bad fingerprint. refuse to use it. We can remove this
4069 * clause once Tor 0.1.2.17 is obsolete. */
4070 log_warn(LD_CONFIG, "Dangerous dirserver line. To correct, erase your "
4071 "torrc file (%s), or reinstall Tor and use the default torrc.",
4072 get_torrc_fname());
4073 goto err;
4075 if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
4076 log_warn(LD_CONFIG, "Unable to decode DirServer key digest.");
4077 goto err;
4080 if (!validate_only && (!required_type || required_type & type)) {
4081 if (required_type)
4082 type &= required_type; /* pare down what we think of them as an
4083 * authority for. */
4084 log_debug(LD_DIR, "Trusted %d dirserver at %s:%d (%s)", (int)type,
4085 address, (int)dir_port, (char*)smartlist_get(items,0));
4086 add_trusted_dir_server(nickname, address, dir_port, or_port, digest,
4087 v3_digest, type);
4090 r = 0;
4091 goto done;
4093 err:
4094 r = -1;
4096 done:
4097 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4098 smartlist_free(items);
4099 tor_free(addrport);
4100 tor_free(address);
4101 tor_free(nickname);
4102 tor_free(fingerprint);
4103 return r;
4106 /** Adjust the value of options->DataDirectory, or fill it in if it's
4107 * absent. Return 0 on success, -1 on failure. */
4108 static int
4109 normalize_data_directory(or_options_t *options)
4111 #ifdef MS_WINDOWS
4112 char *p;
4113 if (options->DataDirectory)
4114 return 0; /* all set */
4115 p = tor_malloc(MAX_PATH);
4116 strlcpy(p,get_windows_conf_root(),MAX_PATH);
4117 options->DataDirectory = p;
4118 return 0;
4119 #else
4120 const char *d = options->DataDirectory;
4121 if (!d)
4122 d = "~/.tor";
4124 if (strncmp(d,"~/",2) == 0) {
4125 char *fn = expand_filename(d);
4126 if (!fn) {
4127 log_warn(LD_CONFIG,"Failed to expand filename \"%s\".", d);
4128 return -1;
4130 if (!options->DataDirectory && !strcmp(fn,"/.tor")) {
4131 /* If our homedir is /, we probably don't want to use it. */
4132 /* Default to LOCALSTATEDIR/tor which is probably closer to what we
4133 * want. */
4134 log_warn(LD_CONFIG,
4135 "Default DataDirectory is \"~/.tor\". This expands to "
4136 "\"%s\", which is probably not what you want. Using "
4137 "\"%s"PATH_SEPARATOR"tor\" instead", fn, LOCALSTATEDIR);
4138 tor_free(fn);
4139 fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor");
4141 tor_free(options->DataDirectory);
4142 options->DataDirectory = fn;
4144 return 0;
4145 #endif
4148 /** Check and normalize the value of options->DataDirectory; return 0 if it
4149 * sane, -1 otherwise. */
4150 static int
4151 validate_data_directory(or_options_t *options)
4153 if (normalize_data_directory(options) < 0)
4154 return -1;
4155 tor_assert(options->DataDirectory);
4156 if (strlen(options->DataDirectory) > (512-128)) {
4157 log_warn(LD_CONFIG, "DataDirectory is too long.");
4158 return -1;
4160 return 0;
4163 /** This string must remain the same forevermore. It is how we
4164 * recognize that the torrc file doesn't need to be backed up. */
4165 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
4166 "if you edit it, comments will not be preserved"
4167 /** This string can change; it tries to give the reader an idea
4168 * that editing this file by hand is not a good plan. */
4169 #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
4170 "to torrc.orig.1 or similar, and Tor will ignore it"
4172 /** Save a configuration file for the configuration in <b>options</b>
4173 * into the file <b>fname</b>. If the file already exists, and
4174 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
4175 * replace it. Return 0 on success, -1 on failure. */
4176 static int
4177 write_configuration_file(const char *fname, or_options_t *options)
4179 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
4180 int rename_old = 0, r;
4181 size_t len;
4183 if (fname) {
4184 switch (file_status(fname)) {
4185 case FN_FILE:
4186 old_val = read_file_to_str(fname, 0, NULL);
4187 if (strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
4188 rename_old = 1;
4190 tor_free(old_val);
4191 break;
4192 case FN_NOENT:
4193 break;
4194 case FN_ERROR:
4195 case FN_DIR:
4196 default:
4197 log_warn(LD_CONFIG,
4198 "Config file \"%s\" is not a file? Failing.", fname);
4199 return -1;
4203 if (!(new_conf = options_dump(options, 1))) {
4204 log_warn(LD_BUG, "Couldn't get configuration string");
4205 goto err;
4208 len = strlen(new_conf)+256;
4209 new_val = tor_malloc(len);
4210 tor_snprintf(new_val, len, "%s\n%s\n\n%s",
4211 GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
4213 if (rename_old) {
4214 int i = 1;
4215 size_t fn_tmp_len = strlen(fname)+32;
4216 char *fn_tmp;
4217 tor_assert(fn_tmp_len > strlen(fname)); /*check for overflow*/
4218 fn_tmp = tor_malloc(fn_tmp_len);
4219 while (1) {
4220 if (tor_snprintf(fn_tmp, fn_tmp_len, "%s.orig.%d", fname, i)<0) {
4221 log_warn(LD_BUG, "tor_snprintf failed inexplicably");
4222 tor_free(fn_tmp);
4223 goto err;
4225 if (file_status(fn_tmp) == FN_NOENT)
4226 break;
4227 ++i;
4229 log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
4230 if (rename(fname, fn_tmp) < 0) {
4231 log_warn(LD_FS,
4232 "Couldn't rename configuration file \"%s\" to \"%s\": %s",
4233 fname, fn_tmp, strerror(errno));
4234 tor_free(fn_tmp);
4235 goto err;
4237 tor_free(fn_tmp);
4240 if (write_str_to_file(fname, new_val, 0) < 0)
4241 goto err;
4243 r = 0;
4244 goto done;
4245 err:
4246 r = -1;
4247 done:
4248 tor_free(new_val);
4249 tor_free(new_conf);
4250 return r;
4254 * Save the current configuration file value to disk. Return 0 on
4255 * success, -1 on failure.
4258 options_save_current(void)
4260 if (torrc_fname) {
4261 /* This fails if we can't write to our configuration file.
4263 * If we try falling back to datadirectory or something, we have a better
4264 * chance of saving the configuration, but a better chance of doing
4265 * something the user never expected. Let's just warn instead. */
4266 return write_configuration_file(torrc_fname, get_options());
4268 return write_configuration_file(get_default_conf_file(), get_options());
4271 /** Mapping from a unit name to a multiplier for converting that unit into a
4272 * base unit. */
4273 struct unit_table_t {
4274 const char *unit;
4275 uint64_t multiplier;
4278 static struct unit_table_t memory_units[] = {
4279 { "", 1 },
4280 { "b", 1<< 0 },
4281 { "byte", 1<< 0 },
4282 { "bytes", 1<< 0 },
4283 { "kb", 1<<10 },
4284 { "kbyte", 1<<10 },
4285 { "kbytes", 1<<10 },
4286 { "kilobyte", 1<<10 },
4287 { "kilobytes", 1<<10 },
4288 { "m", 1<<20 },
4289 { "mb", 1<<20 },
4290 { "mbyte", 1<<20 },
4291 { "mbytes", 1<<20 },
4292 { "megabyte", 1<<20 },
4293 { "megabytes", 1<<20 },
4294 { "gb", 1<<30 },
4295 { "gbyte", 1<<30 },
4296 { "gbytes", 1<<30 },
4297 { "gigabyte", 1<<30 },
4298 { "gigabytes", 1<<30 },
4299 { "tb", U64_LITERAL(1)<<40 },
4300 { "terabyte", U64_LITERAL(1)<<40 },
4301 { "terabytes", U64_LITERAL(1)<<40 },
4302 { NULL, 0 },
4305 static struct unit_table_t time_units[] = {
4306 { "", 1 },
4307 { "second", 1 },
4308 { "seconds", 1 },
4309 { "minute", 60 },
4310 { "minutes", 60 },
4311 { "hour", 60*60 },
4312 { "hours", 60*60 },
4313 { "day", 24*60*60 },
4314 { "days", 24*60*60 },
4315 { "week", 7*24*60*60 },
4316 { "weeks", 7*24*60*60 },
4317 { NULL, 0 },
4320 /** Parse a string <b>val</b> containing a number, zero or more
4321 * spaces, and an optional unit string. If the unit appears in the
4322 * table <b>u</b>, then multiply the number by the unit multiplier.
4323 * On success, set *<b>ok</b> to 1 and return this product.
4324 * Otherwise, set *<b>ok</b> to 0.
4326 static uint64_t
4327 config_parse_units(const char *val, struct unit_table_t *u, int *ok)
4329 uint64_t v;
4330 char *cp;
4332 tor_assert(ok);
4334 v = tor_parse_uint64(val, 10, 0, UINT64_MAX, ok, &cp);
4335 if (!*ok)
4336 return 0;
4337 if (!cp) {
4338 *ok = 1;
4339 return v;
4341 while (TOR_ISSPACE(*cp))
4342 ++cp;
4343 for ( ;u->unit;++u) {
4344 if (!strcasecmp(u->unit, cp)) {
4345 v *= u->multiplier;
4346 *ok = 1;
4347 return v;
4350 log_warn(LD_CONFIG, "Unknown unit '%s'.", cp);
4351 *ok = 0;
4352 return 0;
4355 /** Parse a string in the format "number unit", where unit is a unit of
4356 * information (byte, KB, M, etc). On success, set *<b>ok</b> to true
4357 * and return the number of bytes specified. Otherwise, set
4358 * *<b>ok</b> to false and return 0. */
4359 static uint64_t
4360 config_parse_memunit(const char *s, int *ok)
4362 return config_parse_units(s, memory_units, ok);
4365 /** Parse a string in the format "number unit", where unit is a unit of time.
4366 * On success, set *<b>ok</b> to true and return the number of seconds in
4367 * the provided interval. Otherwise, set *<b>ok</b> to 0 and return -1.
4369 static int
4370 config_parse_interval(const char *s, int *ok)
4372 uint64_t r;
4373 r = config_parse_units(s, time_units, ok);
4374 if (!ok)
4375 return -1;
4376 if (r > INT_MAX) {
4377 log_warn(LD_CONFIG, "Interval '%s' is too long", s);
4378 *ok = 0;
4379 return -1;
4381 return (int)r;
4385 * Initialize the libevent library.
4387 static void
4388 init_libevent(void)
4390 configure_libevent_logging();
4391 /* If the kernel complains that some method (say, epoll) doesn't
4392 * exist, we don't care about it, since libevent will cope.
4394 suppress_libevent_log_msg("Function not implemented");
4395 #ifdef __APPLE__
4396 if (decode_libevent_version() < LE_11B) {
4397 setenv("EVENT_NOKQUEUE","1",1);
4399 #endif
4400 event_init();
4401 suppress_libevent_log_msg(NULL);
4402 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
4403 /* Making this a NOTICE for now so we can link bugs to a libevent versions
4404 * or methods better. */
4405 log(LOG_NOTICE, LD_GENERAL,
4406 "Initialized libevent version %s using method %s. Good.",
4407 event_get_version(), event_get_method());
4408 check_libevent_version(event_get_method(), get_options()->ORPort != 0);
4409 #else
4410 log(LOG_NOTICE, LD_GENERAL,
4411 "Initialized old libevent (version 1.0b or earlier).");
4412 log(LOG_WARN, LD_GENERAL,
4413 "You have a *VERY* old version of libevent. It is likely to be buggy; "
4414 "please build Tor with a more recent version.");
4415 #endif
4418 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
4419 /** Table mapping return value of event_get_version() to le_version_t. */
4420 static const struct {
4421 const char *name; le_version_t version;
4422 } le_version_table[] = {
4423 /* earlier versions don't have get_version. */
4424 { "1.0c", LE_10C },
4425 { "1.0d", LE_10D },
4426 { "1.0e", LE_10E },
4427 { "1.1", LE_11 },
4428 { "1.1a", LE_11A },
4429 { "1.1b", LE_11B },
4430 { "1.2", LE_12 },
4431 { "1.2a", LE_12A },
4432 { "1.3", LE_13 },
4433 { "1.3a", LE_13A },
4434 { "1.3b", LE_13B },
4435 { "1.3c", LE_13C },
4436 { "1.3d", LE_13D },
4437 { NULL, LE_OTHER }
4440 /** Return the le_version_t for the current version of libevent. If the
4441 * version is very new, return LE_OTHER. If the version is so old that it
4442 * doesn't support event_get_version(), return LE_OLD. */
4443 static le_version_t
4444 decode_libevent_version(void)
4446 const char *v = event_get_version();
4447 int i;
4448 for (i=0; le_version_table[i].name; ++i) {
4449 if (!strcmp(le_version_table[i].name, v)) {
4450 return le_version_table[i].version;
4453 return LE_OTHER;
4457 * Compare the given libevent method and version to a list of versions
4458 * which are known not to work. Warn the user as appropriate.
4460 static void
4461 check_libevent_version(const char *m, int server)
4463 int buggy = 0, iffy = 0, slow = 0, thread_unsafe = 0;
4464 le_version_t version;
4465 const char *v = event_get_version();
4466 const char *badness = NULL;
4467 const char *sad_os = "";
4469 version = decode_libevent_version();
4471 /* XXX Would it be worthwhile disabling the methods that we know
4472 * are buggy, rather than just warning about them and then proceeding
4473 * to use them? If so, we should probably not wrap this whole thing
4474 * in HAVE_EVENT_GET_VERSION and HAVE_EVENT_GET_METHOD. -RD */
4475 /* XXXX The problem is that it's not trivial to get libevent to change it's
4476 * method once it's initialized, and it's not trivial to tell what method it
4477 * will use without initializing it. I guess we could preemptively disable
4478 * buggy libevent modes based on the version _before_ initializing it,
4479 * though, but then there's no good way (afaict) to warn "I would have used
4480 * kqueue, but instead I'm using select." -NM */
4481 if (!strcmp(m, "kqueue")) {
4482 if (version < LE_11B)
4483 buggy = 1;
4484 } else if (!strcmp(m, "epoll")) {
4485 if (version < LE_11)
4486 iffy = 1;
4487 } else if (!strcmp(m, "poll")) {
4488 if (version < LE_10E)
4489 buggy = 1;
4490 else if (version < LE_11)
4491 slow = 1;
4492 } else if (!strcmp(m, "select")) {
4493 if (version < LE_11)
4494 slow = 1;
4495 } else if (!strcmp(m, "win32")) {
4496 if (version < LE_11B)
4497 buggy = 1;
4500 /* Libevent versions before 1.3b do very badly on operating systems with
4501 * user-space threading implementations. */
4502 #if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__)
4503 if (server && version < LE_13B) {
4504 thread_unsafe = 1;
4505 sad_os = "BSD variants";
4507 #elif defined(__APPLE__) || defined(__darwin__)
4508 if (server && version < LE_13B) {
4509 thread_unsafe = 1;
4510 sad_os = "Mac OS X";
4512 #endif
4514 if (thread_unsafe) {
4515 log(LOG_WARN, LD_GENERAL,
4516 "Libevent version %s often crashes when running a Tor server with %s. "
4517 "Please use the latest version of libevent (1.3b or later)",v,sad_os);
4518 badness = "BROKEN";
4519 } else if (buggy) {
4520 log(LOG_WARN, LD_GENERAL,
4521 "There are serious bugs in using %s with libevent %s. "
4522 "Please use the latest version of libevent.", m, v);
4523 badness = "BROKEN";
4524 } else if (iffy) {
4525 log(LOG_WARN, LD_GENERAL,
4526 "There are minor bugs in using %s with libevent %s. "
4527 "You may want to use the latest version of libevent.", m, v);
4528 badness = "BUGGY";
4529 } else if (slow && server) {
4530 log(LOG_WARN, LD_GENERAL,
4531 "libevent %s can be very slow with %s. "
4532 "When running a server, please use the latest version of libevent.",
4533 v,m);
4534 badness = "SLOW";
4536 if (badness) {
4537 control_event_general_status(LOG_WARN,
4538 "BAD_LIBEVENT VERSION=%s METHOD=%s BADNESS=%s RECOVERED=NO",
4539 v, m, badness);
4543 #else
4544 static le_version_t
4545 decode_libevent_version(void)
4547 return LE_OLD;
4549 #endif
4551 /** Return the persistent state struct for this Tor. */
4552 or_state_t *
4553 get_or_state(void)
4555 tor_assert(global_state);
4556 return global_state;
4559 /** Return a newly allocated string holding a filename relative to the data
4560 * directory. If <b>sub1</b> is present, it is the first path component after
4561 * the data directory. If <b>sub2</b> is also present, it is the second path
4562 * component after the data directory. If <b>suffix</b> is present, it
4563 * is appended to the filename.
4565 * Examples:
4566 * get_datadir_fname2_suffix("a", NULL, NULL) -> $DATADIR/a
4567 * get_datadir_fname2_suffix("a", NULL, ".tmp") -> $DATADIR/a.tmp
4568 * get_datadir_fname2_suffix("a", "b", ".tmp") -> $DATADIR/a/b/.tmp
4569 * get_datadir_fname2_suffix("a", "b", NULL) -> $DATADIR/a/b
4571 * Note: Consider using the get_datadir_fname* macros in or.h.
4573 char *
4574 get_datadir_fname2_suffix(const char *sub1, const char *sub2,
4575 const char *suffix)
4577 or_options_t *options = get_options();
4578 char *fname = NULL;
4579 size_t len;
4580 tor_assert(options);
4581 tor_assert(options->DataDirectory);
4582 tor_assert(sub1 || !sub2); /* If sub2 is present, sub1 must be present. */
4583 len = strlen(options->DataDirectory);
4584 if (sub1) {
4585 len += strlen(sub1)+1;
4586 if (sub2)
4587 len += strlen(sub2)+1;
4589 if (suffix)
4590 len += strlen(suffix);
4591 len++;
4592 fname = tor_malloc(len);
4593 if (sub1) {
4594 if (sub2) {
4595 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s",
4596 options->DataDirectory, sub1, sub2);
4597 } else {
4598 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s",
4599 options->DataDirectory, sub1);
4601 } else {
4602 strlcpy(fname, options->DataDirectory, len);
4604 if (suffix)
4605 strlcat(fname, suffix, len);
4606 return fname;
4609 /** Return 0 if every setting in <b>state</b> is reasonable, and a
4610 * permissible transition from <b>old_state</b>. Else warn and return -1.
4611 * Should have no side effects, except for normalizing the contents of
4612 * <b>state</b>.
4614 /* XXX from_setconf is here because of bug 238 */
4615 static int
4616 or_state_validate(or_state_t *old_state, or_state_t *state,
4617 int from_setconf, char **msg)
4619 /* We don't use these; only options do. Still, we need to match that
4620 * signature. */
4621 (void) from_setconf;
4622 (void) old_state;
4624 if (entry_guards_parse_state(state, 0, msg)<0)
4625 return -1;
4627 return 0;
4630 /** Replace the current persistent state with <b>new_state</b> */
4631 static void
4632 or_state_set(or_state_t *new_state)
4634 char *err = NULL;
4635 tor_assert(new_state);
4636 if (global_state)
4637 config_free(&state_format, global_state);
4638 global_state = new_state;
4639 if (entry_guards_parse_state(global_state, 1, &err)<0) {
4640 log_warn(LD_GENERAL,"%s",err);
4641 tor_free(err);
4643 if (rep_hist_load_state(global_state, &err)<0) {
4644 log_warn(LD_GENERAL,"Unparseable bandwidth history state: %s",err);
4645 tor_free(err);
4649 /** Reload the persistent state from disk, generating a new state as needed.
4650 * Return 0 on success, less than 0 on failure.
4652 static int
4653 or_state_load(void)
4655 or_state_t *new_state = NULL;
4656 char *contents = NULL, *fname;
4657 char *errmsg = NULL;
4658 int r = -1, badstate = 0;
4660 fname = get_datadir_fname("state");
4661 switch (file_status(fname)) {
4662 case FN_FILE:
4663 if (!(contents = read_file_to_str(fname, 0, NULL))) {
4664 log_warn(LD_FS, "Unable to read state file \"%s\"", fname);
4665 goto done;
4667 break;
4668 case FN_NOENT:
4669 break;
4670 case FN_ERROR:
4671 case FN_DIR:
4672 default:
4673 log_warn(LD_GENERAL,"State file \"%s\" is not a file? Failing.", fname);
4674 goto done;
4676 new_state = tor_malloc_zero(sizeof(or_state_t));
4677 new_state->_magic = OR_STATE_MAGIC;
4678 config_init(&state_format, new_state);
4679 if (contents) {
4680 config_line_t *lines=NULL;
4681 int assign_retval;
4682 if (config_get_lines(contents, &lines)<0)
4683 goto done;
4684 assign_retval = config_assign(&state_format, new_state,
4685 lines, 0, 0, &errmsg);
4686 config_free_lines(lines);
4687 if (assign_retval<0)
4688 badstate = 1;
4689 if (errmsg) {
4690 log_warn(LD_GENERAL, "%s", errmsg);
4691 tor_free(errmsg);
4695 if (!badstate && or_state_validate(NULL, new_state, 1, &errmsg) < 0)
4696 badstate = 1;
4698 if (errmsg) {
4699 log_warn(LD_GENERAL, "%s", errmsg);
4700 tor_free(errmsg);
4703 if (badstate && !contents) {
4704 log_warn(LD_BUG, "Uh oh. We couldn't even validate our own default state."
4705 " This is a bug in Tor.");
4706 goto done;
4707 } else if (badstate && contents) {
4708 int i;
4709 file_status_t status;
4710 size_t len = strlen(fname)+16;
4711 char *fname2 = tor_malloc(len);
4712 for (i = 0; i < 100; ++i) {
4713 tor_snprintf(fname2, len, "%s.%d", fname, i);
4714 status = file_status(fname2);
4715 if (status == FN_NOENT)
4716 break;
4718 if (i == 100) {
4719 log_warn(LD_BUG, "Unable to parse state in \"%s\"; too many saved bad "
4720 "state files to move aside. Discarding the old state file.",
4721 fname);
4722 unlink(fname);
4723 } else {
4724 log_warn(LD_BUG, "Unable to parse state in \"%s\". Moving it aside "
4725 "to \"%s\". This could be a bug in Tor; please tell "
4726 "the developers.", fname, fname2);
4727 rename(fname, fname2);
4729 tor_free(fname2);
4730 tor_free(contents);
4731 config_free(&state_format, new_state);
4733 new_state = tor_malloc_zero(sizeof(or_state_t));
4734 new_state->_magic = OR_STATE_MAGIC;
4735 config_init(&state_format, new_state);
4736 } else if (contents) {
4737 log_info(LD_GENERAL, "Loaded state from \"%s\"", fname);
4738 } else {
4739 log_info(LD_GENERAL, "Initialized state");
4741 or_state_set(new_state);
4742 new_state = NULL;
4743 if (!contents) {
4744 global_state->next_write = 0;
4745 or_state_save(time(NULL));
4747 r = 0;
4749 done:
4750 tor_free(fname);
4751 tor_free(contents);
4752 if (new_state)
4753 config_free(&state_format, new_state);
4755 return r;
4758 /** Write the persistent state to disk. Return 0 for success, <0 on failure. */
4760 or_state_save(time_t now)
4762 char *state, *contents;
4763 char tbuf[ISO_TIME_LEN+1];
4764 size_t len;
4765 char *fname;
4767 tor_assert(global_state);
4769 if (global_state->next_write > now)
4770 return 0;
4772 /* Call everything else that might dirty the state even more, in order
4773 * to avoid redundant writes. */
4774 entry_guards_update_state(global_state);
4775 rep_hist_update_state(global_state);
4776 if (accounting_is_enabled(get_options()))
4777 accounting_run_housekeeping(now);
4779 global_state->LastWritten = time(NULL);
4780 tor_free(global_state->TorVersion);
4781 len = strlen(get_version())+8;
4782 global_state->TorVersion = tor_malloc(len);
4783 tor_snprintf(global_state->TorVersion, len, "Tor %s", get_version());
4785 state = config_dump(&state_format, global_state, 1, 0);
4786 len = strlen(state)+256;
4787 contents = tor_malloc(len);
4788 format_local_iso_time(tbuf, time(NULL));
4789 tor_snprintf(contents, len,
4790 "# Tor state file last generated on %s local time\n"
4791 "# Other times below are in GMT\n"
4792 "# You *do not* need to edit this file.\n\n%s",
4793 tbuf, state);
4794 tor_free(state);
4795 fname = get_datadir_fname("state");
4796 if (write_str_to_file(fname, contents, 0)<0) {
4797 log_warn(LD_FS, "Unable to write state to file \"%s\"", fname);
4798 tor_free(fname);
4799 tor_free(contents);
4800 return -1;
4802 log_info(LD_GENERAL, "Saved state to \"%s\"", fname);
4803 tor_free(fname);
4804 tor_free(contents);
4806 global_state->next_write = TIME_MAX;
4807 return 0;
4810 /** Given a file name check to see whether the file exists but has not been
4811 * modified for a very long time. If so, remove it. */
4812 void
4813 remove_file_if_very_old(const char *fname, time_t now)
4815 #define VERY_OLD_FILE_AGE (28*24*60*60)
4816 struct stat st;
4818 if (stat(fname, &st)==0 && st.st_mtime < now-VERY_OLD_FILE_AGE) {
4819 char buf[ISO_TIME_LEN+1];
4820 format_local_iso_time(buf, st.st_mtime);
4821 log_notice(LD_GENERAL, "Obsolete file %s hasn't been modified since %s. "
4822 "Removing it.", fname, buf);
4823 unlink(fname);
4827 /** Helper to implement GETINFO functions about configuration variables (not
4828 * their values). Given a "config/names" question, set *<b>answer</b> to a
4829 * new string describing the supported configuration variables and their
4830 * types. */
4832 getinfo_helper_config(control_connection_t *conn,
4833 const char *question, char **answer)
4835 (void) conn;
4836 if (!strcmp(question, "config/names")) {
4837 smartlist_t *sl = smartlist_create();
4838 int i;
4839 for (i = 0; _option_vars[i].name; ++i) {
4840 config_var_t *var = &_option_vars[i];
4841 const char *type, *desc;
4842 char *line;
4843 size_t len;
4844 desc = config_find_description(&options_format, var->name);
4845 switch (var->type) {
4846 case CONFIG_TYPE_STRING: type = "String"; break;
4847 case CONFIG_TYPE_UINT: type = "Integer"; break;
4848 case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
4849 case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
4850 case CONFIG_TYPE_DOUBLE: type = "Float"; break;
4851 case CONFIG_TYPE_BOOL: type = "Boolean"; break;
4852 case CONFIG_TYPE_ISOTIME: type = "Time"; break;
4853 case CONFIG_TYPE_CSV: type = "CommaList"; break;
4854 case CONFIG_TYPE_LINELIST: type = "LineList"; break;
4855 case CONFIG_TYPE_LINELIST_S: type = "Dependant"; break;
4856 case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
4857 default:
4858 case CONFIG_TYPE_OBSOLETE:
4859 type = NULL; break;
4861 if (!type)
4862 continue;
4863 len = strlen(var->name)+strlen(type)+16;
4864 if (desc)
4865 len += strlen(desc);
4866 line = tor_malloc(len);
4867 if (desc)
4868 tor_snprintf(line, len, "%s %s %s\n",var->name,type,desc);
4869 else
4870 tor_snprintf(line, len, "%s %s\n",var->name,type);
4871 smartlist_add(sl, line);
4873 *answer = smartlist_join_strings(sl, "", 0, NULL);
4874 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
4875 smartlist_free(sl);
4877 return 0;
4880 #include "aes.h"
4881 #include "ht.h"
4882 #include "test.h"
4884 extern const char aes_c_id[];
4885 extern const char compat_c_id[];
4886 extern const char container_c_id[];
4887 extern const char crypto_c_id[];
4888 extern const char log_c_id[];
4889 extern const char torgzip_c_id[];
4890 extern const char tortls_c_id[];
4891 extern const char util_c_id[];
4893 extern const char buffers_c_id[];
4894 extern const char circuitbuild_c_id[];
4895 extern const char circuitlist_c_id[];
4896 extern const char circuituse_c_id[];
4897 extern const char command_c_id[];
4898 // extern const char config_c_id[];
4899 extern const char connection_c_id[];
4900 extern const char connection_edge_c_id[];
4901 extern const char connection_or_c_id[];
4902 extern const char control_c_id[];
4903 extern const char cpuworker_c_id[];
4904 extern const char directory_c_id[];
4905 extern const char dirserv_c_id[];
4906 extern const char dns_c_id[];
4907 extern const char hibernate_c_id[];
4908 extern const char main_c_id[];
4909 #ifdef NT_SERVICE
4910 extern const char ntmain_c_id[];
4911 #endif
4912 extern const char onion_c_id[];
4913 extern const char policies_c_id[];
4914 extern const char relay_c_id[];
4915 extern const char rendclient_c_id[];
4916 extern const char rendcommon_c_id[];
4917 extern const char rendmid_c_id[];
4918 extern const char rendservice_c_id[];
4919 extern const char rephist_c_id[];
4920 extern const char router_c_id[];
4921 extern const char routerlist_c_id[];
4922 extern const char routerparse_c_id[];
4924 /** Dump the version of every file to the log. */
4925 static void
4926 print_svn_version(void)
4928 puts(AES_H_ID);
4929 puts(COMPAT_H_ID);
4930 puts(CONTAINER_H_ID);
4931 puts(CRYPTO_H_ID);
4932 puts(HT_H_ID);
4933 puts(TEST_H_ID);
4934 puts(LOG_H_ID);
4935 puts(TORGZIP_H_ID);
4936 puts(TORINT_H_ID);
4937 puts(TORTLS_H_ID);
4938 puts(UTIL_H_ID);
4939 puts(aes_c_id);
4940 puts(compat_c_id);
4941 puts(container_c_id);
4942 puts(crypto_c_id);
4943 puts(log_c_id);
4944 puts(torgzip_c_id);
4945 puts(tortls_c_id);
4946 puts(util_c_id);
4948 puts(OR_H_ID);
4949 puts(buffers_c_id);
4950 puts(circuitbuild_c_id);
4951 puts(circuitlist_c_id);
4952 puts(circuituse_c_id);
4953 puts(command_c_id);
4954 puts(config_c_id);
4955 puts(connection_c_id);
4956 puts(connection_edge_c_id);
4957 puts(connection_or_c_id);
4958 puts(control_c_id);
4959 puts(cpuworker_c_id);
4960 puts(directory_c_id);
4961 puts(dirserv_c_id);
4962 puts(dns_c_id);
4963 puts(hibernate_c_id);
4964 puts(main_c_id);
4965 #ifdef NT_SERVICE
4966 puts(ntmain_c_id);
4967 #endif
4968 puts(onion_c_id);
4969 puts(policies_c_id);
4970 puts(relay_c_id);
4971 puts(rendclient_c_id);
4972 puts(rendcommon_c_id);
4973 puts(rendmid_c_id);
4974 puts(rendservice_c_id);
4975 puts(rephist_c_id);
4976 puts(router_c_id);
4977 puts(routerlist_c_id);
4978 puts(routerparse_c_id);