r18639@catbus: nickm | 2008-03-07 20:11:48 -0500
[tor/rransom.git] / src / or / config.c
blob123fe1d9b3001d14319a7dc9b8c43b4878b170a1
1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2008, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
6 /* $Id$ */
7 const char config_c_id[] = \
8 "$Id$";
10 /**
11 * \file config.c
12 * \brief Code to parse and interpret configuration files.
13 **/
15 #define CONFIG_PRIVATE
17 #include "or.h"
18 #ifdef MS_WINDOWS
19 #include <shlobj.h>
20 #endif
22 /** Enumeration of types which option values can take */
23 typedef enum config_type_t {
24 CONFIG_TYPE_STRING = 0, /**< An arbitrary string. */
25 CONFIG_TYPE_UINT, /**< A non-negative integer less than MAX_INT */
26 CONFIG_TYPE_INTERVAL, /**< A number of seconds, with optional units*/
27 CONFIG_TYPE_MEMUNIT, /**< A number of bytes, with optional units*/
28 CONFIG_TYPE_DOUBLE, /**< A floating-point value */
29 CONFIG_TYPE_BOOL, /**< A boolean value, expressed as 0 or 1. */
30 CONFIG_TYPE_ISOTIME, /**< An ISO-formated time relative to GMT. */
31 CONFIG_TYPE_CSV, /**< A list of strings, separated by commas and
32 * optional whitespace. */
33 CONFIG_TYPE_LINELIST, /**< Uninterpreted config lines */
34 CONFIG_TYPE_LINELIST_S, /**< Uninterpreted, context-sensitive config lines,
35 * mixed with other keywords. */
36 CONFIG_TYPE_LINELIST_V, /**< Catch-all "virtual" option to summarize
37 * context-sensitive config lines when fetching.
39 CONFIG_TYPE_OBSOLETE, /**< Obsolete (ignored) option. */
40 } config_type_t;
42 /** An abbreviation for a configuration option allowed on the command line. */
43 typedef struct config_abbrev_t {
44 const char *abbreviated;
45 const char *full;
46 int commandline_only;
47 int warn;
48 } config_abbrev_t;
50 /* Handy macro for declaring "In the config file or on the command line,
51 * you can abbreviate <b>tok</b>s as <b>tok</b>". */
52 #define PLURAL(tok) { #tok, #tok "s", 0, 0 }
54 /* A list of command-line abbreviations. */
55 static config_abbrev_t _option_abbrevs[] = {
56 PLURAL(ExitNode),
57 PLURAL(EntryNode),
58 PLURAL(ExcludeNode),
59 PLURAL(FirewallPort),
60 PLURAL(LongLivedPort),
61 PLURAL(HiddenServiceNode),
62 PLURAL(HiddenServiceExcludeNode),
63 PLURAL(NumCpu),
64 PLURAL(RendNode),
65 PLURAL(RendExcludeNode),
66 PLURAL(StrictEntryNode),
67 PLURAL(StrictExitNode),
68 { "l", "Log", 1, 0},
69 { "AllowUnverifiedNodes", "AllowInvalidNodes", 0, 0},
70 { "AutomapHostSuffixes", "AutomapHostsSuffixes", 0, 0},
71 { "AutomapHostOnResolve", "AutomapHostsOnResolve", 0, 0},
72 { "BandwidthRateBytes", "BandwidthRate", 0, 0},
73 { "BandwidthBurstBytes", "BandwidthBurst", 0, 0},
74 { "DirFetchPostPeriod", "StatusFetchPeriod", 0, 0},
75 { "MaxConn", "ConnLimit", 0, 1},
76 { "ORBindAddress", "ORListenAddress", 0, 0},
77 { "DirBindAddress", "DirListenAddress", 0, 0},
78 { "SocksBindAddress", "SocksListenAddress", 0, 0},
79 { "UseHelperNodes", "UseEntryGuards", 0, 0},
80 { "NumHelperNodes", "NumEntryGuards", 0, 0},
81 { "UseEntryNodes", "UseEntryGuards", 0, 0},
82 { "NumEntryNodes", "NumEntryGuards", 0, 0},
83 { "ResolvConf", "ServerDNSResolvConfFile", 0, 1},
84 { "SearchDomains", "ServerDNSSearchDomains", 0, 1},
85 { "PreferTunnelledDirConns", "PreferTunneledDirConns", 0, 0},
86 { "BridgeAuthoritativeDirectory", "BridgeAuthoritativeDir", 0, 0},
87 { "HashedControlPassword", "__HashedControlSessionPassword", 1, 0},
88 { NULL, NULL, 0, 0},
90 /* A list of state-file abbreviations, for compatibility. */
91 static config_abbrev_t _state_abbrevs[] = {
92 { "AccountingBytesReadInterval", "AccountingBytesReadInInterval", 0, 0 },
93 { "HelperNode", "EntryGuard", 0, 0 },
94 { "HelperNodeDownSince", "EntryGuardDownSince", 0, 0 },
95 { "HelperNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
96 { "EntryNode", "EntryGuard", 0, 0 },
97 { "EntryNodeDownSince", "EntryGuardDownSince", 0, 0 },
98 { "EntryNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
99 { NULL, NULL, 0, 0},
101 #undef PLURAL
103 /** A variable allowed in the configuration file or on the command line. */
104 typedef struct config_var_t {
105 const char *name; /**< The full keyword (case insensitive). */
106 config_type_t type; /**< How to interpret the type and turn it into a
107 * value. */
108 off_t var_offset; /**< Offset of the corresponding member of or_options_t. */
109 const char *initvalue; /**< String (or null) describing initial value. */
110 } config_var_t;
112 /** An entry for config_vars: "The option <b>name</b> has type
113 * CONFIG_TYPE_<b>conftype</b>, and corresponds to
114 * or_options_t.<b>member</b>"
116 #define VAR(name,conftype,member,initvalue) \
117 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_options_t, member), \
118 initvalue }
119 /** As VAR, but the option name and member name are the same. */
120 #define V(member,conftype,initvalue) \
121 VAR(#member, conftype, member, initvalue)
122 /** An entry for config_vars: "The option <b>name</b> is obsolete." */
123 #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL }
125 /** Array of configuration options. Until we disallow nonstandard
126 * abbreviations, order is significant, since the first matching option will
127 * be chosen first.
129 static config_var_t _option_vars[] = {
130 OBSOLETE("AccountingMaxKB"),
131 V(AccountingMax, MEMUNIT, "0 bytes"),
132 V(AccountingStart, STRING, NULL),
133 V(Address, STRING, NULL),
134 V(AllowInvalidNodes, CSV, "middle,rendezvous"),
135 V(AllowNonRFC953Hostnames, BOOL, "0"),
136 V(AlternateBridgeAuthority, LINELIST, NULL),
137 V(AlternateDirAuthority, LINELIST, NULL),
138 V(AlternateHSAuthority, LINELIST, NULL),
139 V(AssumeReachable, BOOL, "0"),
140 V(AuthDirBadDir, LINELIST, NULL),
141 V(AuthDirBadExit, LINELIST, NULL),
142 V(AuthDirInvalid, LINELIST, NULL),
143 V(AuthDirReject, LINELIST, NULL),
144 V(AuthDirRejectUnlisted, BOOL, "0"),
145 V(AuthDirListBadDirs, BOOL, "0"),
146 V(AuthDirListBadExits, BOOL, "0"),
147 V(AuthDirMaxServersPerAddr, UINT, "2"),
148 V(AuthDirMaxServersPerAuthAddr,UINT, "5"),
149 VAR("AuthoritativeDirectory", BOOL, AuthoritativeDir, "0"),
150 V(AutomapHostsOnResolve, BOOL, "0"),
151 V(AutomapHostsSuffixes, CSV, ".onion,.exit"),
152 V(AvoidDiskWrites, BOOL, "0"),
153 V(BandwidthBurst, MEMUNIT, "10 MB"),
154 V(BandwidthRate, MEMUNIT, "5 MB"),
155 V(BridgeAuthoritativeDir, BOOL, "0"),
156 VAR("Bridge", LINELIST, Bridges, NULL),
157 V(BridgePassword, STRING, NULL),
158 V(BridgeRecordUsageByCountry, BOOL, "1"),
159 V(BridgeRelay, BOOL, "0"),
160 V(CircuitBuildTimeout, INTERVAL, "1 minute"),
161 V(CircuitIdleTimeout, INTERVAL, "1 hour"),
162 V(ClientDNSRejectInternalAddresses, BOOL,"1"),
163 V(ClientOnly, BOOL, "0"),
164 V(ConnLimit, UINT, "1000"),
165 V(ConstrainedSockets, BOOL, "0"),
166 V(ConstrainedSockSize, MEMUNIT, "8192"),
167 V(ContactInfo, STRING, NULL),
168 V(ControlListenAddress, LINELIST, NULL),
169 V(ControlPort, UINT, "0"),
170 V(ControlSocket, LINELIST, NULL),
171 V(CookieAuthentication, BOOL, "0"),
172 V(CookieAuthFileGroupReadable, BOOL, "0"),
173 V(CookieAuthFile, STRING, NULL),
174 V(DataDirectory, STRING, NULL),
175 OBSOLETE("DebugLogFile"),
176 V(DirAllowPrivateAddresses, BOOL, NULL),
177 V(DirListenAddress, LINELIST, NULL),
178 OBSOLETE("DirFetchPeriod"),
179 V(DirPolicy, LINELIST, NULL),
180 V(DirPort, UINT, "0"),
181 OBSOLETE("DirPostPeriod"),
182 VAR("DirServer", LINELIST, DirServers, NULL),
183 V(DNSPort, UINT, "0"),
184 V(DNSListenAddress, LINELIST, NULL),
185 V(DownloadExtraInfo, BOOL, "0"),
186 V(EnforceDistinctSubnets, BOOL, "1"),
187 V(EntryNodes, STRING, NULL),
188 V(ExcludeNodes, STRING, NULL),
189 V(ExitNodes, STRING, NULL),
190 V(ExitPolicy, LINELIST, NULL),
191 V(ExitPolicyRejectPrivate, BOOL, "1"),
192 V(FallbackNetworkstatusFile, STRING,
193 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "fallback-consensus"),
194 V(FascistFirewall, BOOL, "0"),
195 V(FirewallPorts, CSV, ""),
196 V(FastFirstHopPK, BOOL, "1"),
197 V(FetchDirInfoEarly, BOOL, "0"),
198 V(FetchServerDescriptors, BOOL, "1"),
199 V(FetchHidServDescriptors, BOOL, "1"),
200 V(FetchUselessDescriptors, BOOL, "0"),
201 V(GeoIPFile, STRING, NULL),
202 V(Group, STRING, NULL),
203 V(HardwareAccel, BOOL, "0"),
204 V(HashedControlPassword, LINELIST, NULL),
205 V(HidServDirectoryV2, BOOL, "0"),
206 VAR("HiddenServiceDir", LINELIST_S, RendConfigLines, NULL),
207 VAR("HiddenServiceExcludeNodes", LINELIST_S, RendConfigLines, NULL),
208 VAR("HiddenServiceNodes", LINELIST_S, RendConfigLines, NULL),
209 VAR("HiddenServiceOptions",LINELIST_V, RendConfigLines, NULL),
210 VAR("HiddenServicePort", LINELIST_S, RendConfigLines, NULL),
211 VAR("HiddenServiceVersion",LINELIST_S, RendConfigLines, NULL),
212 V(HSAuthoritativeDir, BOOL, "0"),
213 V(HSAuthorityRecordStats, BOOL, "0"),
214 V(HttpProxy, STRING, NULL),
215 V(HttpProxyAuthenticator, STRING, NULL),
216 V(HttpsProxy, STRING, NULL),
217 V(HttpsProxyAuthenticator, STRING, NULL),
218 OBSOLETE("IgnoreVersion"),
219 V(KeepalivePeriod, INTERVAL, "5 minutes"),
220 VAR("Log", LINELIST, Logs, NULL),
221 OBSOLETE("LinkPadding"),
222 OBSOLETE("LogLevel"),
223 OBSOLETE("LogFile"),
224 V(LongLivedPorts, CSV,
225 "21,22,706,1863,5050,5190,5222,5223,6667,6697,8300"),
226 VAR("MapAddress", LINELIST, AddressMap, NULL),
227 V(MaxAdvertisedBandwidth, MEMUNIT, "1 GB"),
228 V(MaxCircuitDirtiness, INTERVAL, "10 minutes"),
229 V(MaxOnionsPending, UINT, "100"),
230 OBSOLETE("MonthlyAccountingStart"),
231 V(MyFamily, STRING, NULL),
232 V(NewCircuitPeriod, INTERVAL, "30 seconds"),
233 VAR("NamingAuthoritativeDirectory",BOOL, NamingAuthoritativeDir, "0"),
234 V(NatdListenAddress, LINELIST, NULL),
235 V(NatdPort, UINT, "0"),
236 V(Nickname, STRING, NULL),
237 V(NoPublish, BOOL, "0"),
238 VAR("NodeFamily", LINELIST, NodeFamilies, NULL),
239 V(NumCpus, UINT, "1"),
240 V(NumEntryGuards, UINT, "3"),
241 V(ORListenAddress, LINELIST, NULL),
242 V(ORPort, UINT, "0"),
243 V(OutboundBindAddress, STRING, NULL),
244 OBSOLETE("PathlenCoinWeight"),
245 V(PidFile, STRING, NULL),
246 V(PreferTunneledDirConns, BOOL, "0"),
247 V(ProtocolWarnings, BOOL, "0"),
248 V(PublishServerDescriptor, CSV, "1"),
249 V(PublishHidServDescriptors, BOOL, "1"),
250 V(ReachableAddresses, LINELIST, NULL),
251 V(ReachableDirAddresses, LINELIST, NULL),
252 V(ReachableORAddresses, LINELIST, NULL),
253 V(RecommendedVersions, LINELIST, NULL),
254 V(RecommendedClientVersions, LINELIST, NULL),
255 V(RecommendedServerVersions, LINELIST, NULL),
256 V(RedirectExit, LINELIST, NULL),
257 V(RejectPlaintextPorts, CSV, ""),
258 V(RelayBandwidthBurst, MEMUNIT, "0"),
259 V(RelayBandwidthRate, MEMUNIT, "0"),
260 V(RendExcludeNodes, STRING, NULL),
261 V(RendNodes, STRING, NULL),
262 V(RendPostPeriod, INTERVAL, "1 hour"),
263 V(RephistTrackTime, INTERVAL, "24 hours"),
264 OBSOLETE("RouterFile"),
265 V(RunAsDaemon, BOOL, "0"),
266 V(RunTesting, BOOL, "0"),
267 V(SafeLogging, BOOL, "1"),
268 V(SafeSocks, BOOL, "0"),
269 V(ServerDNSAllowBrokenResolvConf, BOOL, "0"),
270 V(ServerDNSAllowNonRFC953Hostnames, BOOL,"0"),
271 V(ServerDNSDetectHijacking, BOOL, "1"),
272 V(ServerDNSResolvConfFile, STRING, NULL),
273 V(ServerDNSSearchDomains, BOOL, "0"),
274 V(ServerDNSTestAddresses, CSV,
275 "www.google.com,www.mit.edu,www.yahoo.com,www.slashdot.org"),
276 V(ShutdownWaitLength, INTERVAL, "30 seconds"),
277 V(SocksListenAddress, LINELIST, NULL),
278 V(SocksPolicy, LINELIST, NULL),
279 V(SocksPort, UINT, "9050"),
280 V(SocksTimeout, INTERVAL, "2 minutes"),
281 OBSOLETE("StatusFetchPeriod"),
282 V(StrictEntryNodes, BOOL, "0"),
283 V(StrictExitNodes, BOOL, "0"),
284 OBSOLETE("SysLog"),
285 V(TestSocks, BOOL, "0"),
286 V(TestVia, STRING, NULL),
287 V(TrackHostExits, CSV, NULL),
288 V(TrackHostExitsExpire, INTERVAL, "30 minutes"),
289 OBSOLETE("TrafficShaping"),
290 V(TransListenAddress, LINELIST, NULL),
291 V(TransPort, UINT, "0"),
292 V(TunnelDirConns, BOOL, "0"),
293 V(UpdateBridgesFromAuthority, BOOL, "0"),
294 V(UseBridges, BOOL, "0"),
295 V(UseEntryGuards, BOOL, "1"),
296 V(User, STRING, NULL),
297 VAR("V1AuthoritativeDirectory",BOOL, V1AuthoritativeDir, "0"),
298 VAR("V2AuthoritativeDirectory",BOOL, V2AuthoritativeDir, "0"),
299 VAR("V3AuthoritativeDirectory",BOOL, V3AuthoritativeDir, "0"),
300 V(V3AuthVotingInterval, INTERVAL, "1 hour"),
301 V(V3AuthVoteDelay, INTERVAL, "5 minutes"),
302 V(V3AuthDistDelay, INTERVAL, "5 minutes"),
303 V(V3AuthNIntervalsValid, UINT, "3"),
304 VAR("VersioningAuthoritativeDirectory",BOOL,VersioningAuthoritativeDir, "0"),
305 V(VirtualAddrNetwork, STRING, "127.192.0.0/10"),
306 V(WarnPlaintextPorts, CSV, "23,109,110,143"),
307 VAR("__AllDirActionsPrivate", BOOL, AllDirActionsPrivate, "0"),
308 VAR("__DisablePredictedCircuits",BOOL,DisablePredictedCircuits, "0"),
309 VAR("__LeaveStreamsUnattached",BOOL, LeaveStreamsUnattached, "0"),
310 VAR("__HashedControlSessionPassword", LINELIST, HashedControlSessionPassword,
311 NULL),
312 V(MinUptimeHidServDirectoryV2, INTERVAL, "24 hours"),
313 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
315 #undef VAR
317 #define VAR(name,conftype,member,initvalue) \
318 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_state_t, member), \
319 initvalue }
320 static config_var_t _state_vars[] = {
321 V(AccountingBytesReadInInterval, MEMUNIT, NULL),
322 V(AccountingBytesWrittenInInterval, MEMUNIT, NULL),
323 V(AccountingExpectedUsage, MEMUNIT, NULL),
324 V(AccountingIntervalStart, ISOTIME, NULL),
325 V(AccountingSecondsActive, INTERVAL, NULL),
327 VAR("EntryGuard", LINELIST_S, EntryGuards, NULL),
328 VAR("EntryGuardDownSince", LINELIST_S, EntryGuards, NULL),
329 VAR("EntryGuardUnlistedSince", LINELIST_S, EntryGuards, NULL),
330 VAR("EntryGuardAddedBy", LINELIST_S, EntryGuards, NULL),
331 V(EntryGuards, LINELIST_V, NULL),
333 V(BWHistoryReadEnds, ISOTIME, NULL),
334 V(BWHistoryReadInterval, UINT, "900"),
335 V(BWHistoryReadValues, CSV, ""),
336 V(BWHistoryWriteEnds, ISOTIME, NULL),
337 V(BWHistoryWriteInterval, UINT, "900"),
338 V(BWHistoryWriteValues, CSV, ""),
340 V(TorVersion, STRING, NULL),
342 V(LastRotatedOnionKey, ISOTIME, NULL),
343 V(LastWritten, ISOTIME, NULL),
345 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
348 #undef VAR
349 #undef V
350 #undef OBSOLETE
352 /** Represents an English description of a configuration variable; used when
353 * generating configuration file comments. */
354 typedef struct config_var_description_t {
355 const char *name;
356 const char *description;
357 } config_var_description_t;
359 static config_var_description_t options_description[] = {
360 /* ==== general options */
361 { "AvoidDiskWrites", "If non-zero, try to write to disk less frequently than"
362 " we would otherwise." },
363 { "BandwidthRate", "A token bucket limits the average incoming bandwidth on "
364 "this node to the specified number of bytes per second." },
365 { "BandwidthBurst", "Limit the maximum token buffer size (also known as "
366 "burst) to the given number of bytes." },
367 { "ConnLimit", "Minimum number of simultaneous sockets we must have." },
368 { "ConstrainedSockets", "Shrink tx and rx buffers for sockets to avoid "
369 "system limits on vservers and related environments. See man page for "
370 "more information regarding this option." },
371 { "ConstrainedSockSize", "Limit socket buffers to this size when "
372 "ConstrainedSockets is enabled." },
373 /* ControlListenAddress */
374 { "ControlPort", "If set, Tor will accept connections from the same machine "
375 "(localhost only) on this port, and allow those connections to control "
376 "the Tor process using the Tor Control Protocol (described in"
377 "control-spec.txt).", },
378 { "CookieAuthentication", "If this option is set to 1, don't allow any "
379 "connections to the control port except when the connecting process "
380 "can read a file that Tor creates in its data directory." },
381 { "DataDirectory", "Store working data, state, keys, and caches here." },
382 { "DirServer", "Tor only trusts directories signed with one of these "
383 "servers' keys. Used to override the standard list of directory "
384 "authorities." },
385 /* { "FastFirstHopPK", "" }, */
386 /* FetchServerDescriptors, FetchHidServDescriptors,
387 * FetchUselessDescriptors */
388 { "Group", "On startup, setgid to this group." },
389 { "HardwareAccel", "If set, Tor tries to use hardware crypto accelerators "
390 "when it can." },
391 /* HashedControlPassword */
392 { "HTTPProxy", "Force Tor to make all HTTP directory requests through this "
393 "host:port (or host:80 if port is not set)." },
394 { "HTTPProxyAuthenticator", "A username:password pair to be used with "
395 "HTTPProxy." },
396 { "HTTPSProxy", "Force Tor to make all TLS (SSL) connectinos through this "
397 "host:port (or host:80 if port is not set)." },
398 { "HTTPSProxyAuthenticator", "A username:password pair to be used with "
399 "HTTPSProxy." },
400 { "KeepalivePeriod", "Send a padding cell every N seconds to keep firewalls "
401 "from closing our connections while Tor is not in use." },
402 { "Log", "Where to send logging messages. Format is "
403 "minSeverity[-maxSeverity] (stderr|stdout|syslog|file FILENAME)." },
404 { "OutboundBindAddress", "Make all outbound connections originate from the "
405 "provided IP address (only useful for multiple network interfaces)." },
406 { "PIDFile", "On startup, write our PID to this file. On clean shutdown, "
407 "remove the file." },
408 { "PreferTunneledDirConns", "If non-zero, avoid directory servers that "
409 "don't support tunneled connections." },
410 /* PreferTunneledDirConns */
411 /* ProtocolWarnings */
412 /* RephistTrackTime */
413 { "RunAsDaemon", "If set, Tor forks and daemonizes to the background when "
414 "started. Unix only." },
415 { "SafeLogging", "If set to 0, Tor logs potentially sensitive strings "
416 "rather than replacing them with the string [scrubbed]." },
417 { "TunnelDirConns", "If non-zero, when a directory server we contact "
418 "supports it, we will build a one-hop circuit and make an encrypted "
419 "connection via its ORPort." },
420 { "User", "On startup, setuid to this user" },
422 /* ==== client options */
423 { "AllowInvalidNodes", "Where on our circuits should Tor allow servers "
424 "that the directory authorities haven't called \"valid\"?" },
425 { "AllowNonRFC953Hostnames", "If set to 1, we don't automatically reject "
426 "hostnames for having invalid characters." },
427 /* CircuitBuildTimeout, CircuitIdleTimeout */
428 { "ClientOnly", "If set to 1, Tor will under no circumstances run as a "
429 "server, even if ORPort is enabled." },
430 { "EntryNodes", "A list of preferred entry nodes to use for the first hop "
431 "in circuits, when possible." },
432 /* { "EnforceDistinctSubnets" , "" }, */
433 { "ExitNodes", "A list of preferred nodes to use for the last hop in "
434 "circuits, when possible." },
435 { "ExcludeNodes", "A list of nodes never to use when building a circuit." },
436 { "FascistFirewall", "If set, Tor will only create outgoing connections to "
437 "servers running on the ports listed in FirewallPorts." },
438 { "FirewallPorts", "A list of ports that we can connect to. Only used "
439 "when FascistFirewall is set." },
440 { "LongLivedPorts", "A list of ports for services that tend to require "
441 "high-uptime connections." },
442 { "MapAddress", "Force Tor to treat all requests for one address as if "
443 "they were for another." },
444 { "NewCircuitPeriod", "Force Tor to consider whether to build a new circuit "
445 "every NUM seconds." },
446 { "MaxCircuitDirtiness", "Do not attach new streams to a circuit that has "
447 "been used more than this many seconds ago." },
448 /* NatdPort, NatdListenAddress */
449 { "NodeFamily", "A list of servers that constitute a 'family' and should "
450 "never be used in the same circuit." },
451 { "NumEntryGuards", "How many entry guards should we keep at a time?" },
452 /* PathlenCoinWeight */
453 { "ReachableAddresses", "Addresses we can connect to, as IP/bits:port-port. "
454 "By default, we assume all addresses are reachable." },
455 /* reachablediraddresses, reachableoraddresses. */
456 { "RendNodes", "A list of preferred nodes to use for a rendezvous point, "
457 "when possible." },
458 { "RendExcludenodes", "A list of nodes never to use as rendezvous points." },
459 /* SafeSOCKS */
460 { "SOCKSPort", "The port where we listen for SOCKS connections from "
461 "applications." },
462 { "SOCKSListenAddress", "Bind to this address to listen to connections from "
463 "SOCKS-speaking applications." },
464 { "SOCKSPolicy", "Set an entry policy to limit which addresses can connect "
465 "to the SOCKSPort." },
466 /* SocksTimeout */
467 { "StrictExitNodes", "If set, Tor will fail to operate when none of the "
468 "configured ExitNodes can be used." },
469 { "StrictEntryNodes", "If set, Tor will fail to operate when none of the "
470 "configured EntryNodes can be used." },
471 /* TestSocks */
472 { "TrackHostsExit", "Hosts and domains which should, if possible, be "
473 "accessed from the same exit node each time we connect to them." },
474 { "TrackHostsExitExpire", "Time after which we forget which exit we were "
475 "using to connect to hosts in TrackHostsExit." },
476 /* "TransPort", "TransListenAddress */
477 { "UseEntryGuards", "Set to 0 if we want to pick from the whole set of "
478 "servers for the first position in each circuit, rather than picking a "
479 "set of 'Guards' to prevent profiling attacks." },
481 /* === server options */
482 { "Address", "The advertised (external) address we should use." },
483 /* Accounting* options. */
484 /* AssumeReachable */
485 { "ContactInfo", "Administrative contact information to advertise for this "
486 "server." },
487 { "ExitPolicy", "Address/port ranges for which to accept or reject outgoing "
488 "connections on behalf of Tor users." },
489 /* { "ExitPolicyRejectPrivate, "" }, */
490 { "MaxAdvertisedBandwidth", "If set, we will not advertise more than this "
491 "amount of bandwidth for our bandwidth rate, regardless of how much "
492 "bandwidth we actually detect." },
493 { "MaxOnionsPending", "Reject new attempts to extend circuits when we "
494 "already have this many pending." },
495 { "MyFamily", "Declare a list of other servers as belonging to the same "
496 "family as this one, so that clients will not use two from the same "
497 "family in the same circuit." },
498 { "Nickname", "Set the server nickname." },
499 { "NoPublish", "{DEPRECATED}" },
500 { "NumCPUs", "How many processes to use at once for public-key crypto." },
501 { "ORPort", "Advertise this port to listen for connections from Tor clients "
502 "and servers." },
503 { "ORListenAddress", "Bind to this address to listen for connections from "
504 "clients and servers, instead of the default 0.0.0.0:ORPort." },
505 { "PublishServerDescriptor", "Set to 0 to keep the server from "
506 "uploading info to the directory authorities." },
507 /*{ "RedirectExit", "When an outgoing connection tries to connect to a "
508 *"given address, redirect it to another address instead." },
510 /* ServerDNS: DetectHijacking, ResolvConfFile, SearchDomains */
511 { "ShutdownWaitLength", "Wait this long for clients to finish when "
512 "shutting down because of a SIGINT." },
513 /* { "TestVia", } */
515 /* === directory cache options */
516 { "DirPort", "Serve directory information from this port, and act as a "
517 "directory cache." },
518 { "DirListenAddress", "Bind to this address to listen for connections from "
519 "clients and servers, instead of the default 0.0.0.0:DirPort." },
520 { "DirPolicy", "Set a policy to limit who can connect to the directory "
521 "port" },
523 /* Authority options: AuthDirBadExit, AuthDirInvalid, AuthDirReject,
524 * AuthDirRejectUnlisted, AuthDirListBadExits, AuthoritativeDirectory,
525 * DirAllowPrivateAddresses, HSAuthoritativeDir,
526 * NamingAuthoritativeDirectory, RecommendedVersions,
527 * RecommendedClientVersions, RecommendedServerVersions, RendPostPeriod,
528 * RunTesting, V1AuthoritativeDirectory, VersioningAuthoritativeDirectory, */
530 /* Hidden service options: HiddenService: dir,excludenodes, nodes,
531 * options, port. PublishHidServDescriptor */
533 /* Nonpersistent options: __LeaveStreamsUnattached, __AllDirActionsPrivate */
534 { NULL, NULL },
537 static config_var_description_t state_description[] = {
538 { "AccountingBytesReadInInterval",
539 "How many bytes have we read in this accounting period?" },
540 { "AccountingBytesWrittenInInterval",
541 "How many bytes have we written in this accounting period?" },
542 { "AccountingExpectedUsage",
543 "How many bytes did we expect to use per minute? (0 for no estimate.)" },
544 { "AccountingIntervalStart", "When did this accounting period begin?" },
545 { "AccountingSecondsActive", "How long have we been awake in this period?" },
547 { "BWHistoryReadEnds", "When does the last-recorded read-interval end?" },
548 { "BWHistoryReadInterval", "How long is each read-interval (in seconds)?" },
549 { "BWHistoryReadValues", "Number of bytes read in each interval." },
550 { "BWHistoryWriteEnds", "When does the last-recorded write-interval end?" },
551 { "BWHistoryWriteInterval", "How long is each write-interval (in seconds)?"},
552 { "BWHistoryWriteValues", "Number of bytes written in each interval." },
554 { "EntryGuard", "One of the nodes we have chosen as a fixed entry" },
555 { "EntryGuardDownSince",
556 "The last entry guard has been unreachable since this time." },
557 { "EntryGuardUnlistedSince",
558 "The last entry guard has been unusable since this time." },
560 { "LastRotatedOnionKey",
561 "The last time at which we changed the medium-term private key used for "
562 "building circuits." },
563 { "LastWritten", "When was this state file last regenerated?" },
565 { "TorVersion", "Which version of Tor generated this state file?" },
566 { NULL, NULL },
569 /** Type of a callback to validate whether a given configuration is
570 * well-formed and consistent. See options_trial_assign() for documentation
571 * of arguments. */
572 typedef int (*validate_fn_t)(void*,void*,int,char**);
574 /** Information on the keys, value types, key-to-struct-member mappings,
575 * variable descriptions, validation functions, and abbreviations for a
576 * configuration or storage format. */
577 typedef struct {
578 size_t size; /**< Size of the struct that everything gets parsed into. */
579 uint32_t magic; /**< Required 'magic value' to make sure we have a struct
580 * of the right type. */
581 off_t magic_offset; /**< Offset of the magic value within the struct. */
582 config_abbrev_t *abbrevs; /**< List of abbreviations that we expand when
583 * parsing this format. */
584 config_var_t *vars; /**< List of variables we recognize, their default
585 * values, and where we stick them in the structure. */
586 validate_fn_t validate_fn; /**< Function to validate config. */
587 /** Documentation for configuration variables. */
588 config_var_description_t *descriptions;
589 /** If present, extra is a LINELIST variable for unrecognized
590 * lines. Otherwise, unrecognized lines are an error. */
591 config_var_t *extra;
592 } config_format_t;
594 /** Macro: assert that <b>cfg</b> has the right magic field for format
595 * <b>fmt</b>. */
596 #define CHECK(fmt, cfg) STMT_BEGIN \
597 tor_assert(fmt && cfg); \
598 tor_assert((fmt)->magic == \
599 *(uint32_t*)STRUCT_VAR_P(cfg,fmt->magic_offset)); \
600 STMT_END
602 static void config_line_append(config_line_t **lst,
603 const char *key, const char *val);
604 static void option_clear(config_format_t *fmt, or_options_t *options,
605 config_var_t *var);
606 static void option_reset(config_format_t *fmt, or_options_t *options,
607 config_var_t *var, int use_defaults);
608 static void config_free(config_format_t *fmt, void *options);
609 static int config_lines_eq(config_line_t *a, config_line_t *b);
610 static int option_is_same(config_format_t *fmt,
611 or_options_t *o1, or_options_t *o2,
612 const char *name);
613 static or_options_t *options_dup(config_format_t *fmt, or_options_t *old);
614 static int options_validate(or_options_t *old_options, or_options_t *options,
615 int from_setconf, char **msg);
616 static int options_act_reversible(or_options_t *old_options, char **msg);
617 static int options_act(or_options_t *old_options);
618 static int options_transition_allowed(or_options_t *old, or_options_t *new,
619 char **msg);
620 static int options_transition_affects_workers(or_options_t *old_options,
621 or_options_t *new_options);
622 static int options_transition_affects_descriptor(or_options_t *old_options,
623 or_options_t *new_options);
624 static int check_nickname_list(const char *lst, const char *name, char **msg);
625 static void config_register_addressmaps(or_options_t *options);
627 static int parse_bridge_line(const char *line, int validate_only);
628 static int parse_dir_server_line(const char *line,
629 authority_type_t required_type,
630 int validate_only);
631 static int parse_redirect_line(smartlist_t *result,
632 config_line_t *line, char **msg);
633 static int validate_data_directory(or_options_t *options);
634 static int write_configuration_file(const char *fname, or_options_t *options);
635 static config_line_t *get_assigned_option(config_format_t *fmt,
636 or_options_t *options, const char *key,
637 int escape_val);
638 static void config_init(config_format_t *fmt, void *options);
639 static int or_state_validate(or_state_t *old_options, or_state_t *options,
640 int from_setconf, char **msg);
641 static int or_state_load(void);
642 static int options_init_logs(or_options_t *options, int validate_only);
644 static uint64_t config_parse_memunit(const char *s, int *ok);
645 static int config_parse_interval(const char *s, int *ok);
646 static void print_svn_version(void);
647 static void init_libevent(void);
648 static int opt_streq(const char *s1, const char *s2);
649 /** Versions of libevent. */
650 typedef enum {
651 /* Note: we compare these, so it's important that "old" precede everything,
652 * and that "other" come last. */
653 LE_OLD=0, LE_10C, LE_10D, LE_10E, LE_11, LE_11A, LE_11B, LE_12, LE_12A,
654 LE_13, LE_13A, LE_13B, LE_13C, LE_13D,
655 LE_OTHER
656 } le_version_t;
657 static le_version_t decode_libevent_version(void);
658 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
659 static void check_libevent_version(const char *m, int server);
660 #endif
662 /** Magic value for or_options_t. */
663 #define OR_OPTIONS_MAGIC 9090909
665 /** Configuration format for or_options_t. */
666 static config_format_t options_format = {
667 sizeof(or_options_t),
668 OR_OPTIONS_MAGIC,
669 STRUCT_OFFSET(or_options_t, _magic),
670 _option_abbrevs,
671 _option_vars,
672 (validate_fn_t)options_validate,
673 options_description,
674 NULL
677 /** Magic value for or_state_t. */
678 #define OR_STATE_MAGIC 0x57A73f57
680 /** "Extra" variable in the state that receives lines we can't parse. This
681 * lets us preserve options from versions of Tor newer than us. */
682 static config_var_t state_extra_var = {
683 "__extra", CONFIG_TYPE_LINELIST, STRUCT_OFFSET(or_state_t, ExtraLines), NULL
686 /** Configuration format for or_state_t. */
687 static config_format_t state_format = {
688 sizeof(or_state_t),
689 OR_STATE_MAGIC,
690 STRUCT_OFFSET(or_state_t, _magic),
691 _state_abbrevs,
692 _state_vars,
693 (validate_fn_t)or_state_validate,
694 state_description,
695 &state_extra_var,
699 * Functions to read and write the global options pointer.
702 /** Command-line and config-file options. */
703 static or_options_t *global_options = NULL;
704 /** Name of most recently read torrc file. */
705 static char *torrc_fname = NULL;
706 /** Persistent serialized state. */
707 static or_state_t *global_state = NULL;
709 /** Allocate an empty configuration object of a given format type. */
710 static void *
711 config_alloc(config_format_t *fmt)
713 void *opts = tor_malloc_zero(fmt->size);
714 *(uint32_t*)STRUCT_VAR_P(opts, fmt->magic_offset) = fmt->magic;
715 CHECK(fmt, opts);
716 return opts;
719 /** Return the currently configured options. */
720 or_options_t *
721 get_options(void)
723 tor_assert(global_options);
724 return global_options;
727 /** Change the current global options to contain <b>new_val</b> instead of
728 * their current value; take action based on the new value; free the old value
729 * as necessary.
732 set_options(or_options_t *new_val, char **msg)
734 or_options_t *old_options = global_options;
735 global_options = new_val;
736 /* Note that we pass the *old* options below, for comparison. It
737 * pulls the new options directly out of global_options. */
738 if (options_act_reversible(old_options, msg)<0) {
739 tor_assert(*msg);
740 global_options = old_options;
741 return -1;
743 if (options_act(old_options) < 0) { /* acting on the options failed. die. */
744 log_err(LD_BUG,
745 "Acting on config options left us in a broken state. Dying.");
746 exit(1);
748 if (old_options)
749 config_free(&options_format, old_options);
751 return 0;
754 extern const char tor_svn_revision[]; /* from tor_main.c */
756 static char *_version = NULL;
758 /** Return the current Tor version, possibly */
759 const char *
760 get_version(void)
762 if (_version == NULL) {
763 if (strlen(tor_svn_revision)) {
764 size_t len = strlen(VERSION)+strlen(tor_svn_revision)+8;
765 _version = tor_malloc(len);
766 tor_snprintf(_version, len, "%s (r%s)", VERSION, tor_svn_revision);
767 } else {
768 _version = tor_strdup(VERSION);
771 return _version;
774 /** Release all memory and resources held by global configuration structures.
776 void
777 config_free_all(void)
779 if (global_options) {
780 config_free(&options_format, global_options);
781 global_options = NULL;
783 if (global_state) {
784 config_free(&state_format, global_state);
785 global_state = NULL;
787 tor_free(torrc_fname);
788 tor_free(_version);
791 /** If options->SafeLogging is on, return a not very useful string,
792 * else return address.
794 const char *
795 safe_str(const char *address)
797 tor_assert(address);
798 if (get_options()->SafeLogging)
799 return "[scrubbed]";
800 else
801 return address;
804 /** Equivalent to escaped(safe_str(address)). See reentrancy note on
805 * escaped(): don't use this outside the main thread, or twice in the same
806 * log statement. */
807 const char *
808 escaped_safe_str(const char *address)
810 if (get_options()->SafeLogging)
811 return "[scrubbed]";
812 else
813 return escaped(address);
816 /** Add the default directory authorities directly into the trusted dir list,
817 * but only add them insofar as they share bits with <b>type</b>. */
818 static void
819 add_default_trusted_dir_authorities(authority_type_t type)
821 int i;
822 const char *dirservers[] = {
823 "moria1 v1 orport=9001 v3ident=5420FD8EA46BD4290F1D07A1883C9D85ECC486C4 "
824 "128.31.0.34:9031 FFCB 46DB 1339 DA84 674C 70D7 CB58 6434 C437 0441",
825 "moria2 v1 orport=9002 128.31.0.34:9032 "
826 "719B E45D E224 B607 C537 07D0 E214 3E2D 423E 74CF",
827 "tor26 v1 orport=443 v3ident=A9AC67E64B200BBF2FA26DF194AC0469E2A948C6 "
828 "86.59.21.38:80 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D",
829 "lefkada orport=443 v3ident=0D95B91896E6089AB9A3C6CB56E724CAF898C43F "
830 "140.247.60.64:80 38D4 F5FC F7B1 0232 28B8 95EA 56ED E7D5 CCDC AF32",
831 "dizum 194.109.206.212:80 "
832 "7EA6 EAD6 FD83 083C 538F 4403 8BBF A077 587D D755",
833 "Tonga orport=443 bridge no-v2 82.94.251.206:80 "
834 "4A0C CD2D DC79 9508 3D73 F5D6 6710 0C8A 5831 F16D",
835 "ides orport=9090 no-v2 v3ident=27B6B5996C426270A5C95488AA5BCEB6BCC86956 "
836 "216.224.124.114:9030 F397 038A DC51 3361 35E7 B80B D99C A384 4360 292B",
837 "gabelmoo orport=443 no-v2 "
838 "v3ident=EAA879B5C75032E462CB018630D2D0DF46EBA606 "
839 "88.198.7.215:80 6833 3D07 61BC F397 A587 A0C0 B963 E4A9 E99E C4D3",
840 "dannenberg orport=443 no-v2 "
841 "v3ident=585769C78764D58426B8B52B6651A5A71137189A "
842 "213.73.91.31:80 7BE6 83E6 5D48 1413 21C5 ED92 F075 C553 64AC 7123",
843 NULL
845 for (i=0; dirservers[i]; i++) {
846 if (parse_dir_server_line(dirservers[i], type, 0)<0) {
847 log_err(LD_BUG, "Couldn't parse internal dirserver line %s",
848 dirservers[i]);
853 /** Look at all the config options for using alternate directory
854 * authorities, and make sure none of them are broken. Also, warn the
855 * user if we changed any dangerous ones.
857 static int
858 validate_dir_authorities(or_options_t *options, or_options_t *old_options)
860 config_line_t *cl;
862 if (options->DirServers &&
863 (options->AlternateDirAuthority || options->AlternateBridgeAuthority ||
864 options->AlternateHSAuthority)) {
865 log_warn(LD_CONFIG,
866 "You cannot set both DirServers and Alternate*Authority.");
867 return -1;
870 /* do we want to complain to the user about being partitionable? */
871 if ((options->DirServers &&
872 (!old_options ||
873 !config_lines_eq(options->DirServers, old_options->DirServers))) ||
874 (options->AlternateDirAuthority &&
875 (!old_options ||
876 !config_lines_eq(options->AlternateDirAuthority,
877 old_options->AlternateDirAuthority)))) {
878 log_warn(LD_CONFIG,
879 "You have used DirServer or AlternateDirAuthority to "
880 "specify alternate directory authorities in "
881 "your configuration. This is potentially dangerous: it can "
882 "make you look different from all other Tor users, and hurt "
883 "your anonymity. Even if you've specified the same "
884 "authorities as Tor uses by default, the defaults could "
885 "change in the future. Be sure you know what you're doing.");
888 /* Now go through the four ways you can configure an alternate
889 * set of directory authorities, and make sure none are broken. */
890 for (cl = options->DirServers; cl; cl = cl->next)
891 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
892 return -1;
893 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
894 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
895 return -1;
896 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
897 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
898 return -1;
899 for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
900 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
901 return -1;
902 return 0;
905 /** Look at all the config options and assign new dir authorities
906 * as appropriate.
908 static int
909 consider_adding_dir_authorities(or_options_t *options,
910 or_options_t *old_options)
912 config_line_t *cl;
913 int need_to_update =
914 !smartlist_len(router_get_trusted_dir_servers()) || !old_options ||
915 !config_lines_eq(options->DirServers, old_options->DirServers) ||
916 !config_lines_eq(options->AlternateBridgeAuthority,
917 old_options->AlternateBridgeAuthority) ||
918 !config_lines_eq(options->AlternateDirAuthority,
919 old_options->AlternateDirAuthority) ||
920 !config_lines_eq(options->AlternateHSAuthority,
921 old_options->AlternateHSAuthority);
923 if (!need_to_update)
924 return 0; /* all done */
926 /* Start from a clean slate. */
927 clear_trusted_dir_servers();
929 if (!options->DirServers) {
930 /* then we may want some of the defaults */
931 authority_type_t type = NO_AUTHORITY;
932 if (!options->AlternateBridgeAuthority)
933 type |= BRIDGE_AUTHORITY;
934 if (!options->AlternateDirAuthority)
935 type |= V1_AUTHORITY | V2_AUTHORITY | V3_AUTHORITY;
936 if (!options->AlternateHSAuthority)
937 type |= HIDSERV_AUTHORITY;
938 add_default_trusted_dir_authorities(type);
941 for (cl = options->DirServers; cl; cl = cl->next)
942 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
943 return -1;
944 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
945 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
946 return -1;
947 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
948 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
949 return -1;
950 for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
951 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
952 return -1;
953 return 0;
956 /** Fetch the active option list, and take actions based on it. All of the
957 * things we do should survive being done repeatedly. If present,
958 * <b>old_options</b> contains the previous value of the options.
960 * Return 0 if all goes well, return -1 if things went badly.
962 static int
963 options_act_reversible(or_options_t *old_options, char **msg)
965 smartlist_t *new_listeners = smartlist_create();
966 smartlist_t *replaced_listeners = smartlist_create();
967 static int libevent_initialized = 0;
968 or_options_t *options = get_options();
969 int running_tor = options->command == CMD_RUN_TOR;
970 int set_conn_limit = 0;
971 int r = -1;
972 int logs_marked = 0;
974 /* Daemonize _first_, since we only want to open most of this stuff in
975 * the subprocess. Libevent bases can't be reliably inherited across
976 * processes. */
977 if (running_tor && options->RunAsDaemon) {
978 /* No need to roll back, since you can't change the value. */
979 start_daemon();
982 #ifndef HAVE_SYS_UN_H
983 if (options->ControlSocket) {
984 *msg = tor_strdup("Unix domain sockets (ControlSocket) not supported"
985 " on this OS/with this build.");
986 goto rollback;
988 #endif
990 if (running_tor) {
991 /* We need to set the connection limit before we can open the listeners. */
992 if (set_max_file_descriptors((unsigned)options->ConnLimit,
993 &options->_ConnLimit) < 0) {
994 *msg = tor_strdup("Problem with ConnLimit value. See logs for details.");
995 goto rollback;
997 set_conn_limit = 1;
999 /* Set up libevent. (We need to do this before we can register the
1000 * listeners as listeners.) */
1001 if (running_tor && !libevent_initialized) {
1002 init_libevent();
1003 libevent_initialized = 1;
1006 /* Launch the listeners. (We do this before we setuid, so we can bind to
1007 * ports under 1024.) */
1008 if (retry_all_listeners(replaced_listeners, new_listeners) < 0) {
1009 *msg = tor_strdup("Failed to bind one of the listener ports.");
1010 goto rollback;
1014 /* Setuid/setgid as appropriate */
1015 if (options->User || options->Group) {
1016 /* XXXX021 We should only do this the first time through, not on
1017 * every setconf. */
1018 if (switch_id(options->User, options->Group) != 0) {
1019 /* No need to roll back, since you can't change the value. */
1020 *msg = tor_strdup("Problem with User or Group value. "
1021 "See logs for details.");
1022 goto done;
1026 /* Ensure data directory is private; create if possible. */
1027 if (check_private_dir(options->DataDirectory,
1028 running_tor ? CPD_CREATE : CPD_CHECK)<0) {
1029 char buf[1024];
1030 int tmp = tor_snprintf(buf, sizeof(buf),
1031 "Couldn't access/create private data directory \"%s\"",
1032 options->DataDirectory);
1033 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1034 goto done;
1035 /* No need to roll back, since you can't change the value. */
1038 /* Bail out at this point if we're not going to be a client or server:
1039 * we don't run Tor itself. */
1040 if (!running_tor)
1041 goto commit;
1043 mark_logs_temp(); /* Close current logs once new logs are open. */
1044 logs_marked = 1;
1045 if (options_init_logs(options, 0)<0) { /* Configure the log(s) */
1046 *msg = tor_strdup("Failed to init Log options. See logs for details.");
1047 goto rollback;
1050 commit:
1051 r = 0;
1052 if (logs_marked) {
1053 log_severity_list_t *severity =
1054 tor_malloc_zero(sizeof(log_severity_list_t));
1055 close_temp_logs();
1056 add_callback_log(severity, control_event_logmsg);
1057 control_adjust_event_log_severity();
1058 tor_free(severity);
1060 SMARTLIST_FOREACH(replaced_listeners, connection_t *, conn,
1062 log_notice(LD_NET, "Closing old %s on %s:%d",
1063 conn_type_to_string(conn->type), conn->address, conn->port);
1064 connection_close_immediate(conn);
1065 connection_mark_for_close(conn);
1067 goto done;
1069 rollback:
1070 r = -1;
1071 tor_assert(*msg);
1073 if (logs_marked) {
1074 rollback_log_changes();
1075 control_adjust_event_log_severity();
1078 if (set_conn_limit && old_options)
1079 set_max_file_descriptors((unsigned)old_options->ConnLimit,
1080 &options->_ConnLimit);
1082 SMARTLIST_FOREACH(new_listeners, connection_t *, conn,
1084 log_notice(LD_NET, "Closing partially-constructed listener %s on %s:%d",
1085 conn_type_to_string(conn->type), conn->address, conn->port);
1086 connection_close_immediate(conn);
1087 connection_mark_for_close(conn);
1090 done:
1091 smartlist_free(new_listeners);
1092 smartlist_free(replaced_listeners);
1093 return r;
1096 /** Fetch the active option list, and take actions based on it. All of the
1097 * things we do should survive being done repeatedly. If present,
1098 * <b>old_options</b> contains the previous value of the options.
1100 * Return 0 if all goes well, return -1 if it's time to die.
1102 * Note: We haven't moved all the "act on new configuration" logic
1103 * here yet. Some is still in do_hup() and other places.
1105 static int
1106 options_act(or_options_t *old_options)
1108 config_line_t *cl;
1109 char *fn;
1110 size_t len;
1111 or_options_t *options = get_options();
1112 int running_tor = options->command == CMD_RUN_TOR;
1113 char *msg;
1115 if (consider_adding_dir_authorities(options, old_options) < 0)
1116 return -1;
1118 if (options->Bridges) {
1119 clear_bridge_list();
1120 for (cl = options->Bridges; cl; cl = cl->next) {
1121 if (parse_bridge_line(cl->value, 0)<0) {
1122 log_warn(LD_BUG,
1123 "Previously validated Bridge line could not be added!");
1124 return -1;
1129 if (running_tor && rend_config_services(options, 0)<0) {
1130 log_warn(LD_BUG,
1131 "Previously validated hidden services line could not be added!");
1132 return -1;
1135 if (running_tor && directory_caches_v2_dir_info(options)) {
1136 len = strlen(options->DataDirectory)+32;
1137 fn = tor_malloc(len);
1138 tor_snprintf(fn, len, "%s"PATH_SEPARATOR"cached-status",
1139 options->DataDirectory);
1140 if (check_private_dir(fn, CPD_CREATE) != 0) {
1141 log_warn(LD_CONFIG,
1142 "Couldn't access/create private data directory \"%s\"", fn);
1143 tor_free(fn);
1144 return -1;
1146 tor_free(fn);
1149 /* Load state */
1150 if (! global_state && running_tor) {
1151 if (or_state_load())
1152 return -1;
1153 rep_hist_load_mtbf_data(time(NULL));
1156 /* Bail out at this point if we're not going to be a client or server:
1157 * we want to not fork, and to log stuff to stderr. */
1158 if (!running_tor)
1159 return 0;
1162 smartlist_t *sl = smartlist_create();
1163 char *errmsg = NULL;
1164 for (cl = options->RedirectExit; cl; cl = cl->next) {
1165 if (parse_redirect_line(sl, cl, &errmsg)<0) {
1166 log_warn(LD_CONFIG, "%s", errmsg);
1167 tor_free(errmsg);
1168 SMARTLIST_FOREACH(sl, exit_redirect_t *, er, tor_free(er));
1169 smartlist_free(sl);
1170 return -1;
1173 set_exit_redirects(sl);
1176 /* Finish backgrounding the process */
1177 if (running_tor && options->RunAsDaemon) {
1178 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
1179 finish_daemon(options->DataDirectory);
1182 /* Write our pid to the pid file. If we do not have write permissions we
1183 * will log a warning */
1184 if (running_tor && options->PidFile)
1185 write_pidfile(options->PidFile);
1187 /* Register addressmap directives */
1188 config_register_addressmaps(options);
1189 parse_virtual_addr_network(options->VirtualAddrNetwork, 0, &msg);
1191 /* Update address policies. */
1192 if (policies_parse_from_options(options) < 0) {
1193 /* This should be impossible, but let's be sure. */
1194 log_warn(LD_BUG,"Error parsing already-validated policy options.");
1195 return -1;
1198 if (init_cookie_authentication(options->CookieAuthentication) < 0) {
1199 log_warn(LD_CONFIG,"Error creating cookie authentication file.");
1200 return -1;
1203 /* reload keys as needed for rendezvous services. */
1204 if (rend_service_load_keys()<0) {
1205 log_warn(LD_GENERAL,"Error loading rendezvous service keys");
1206 return -1;
1209 /* Set up accounting */
1210 if (accounting_parse_options(options, 0)<0) {
1211 log_warn(LD_CONFIG,"Error in accounting options");
1212 return -1;
1214 if (accounting_is_enabled(options))
1215 configure_accounting(time(NULL));
1217 /* Check for transitions that need action. */
1218 if (old_options) {
1219 if (options->UseEntryGuards && !old_options->UseEntryGuards) {
1220 log_info(LD_CIRC,
1221 "Switching to entry guards; abandoning previous circuits");
1222 circuit_mark_all_unused_circs();
1223 circuit_expire_all_dirty_circs();
1226 if (options_transition_affects_workers(old_options, options)) {
1227 log_info(LD_GENERAL,
1228 "Worker-related options changed. Rotating workers.");
1229 if (server_mode(options) && !server_mode(old_options)) {
1230 if (init_keys() < 0) {
1231 log_warn(LD_BUG,"Error initializing keys; exiting");
1232 return -1;
1234 ip_address_changed(0);
1235 if (has_completed_circuit || !any_predicted_circuits(time(NULL)))
1236 inform_testing_reachability();
1238 cpuworkers_rotate();
1239 if (dns_reset())
1240 return -1;
1241 } else {
1242 if (dns_reset())
1243 return -1;
1246 if (options->V3AuthoritativeDir && !old_options->V3AuthoritativeDir)
1247 init_keys();
1250 /* Maybe load geoip file */
1251 if (options->GeoIPFile &&
1252 ((!old_options || !opt_streq(old_options->GeoIPFile, options->GeoIPFile))
1253 || !geoip_is_loaded())) {
1254 geoip_load_file(options->GeoIPFile);
1256 /* Check if we need to parse and add the EntryNodes config option. */
1257 if (options->EntryNodes &&
1258 (!old_options ||
1259 !opt_streq(old_options->EntryNodes, options->EntryNodes)))
1260 entry_nodes_should_be_added();
1262 /* Since our options changed, we might need to regenerate and upload our
1263 * server descriptor.
1265 if (!old_options ||
1266 options_transition_affects_descriptor(old_options, options))
1267 mark_my_descriptor_dirty();
1269 /* We may need to reschedule some directory stuff if our status changed. */
1270 if (old_options) {
1271 if (authdir_mode_v3(options) && !authdir_mode_v3(old_options))
1272 dirvote_recalculate_timing(options, time(NULL));
1273 if (!bool_eq(directory_fetches_dir_info_early(options),
1274 directory_fetches_dir_info_early(old_options)) ||
1275 !bool_eq(directory_fetches_dir_info_later(options),
1276 directory_fetches_dir_info_later(old_options))) {
1277 /* Make sure update_router_have_min_dir_info gets called. */
1278 router_dir_info_changed();
1279 /* We might need to download a new consensus status later or sooner than
1280 * we had expected. */
1281 update_consensus_networkstatus_fetch_time(time(NULL));
1285 return 0;
1289 * Functions to parse config options
1292 /** If <b>option</b> is an official abbreviation for a longer option,
1293 * return the longer option. Otherwise return <b>option</b>.
1294 * If <b>command_line</b> is set, apply all abbreviations. Otherwise, only
1295 * apply abbreviations that work for the config file and the command line.
1296 * If <b>warn_obsolete</b> is set, warn about deprecated names. */
1297 static const char *
1298 expand_abbrev(config_format_t *fmt, const char *option, int command_line,
1299 int warn_obsolete)
1301 int i;
1302 if (! fmt->abbrevs)
1303 return option;
1304 for (i=0; fmt->abbrevs[i].abbreviated; ++i) {
1305 /* Abbreviations are casei. */
1306 if (!strcasecmp(option,fmt->abbrevs[i].abbreviated) &&
1307 (command_line || !fmt->abbrevs[i].commandline_only)) {
1308 if (warn_obsolete && fmt->abbrevs[i].warn) {
1309 log_warn(LD_CONFIG,
1310 "The configuration option '%s' is deprecated; "
1311 "use '%s' instead.",
1312 fmt->abbrevs[i].abbreviated,
1313 fmt->abbrevs[i].full);
1315 return fmt->abbrevs[i].full;
1318 return option;
1321 /** Helper: Read a list of configuration options from the command line.
1322 * If successful, put them in *<b>result</b> and return 0, and return
1323 * -1 and leave *<b>result</b> alone. */
1324 static int
1325 config_get_commandlines(int argc, char **argv, config_line_t **result)
1327 config_line_t *front = NULL;
1328 config_line_t **new = &front;
1329 char *s;
1330 int i = 1;
1332 while (i < argc) {
1333 if (!strcmp(argv[i],"-f") ||
1334 !strcmp(argv[i],"--hash-password")) {
1335 i += 2; /* command-line option with argument. ignore them. */
1336 continue;
1337 } else if (!strcmp(argv[i],"--list-fingerprint") ||
1338 !strcmp(argv[i],"--verify-config") ||
1339 !strcmp(argv[i],"--ignore-missing-torrc") ||
1340 !strcmp(argv[i],"--quiet")) {
1341 i += 1; /* command-line option. ignore it. */
1342 continue;
1343 } else if (!strcmp(argv[i],"--nt-service") ||
1344 !strcmp(argv[i],"-nt-service")) {
1345 i += 1;
1346 continue;
1349 if (i == argc-1) {
1350 log_warn(LD_CONFIG,"Command-line option '%s' with no value. Failing.",
1351 argv[i]);
1352 config_free_lines(front);
1353 return -1;
1356 *new = tor_malloc_zero(sizeof(config_line_t));
1357 s = argv[i];
1359 while (*s == '-')
1360 s++;
1362 (*new)->key = tor_strdup(expand_abbrev(&options_format, s, 1, 1));
1363 (*new)->value = tor_strdup(argv[i+1]);
1364 (*new)->next = NULL;
1365 log(LOG_DEBUG, LD_CONFIG, "Commandline: parsed keyword '%s', value '%s'",
1366 (*new)->key, (*new)->value);
1368 new = &((*new)->next);
1369 i += 2;
1371 *result = front;
1372 return 0;
1375 /** Helper: allocate a new configuration option mapping 'key' to 'val',
1376 * append it to *<b>lst</b>. */
1377 static void
1378 config_line_append(config_line_t **lst,
1379 const char *key,
1380 const char *val)
1382 config_line_t *newline;
1384 newline = tor_malloc(sizeof(config_line_t));
1385 newline->key = tor_strdup(key);
1386 newline->value = tor_strdup(val);
1387 newline->next = NULL;
1388 while (*lst)
1389 lst = &((*lst)->next);
1391 (*lst) = newline;
1394 /** Helper: parse the config string and strdup into key/value
1395 * strings. Set *result to the list, or NULL if parsing the string
1396 * failed. Return 0 on success, -1 on failure. Warn and ignore any
1397 * misformatted lines. */
1399 config_get_lines(const char *string, config_line_t **result)
1401 config_line_t *list = NULL, **next;
1402 char *k, *v;
1404 next = &list;
1405 do {
1406 string = parse_config_line_from_str(string, &k, &v);
1407 if (!string) {
1408 config_free_lines(list);
1409 return -1;
1411 if (k && v) {
1412 /* This list can get long, so we keep a pointer to the end of it
1413 * rather than using config_line_append over and over and getting
1414 * n^2 performance. */
1415 *next = tor_malloc(sizeof(config_line_t));
1416 (*next)->key = k;
1417 (*next)->value = v;
1418 (*next)->next = NULL;
1419 next = &((*next)->next);
1420 } else {
1421 tor_free(k);
1422 tor_free(v);
1424 } while (*string);
1426 *result = list;
1427 return 0;
1431 * Free all the configuration lines on the linked list <b>front</b>.
1433 void
1434 config_free_lines(config_line_t *front)
1436 config_line_t *tmp;
1438 while (front) {
1439 tmp = front;
1440 front = tmp->next;
1442 tor_free(tmp->key);
1443 tor_free(tmp->value);
1444 tor_free(tmp);
1448 /** Return the description for a given configuration variable, or NULL if no
1449 * description exists. */
1450 static const char *
1451 config_find_description(config_format_t *fmt, const char *name)
1453 int i;
1454 for (i=0; fmt->descriptions[i].name; ++i) {
1455 if (!strcasecmp(name, fmt->descriptions[i].name))
1456 return fmt->descriptions[i].description;
1458 return NULL;
1461 /** If <b>key</b> is a configuration option, return the corresponding
1462 * config_var_t. Otherwise, if <b>key</b> is a non-standard abbreviation,
1463 * warn, and return the corresponding config_var_t. Otherwise return NULL.
1465 static config_var_t *
1466 config_find_option(config_format_t *fmt, const char *key)
1468 int i;
1469 size_t keylen = strlen(key);
1470 if (!keylen)
1471 return NULL; /* if they say "--" on the commandline, it's not an option */
1472 /* First, check for an exact (case-insensitive) match */
1473 for (i=0; fmt->vars[i].name; ++i) {
1474 if (!strcasecmp(key, fmt->vars[i].name)) {
1475 return &fmt->vars[i];
1478 /* If none, check for an abbreviated match */
1479 for (i=0; fmt->vars[i].name; ++i) {
1480 if (!strncasecmp(key, fmt->vars[i].name, keylen)) {
1481 log_warn(LD_CONFIG, "The abbreviation '%s' is deprecated. "
1482 "Please use '%s' instead",
1483 key, fmt->vars[i].name);
1484 return &fmt->vars[i];
1487 /* Okay, unrecognized option */
1488 return NULL;
1492 * Functions to assign config options.
1495 /** <b>c</b>-\>key is known to be a real key. Update <b>options</b>
1496 * with <b>c</b>-\>value and return 0, or return -1 if bad value.
1498 * Called from config_assign_line() and option_reset().
1500 static int
1501 config_assign_value(config_format_t *fmt, or_options_t *options,
1502 config_line_t *c, char **msg)
1504 int i, r, ok;
1505 char buf[1024];
1506 config_var_t *var;
1507 void *lvalue;
1509 CHECK(fmt, options);
1511 var = config_find_option(fmt, c->key);
1512 tor_assert(var);
1514 lvalue = STRUCT_VAR_P(options, var->var_offset);
1516 switch (var->type) {
1518 case CONFIG_TYPE_UINT:
1519 i = (int)tor_parse_long(c->value, 10, 0, INT_MAX, &ok, NULL);
1520 if (!ok) {
1521 r = tor_snprintf(buf, sizeof(buf),
1522 "Int keyword '%s %s' is malformed or out of bounds.",
1523 c->key, c->value);
1524 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1525 return -1;
1527 *(int *)lvalue = i;
1528 break;
1530 case CONFIG_TYPE_INTERVAL: {
1531 i = config_parse_interval(c->value, &ok);
1532 if (!ok) {
1533 r = tor_snprintf(buf, sizeof(buf),
1534 "Interval '%s %s' is malformed or out of bounds.",
1535 c->key, c->value);
1536 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1537 return -1;
1539 *(int *)lvalue = i;
1540 break;
1543 case CONFIG_TYPE_MEMUNIT: {
1544 uint64_t u64 = config_parse_memunit(c->value, &ok);
1545 if (!ok) {
1546 r = tor_snprintf(buf, sizeof(buf),
1547 "Value '%s %s' is malformed or out of bounds.",
1548 c->key, c->value);
1549 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1550 return -1;
1552 *(uint64_t *)lvalue = u64;
1553 break;
1556 case CONFIG_TYPE_BOOL:
1557 i = (int)tor_parse_long(c->value, 10, 0, 1, &ok, NULL);
1558 if (!ok) {
1559 r = tor_snprintf(buf, sizeof(buf),
1560 "Boolean '%s %s' expects 0 or 1.",
1561 c->key, c->value);
1562 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1563 return -1;
1565 *(int *)lvalue = i;
1566 break;
1568 case CONFIG_TYPE_STRING:
1569 tor_free(*(char **)lvalue);
1570 *(char **)lvalue = tor_strdup(c->value);
1571 break;
1573 case CONFIG_TYPE_DOUBLE:
1574 *(double *)lvalue = atof(c->value);
1575 break;
1577 case CONFIG_TYPE_ISOTIME:
1578 if (parse_iso_time(c->value, (time_t *)lvalue)) {
1579 r = tor_snprintf(buf, sizeof(buf),
1580 "Invalid time '%s' for keyword '%s'", c->value, c->key);
1581 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1582 return -1;
1584 break;
1586 case CONFIG_TYPE_CSV:
1587 if (*(smartlist_t**)lvalue) {
1588 SMARTLIST_FOREACH(*(smartlist_t**)lvalue, char *, cp, tor_free(cp));
1589 smartlist_clear(*(smartlist_t**)lvalue);
1590 } else {
1591 *(smartlist_t**)lvalue = smartlist_create();
1594 smartlist_split_string(*(smartlist_t**)lvalue, c->value, ",",
1595 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1596 break;
1598 case CONFIG_TYPE_LINELIST:
1599 case CONFIG_TYPE_LINELIST_S:
1600 config_line_append((config_line_t**)lvalue, c->key, c->value);
1601 break;
1603 case CONFIG_TYPE_OBSOLETE:
1604 log_warn(LD_CONFIG, "Skipping obsolete configuration option '%s'", c->key);
1605 break;
1606 case CONFIG_TYPE_LINELIST_V:
1607 r = tor_snprintf(buf, sizeof(buf),
1608 "You may not provide a value for virtual option '%s'", c->key);
1609 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1610 return -1;
1611 default:
1612 tor_assert(0);
1613 break;
1615 return 0;
1618 /** If <b>c</b> is a syntactically valid configuration line, update
1619 * <b>options</b> with its value and return 0. Otherwise return -1 for bad
1620 * key, -2 for bad value.
1622 * If <b>clear_first</b> is set, clear the value first. Then if
1623 * <b>use_defaults</b> is set, set the value to the default.
1625 * Called from config_assign().
1627 static int
1628 config_assign_line(config_format_t *fmt, or_options_t *options,
1629 config_line_t *c, int use_defaults,
1630 int clear_first, char **msg)
1632 config_var_t *var;
1634 CHECK(fmt, options);
1636 var = config_find_option(fmt, c->key);
1637 if (!var) {
1638 if (fmt->extra) {
1639 void *lvalue = STRUCT_VAR_P(options, fmt->extra->var_offset);
1640 log_info(LD_CONFIG,
1641 "Found unrecognized option '%s'; saving it.", c->key);
1642 config_line_append((config_line_t**)lvalue, c->key, c->value);
1643 return 0;
1644 } else {
1645 char buf[1024];
1646 int tmp = tor_snprintf(buf, sizeof(buf),
1647 "Unknown option '%s'. Failing.", c->key);
1648 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1649 return -1;
1652 /* Put keyword into canonical case. */
1653 if (strcmp(var->name, c->key)) {
1654 tor_free(c->key);
1655 c->key = tor_strdup(var->name);
1658 if (!strlen(c->value)) {
1659 /* reset or clear it, then return */
1660 if (!clear_first) {
1661 if (var->type == CONFIG_TYPE_LINELIST ||
1662 var->type == CONFIG_TYPE_LINELIST_S) {
1663 /* We got an empty linelist from the torrc or commandline.
1664 As a special case, call this an error. Warn and ignore. */
1665 log_warn(LD_CONFIG,
1666 "Linelist option '%s' has no value. Skipping.", c->key);
1667 } else { /* not already cleared */
1668 option_reset(fmt, options, var, use_defaults);
1671 return 0;
1674 if (config_assign_value(fmt, options, c, msg) < 0)
1675 return -2;
1676 return 0;
1679 /** Restore the option named <b>key</b> in options to its default value.
1680 * Called from config_assign(). */
1681 static void
1682 config_reset_line(config_format_t *fmt, or_options_t *options,
1683 const char *key, int use_defaults)
1685 config_var_t *var;
1687 CHECK(fmt, options);
1689 var = config_find_option(fmt, key);
1690 if (!var)
1691 return; /* give error on next pass. */
1693 option_reset(fmt, options, var, use_defaults);
1696 /** Return true iff key is a valid configuration option. */
1698 option_is_recognized(const char *key)
1700 config_var_t *var = config_find_option(&options_format, key);
1701 return (var != NULL);
1704 /** Return the canonical name of a configuration option, or NULL
1705 * if no such option exists. */
1706 const char *
1707 option_get_canonical_name(const char *key)
1709 config_var_t *var = config_find_option(&options_format, key);
1710 return var ? var->name : NULL;
1713 /** Return a canonicalized list of the options assigned for key.
1715 config_line_t *
1716 option_get_assignment(or_options_t *options, const char *key)
1718 return get_assigned_option(&options_format, options, key, 1);
1721 /** Return true iff value needs to be quoted and escaped to be used in
1722 * a configuration file. */
1723 static int
1724 config_value_needs_escape(const char *value)
1726 if (*value == '\"')
1727 return 1;
1728 while (*value) {
1729 switch (*value)
1731 case '\r':
1732 case '\n':
1733 case '#':
1734 /* Note: quotes and backspaces need special handling when we are using
1735 * quotes, not otherwise, so they don't trigger escaping on their
1736 * own. */
1737 return 1;
1738 default:
1739 if (!TOR_ISPRINT(*value))
1740 return 1;
1742 ++value;
1744 return 0;
1747 /** Return a newly allocated deep copy of the lines in <b>inp</b>. */
1748 static config_line_t *
1749 config_lines_dup(const config_line_t *inp)
1751 config_line_t *result = NULL;
1752 config_line_t **next_out = &result;
1753 while (inp) {
1754 *next_out = tor_malloc(sizeof(config_line_t));
1755 (*next_out)->key = tor_strdup(inp->key);
1756 (*next_out)->value = tor_strdup(inp->value);
1757 inp = inp->next;
1758 next_out = &((*next_out)->next);
1760 (*next_out) = NULL;
1761 return result;
1764 /** Return newly allocated line or lines corresponding to <b>key</b> in the
1765 * configuration <b>options</b>. If <b>escape_val</b> is true and a
1766 * value needs to be quoted before it's put in a config file, quote and
1767 * escape that value. Return NULL if no such key exists. */
1768 static config_line_t *
1769 get_assigned_option(config_format_t *fmt, or_options_t *options,
1770 const char *key, int escape_val)
1771 /* XXXX argument is options, but fmt is provided. Inconsistent. */
1773 config_var_t *var;
1774 const void *value;
1775 char buf[32];
1776 config_line_t *result;
1777 tor_assert(options && key);
1779 CHECK(fmt, options);
1781 var = config_find_option(fmt, key);
1782 if (!var) {
1783 log_warn(LD_CONFIG, "Unknown option '%s'. Failing.", key);
1784 return NULL;
1786 value = STRUCT_VAR_P(options, var->var_offset);
1788 result = tor_malloc_zero(sizeof(config_line_t));
1789 result->key = tor_strdup(var->name);
1790 switch (var->type)
1792 case CONFIG_TYPE_STRING:
1793 if (*(char**)value) {
1794 result->value = tor_strdup(*(char**)value);
1795 } else {
1796 tor_free(result->key);
1797 tor_free(result);
1798 return NULL;
1800 break;
1801 case CONFIG_TYPE_ISOTIME:
1802 if (*(time_t*)value) {
1803 result->value = tor_malloc(ISO_TIME_LEN+1);
1804 format_iso_time(result->value, *(time_t*)value);
1805 } else {
1806 tor_free(result->key);
1807 tor_free(result);
1809 escape_val = 0; /* Can't need escape. */
1810 break;
1811 case CONFIG_TYPE_INTERVAL:
1812 case CONFIG_TYPE_UINT:
1813 /* This means every or_options_t uint or bool element
1814 * needs to be an int. Not, say, a uint16_t or char. */
1815 tor_snprintf(buf, sizeof(buf), "%d", *(int*)value);
1816 result->value = tor_strdup(buf);
1817 escape_val = 0; /* Can't need escape. */
1818 break;
1819 case CONFIG_TYPE_MEMUNIT:
1820 tor_snprintf(buf, sizeof(buf), U64_FORMAT,
1821 U64_PRINTF_ARG(*(uint64_t*)value));
1822 result->value = tor_strdup(buf);
1823 escape_val = 0; /* Can't need escape. */
1824 break;
1825 case CONFIG_TYPE_DOUBLE:
1826 tor_snprintf(buf, sizeof(buf), "%f", *(double*)value);
1827 result->value = tor_strdup(buf);
1828 escape_val = 0; /* Can't need escape. */
1829 break;
1830 case CONFIG_TYPE_BOOL:
1831 result->value = tor_strdup(*(int*)value ? "1" : "0");
1832 escape_val = 0; /* Can't need escape. */
1833 break;
1834 case CONFIG_TYPE_CSV:
1835 if (*(smartlist_t**)value)
1836 result->value =
1837 smartlist_join_strings(*(smartlist_t**)value, ",", 0, NULL);
1838 else
1839 result->value = tor_strdup("");
1840 break;
1841 case CONFIG_TYPE_OBSOLETE:
1842 log_warn(LD_CONFIG,
1843 "You asked me for the value of an obsolete config option '%s'.",
1844 key);
1845 tor_free(result->key);
1846 tor_free(result);
1847 return NULL;
1848 case CONFIG_TYPE_LINELIST_S:
1849 log_warn(LD_CONFIG,
1850 "Can't return context-sensitive '%s' on its own", key);
1851 tor_free(result->key);
1852 tor_free(result);
1853 return NULL;
1854 case CONFIG_TYPE_LINELIST:
1855 case CONFIG_TYPE_LINELIST_V:
1856 tor_free(result->key);
1857 tor_free(result);
1858 result = config_lines_dup(*(const config_line_t**)value);
1859 break;
1860 default:
1861 tor_free(result->key);
1862 tor_free(result);
1863 log_warn(LD_BUG,"Unknown type %d for known key '%s'",
1864 var->type, key);
1865 return NULL;
1868 if (escape_val) {
1869 config_line_t *line;
1870 for (line = result; line; line = line->next) {
1871 if (line->value && config_value_needs_escape(line->value)) {
1872 char *newval = esc_for_log(line->value);
1873 tor_free(line->value);
1874 line->value = newval;
1879 return result;
1882 /** Iterate through the linked list of requested options <b>list</b>.
1883 * For each item, convert as appropriate and assign to <b>options</b>.
1884 * If an item is unrecognized, set *msg and return -1 immediately,
1885 * else return 0 for success.
1887 * If <b>clear_first</b>, interpret config options as replacing (not
1888 * extending) their previous values. If <b>clear_first</b> is set,
1889 * then <b>use_defaults</b> to decide if you set to defaults after
1890 * clearing, or make the value 0 or NULL.
1892 * Here are the use cases:
1893 * 1. A non-empty AllowInvalid line in your torrc. Appends to current
1894 * if linelist, replaces current if csv.
1895 * 2. An empty AllowInvalid line in your torrc. Should clear it.
1896 * 3. "RESETCONF AllowInvalid" sets it to default.
1897 * 4. "SETCONF AllowInvalid" makes it NULL.
1898 * 5. "SETCONF AllowInvalid=foo" clears it and sets it to "foo".
1900 * Use_defaults Clear_first
1901 * 0 0 "append"
1902 * 1 0 undefined, don't use
1903 * 0 1 "set to null first"
1904 * 1 1 "set to defaults first"
1905 * Return 0 on success, -1 on bad key, -2 on bad value.
1907 * As an additional special case, if a LINELIST config option has
1908 * no value and clear_first is 0, then warn and ignore it.
1912 There are three call cases for config_assign() currently.
1914 Case one: Torrc entry
1915 options_init_from_torrc() calls config_assign(0, 0)
1916 calls config_assign_line(0, 0).
1917 if value is empty, calls option_reset(0) and returns.
1918 calls config_assign_value(), appends.
1920 Case two: setconf
1921 options_trial_assign() calls config_assign(0, 1)
1922 calls config_reset_line(0)
1923 calls option_reset(0)
1924 calls option_clear().
1925 calls config_assign_line(0, 1).
1926 if value is empty, returns.
1927 calls config_assign_value(), appends.
1929 Case three: resetconf
1930 options_trial_assign() calls config_assign(1, 1)
1931 calls config_reset_line(1)
1932 calls option_reset(1)
1933 calls option_clear().
1934 calls config_assign_value(default)
1935 calls config_assign_line(1, 1).
1936 returns.
1938 static int
1939 config_assign(config_format_t *fmt, void *options, config_line_t *list,
1940 int use_defaults, int clear_first, char **msg)
1942 config_line_t *p;
1944 CHECK(fmt, options);
1946 /* pass 1: normalize keys */
1947 for (p = list; p; p = p->next) {
1948 const char *full = expand_abbrev(fmt, p->key, 0, 1);
1949 if (strcmp(full,p->key)) {
1950 tor_free(p->key);
1951 p->key = tor_strdup(full);
1955 /* pass 2: if we're reading from a resetting source, clear all
1956 * mentioned config options, and maybe set to their defaults. */
1957 if (clear_first) {
1958 for (p = list; p; p = p->next)
1959 config_reset_line(fmt, options, p->key, use_defaults);
1962 /* pass 3: assign. */
1963 while (list) {
1964 int r;
1965 if ((r=config_assign_line(fmt, options, list, use_defaults,
1966 clear_first, msg)))
1967 return r;
1968 list = list->next;
1970 return 0;
1973 /** Try assigning <b>list</b> to the global options. You do this by duping
1974 * options, assigning list to the new one, then validating it. If it's
1975 * ok, then throw out the old one and stick with the new one. Else,
1976 * revert to old and return failure. Return 0 on success, -1 on bad
1977 * keys, -2 on bad values, -3 on bad transition, and -4 on failed-to-set.
1979 * If not success, point *<b>msg</b> to a newly allocated string describing
1980 * what went wrong.
1983 options_trial_assign(config_line_t *list, int use_defaults,
1984 int clear_first, char **msg)
1986 int r;
1987 or_options_t *trial_options = options_dup(&options_format, get_options());
1989 if ((r=config_assign(&options_format, trial_options,
1990 list, use_defaults, clear_first, msg)) < 0) {
1991 config_free(&options_format, trial_options);
1992 return r;
1995 if (options_validate(get_options(), trial_options, 1, msg) < 0) {
1996 config_free(&options_format, trial_options);
1997 return -2;
2000 if (options_transition_allowed(get_options(), trial_options, msg) < 0) {
2001 config_free(&options_format, trial_options);
2002 return -3;
2005 if (set_options(trial_options, msg)<0) {
2006 config_free(&options_format, trial_options);
2007 return -4;
2010 /* we liked it. put it in place. */
2011 return 0;
2014 /** Reset config option <b>var</b> to 0, 0.0, NULL, or the equivalent.
2015 * Called from option_reset() and config_free(). */
2016 static void
2017 option_clear(config_format_t *fmt, or_options_t *options, config_var_t *var)
2019 void *lvalue = STRUCT_VAR_P(options, var->var_offset);
2020 (void)fmt; /* unused */
2021 switch (var->type) {
2022 case CONFIG_TYPE_STRING:
2023 tor_free(*(char**)lvalue);
2024 break;
2025 case CONFIG_TYPE_DOUBLE:
2026 *(double*)lvalue = 0.0;
2027 break;
2028 case CONFIG_TYPE_ISOTIME:
2029 *(time_t*)lvalue = 0;
2030 case CONFIG_TYPE_INTERVAL:
2031 case CONFIG_TYPE_UINT:
2032 case CONFIG_TYPE_BOOL:
2033 *(int*)lvalue = 0;
2034 break;
2035 case CONFIG_TYPE_MEMUNIT:
2036 *(uint64_t*)lvalue = 0;
2037 break;
2038 case CONFIG_TYPE_CSV:
2039 if (*(smartlist_t**)lvalue) {
2040 SMARTLIST_FOREACH(*(smartlist_t **)lvalue, char *, cp, tor_free(cp));
2041 smartlist_free(*(smartlist_t **)lvalue);
2042 *(smartlist_t **)lvalue = NULL;
2044 break;
2045 case CONFIG_TYPE_LINELIST:
2046 case CONFIG_TYPE_LINELIST_S:
2047 config_free_lines(*(config_line_t **)lvalue);
2048 *(config_line_t **)lvalue = NULL;
2049 break;
2050 case CONFIG_TYPE_LINELIST_V:
2051 /* handled by linelist_s. */
2052 break;
2053 case CONFIG_TYPE_OBSOLETE:
2054 break;
2058 /** Clear the option indexed by <b>var</b> in <b>options</b>. Then if
2059 * <b>use_defaults</b>, set it to its default value.
2060 * Called by config_init() and option_reset_line() and option_assign_line(). */
2061 static void
2062 option_reset(config_format_t *fmt, or_options_t *options,
2063 config_var_t *var, int use_defaults)
2065 config_line_t *c;
2066 char *msg = NULL;
2067 CHECK(fmt, options);
2068 option_clear(fmt, options, var); /* clear it first */
2069 if (!use_defaults)
2070 return; /* all done */
2071 if (var->initvalue) {
2072 c = tor_malloc_zero(sizeof(config_line_t));
2073 c->key = tor_strdup(var->name);
2074 c->value = tor_strdup(var->initvalue);
2075 if (config_assign_value(fmt, options, c, &msg) < 0) {
2076 log_warn(LD_BUG, "Failed to assign default: %s", msg);
2077 tor_free(msg); /* if this happens it's a bug */
2079 config_free_lines(c);
2083 /** Print a usage message for tor. */
2084 static void
2085 print_usage(void)
2087 printf(
2088 "Copyright (c) 2001-2004, Roger Dingledine\n"
2089 "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
2090 "Copyright (c) 2007-2008, The Tor Project, Inc.\n\n"
2091 "tor -f <torrc> [args]\n"
2092 "See man page for options, or https://www.torproject.org/ for "
2093 "documentation.\n");
2096 /** Print all non-obsolete torrc options. */
2097 static void
2098 list_torrc_options(void)
2100 int i;
2101 smartlist_t *lines = smartlist_create();
2102 for (i = 0; _option_vars[i].name; ++i) {
2103 config_var_t *var = &_option_vars[i];
2104 const char *desc;
2105 if (var->type == CONFIG_TYPE_OBSOLETE ||
2106 var->type == CONFIG_TYPE_LINELIST_V)
2107 continue;
2108 desc = config_find_description(&options_format, var->name);
2109 printf("%s\n", var->name);
2110 if (desc) {
2111 wrap_string(lines, desc, 76, " ", " ");
2112 SMARTLIST_FOREACH(lines, char *, cp, {
2113 printf("%s", cp);
2114 tor_free(cp);
2116 smartlist_clear(lines);
2119 smartlist_free(lines);
2122 /** Last value actually set by resolve_my_address. */
2123 static uint32_t last_resolved_addr = 0;
2125 * Based on <b>options-\>Address</b>, guess our public IP address and put it
2126 * (in host order) into *<b>addr_out</b>. If <b>hostname_out</b> is provided,
2127 * set *<b>hostname_out</b> to a new string holding the hostname we used to
2128 * get the address. Return 0 if all is well, or -1 if we can't find a suitable
2129 * public IP address.
2132 resolve_my_address(int warn_severity, or_options_t *options,
2133 uint32_t *addr_out, char **hostname_out)
2135 struct in_addr in;
2136 struct hostent *rent;
2137 char hostname[256];
2138 int explicit_ip=1;
2139 int explicit_hostname=1;
2140 int from_interface=0;
2141 char tmpbuf[INET_NTOA_BUF_LEN];
2142 const char *address = options->Address;
2143 int notice_severity = warn_severity <= LOG_NOTICE ?
2144 LOG_NOTICE : warn_severity;
2146 tor_assert(addr_out);
2148 if (address && *address) {
2149 strlcpy(hostname, address, sizeof(hostname));
2150 } else { /* then we need to guess our address */
2151 explicit_ip = 0; /* it's implicit */
2152 explicit_hostname = 0; /* it's implicit */
2154 if (gethostname(hostname, sizeof(hostname)) < 0) {
2155 log_fn(warn_severity, LD_NET,"Error obtaining local hostname");
2156 return -1;
2158 log_debug(LD_CONFIG,"Guessed local host name as '%s'",hostname);
2161 /* now we know hostname. resolve it and keep only the IP address */
2163 if (tor_inet_aton(hostname, &in) == 0) {
2164 /* then we have to resolve it */
2165 explicit_ip = 0;
2166 rent = (struct hostent *)gethostbyname(hostname);
2167 if (!rent) {
2168 uint32_t interface_ip;
2170 if (explicit_hostname) {
2171 log_fn(warn_severity, LD_CONFIG,
2172 "Could not resolve local Address '%s'. Failing.", hostname);
2173 return -1;
2175 log_fn(notice_severity, LD_CONFIG,
2176 "Could not resolve guessed local hostname '%s'. "
2177 "Trying something else.", hostname);
2178 if (get_interface_address(warn_severity, &interface_ip)) {
2179 log_fn(warn_severity, LD_CONFIG,
2180 "Could not get local interface IP address. Failing.");
2181 return -1;
2183 from_interface = 1;
2184 in.s_addr = htonl(interface_ip);
2185 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2186 log_fn(notice_severity, LD_CONFIG, "Learned IP address '%s' for "
2187 "local interface. Using that.", tmpbuf);
2188 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2189 } else {
2190 tor_assert(rent->h_length == 4);
2191 memcpy(&in.s_addr, rent->h_addr, rent->h_length);
2193 if (!explicit_hostname &&
2194 is_internal_IP(ntohl(in.s_addr), 0)) {
2195 uint32_t interface_ip;
2197 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2198 log_fn(notice_severity, LD_CONFIG, "Guessed local hostname '%s' "
2199 "resolves to a private IP address (%s). Trying something "
2200 "else.", hostname, tmpbuf);
2202 if (get_interface_address(warn_severity, &interface_ip)) {
2203 log_fn(warn_severity, LD_CONFIG,
2204 "Could not get local interface IP address. Too bad.");
2205 } else if (is_internal_IP(interface_ip, 0)) {
2206 struct in_addr in2;
2207 in2.s_addr = htonl(interface_ip);
2208 tor_inet_ntoa(&in2,tmpbuf,sizeof(tmpbuf));
2209 log_fn(notice_severity, LD_CONFIG,
2210 "Interface IP address '%s' is a private address too. "
2211 "Ignoring.", tmpbuf);
2212 } else {
2213 from_interface = 1;
2214 in.s_addr = htonl(interface_ip);
2215 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2216 log_fn(notice_severity, LD_CONFIG,
2217 "Learned IP address '%s' for local interface."
2218 " Using that.", tmpbuf);
2219 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2225 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2226 if (is_internal_IP(ntohl(in.s_addr), 0) &&
2227 options->_PublishServerDescriptor) {
2228 /* make sure we're ok with publishing an internal IP */
2229 if (!options->DirServers && !options->AlternateDirAuthority) {
2230 /* if they are using the default dirservers, disallow internal IPs
2231 * always. */
2232 log_fn(warn_severity, LD_CONFIG,
2233 "Address '%s' resolves to private IP address '%s'. "
2234 "Tor servers that use the default DirServers must have public "
2235 "IP addresses.", hostname, tmpbuf);
2236 return -1;
2238 if (!explicit_ip) {
2239 /* even if they've set their own dirservers, require an explicit IP if
2240 * they're using an internal address. */
2241 log_fn(warn_severity, LD_CONFIG, "Address '%s' resolves to private "
2242 "IP address '%s'. Please set the Address config option to be "
2243 "the IP address you want to use.", hostname, tmpbuf);
2244 return -1;
2248 log_debug(LD_CONFIG, "Resolved Address to '%s'.", tmpbuf);
2249 *addr_out = ntohl(in.s_addr);
2250 if (last_resolved_addr && last_resolved_addr != *addr_out) {
2251 /* Leave this as a notice, regardless of the requested severity,
2252 * at least until dynamic IP address support becomes bulletproof. */
2253 log_notice(LD_NET,
2254 "Your IP address seems to have changed to %s. Updating.",
2255 tmpbuf);
2256 ip_address_changed(0);
2258 if (last_resolved_addr != *addr_out) {
2259 const char *method;
2260 const char *h = hostname;
2261 if (explicit_ip) {
2262 method = "CONFIGURED";
2263 h = NULL;
2264 } else if (explicit_hostname) {
2265 method = "RESOLVED";
2266 } else if (from_interface) {
2267 method = "INTERFACE";
2268 h = NULL;
2269 } else {
2270 method = "GETHOSTNAME";
2272 control_event_server_status(LOG_NOTICE,
2273 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s %s%s",
2274 tmpbuf, method, h?"HOSTNAME=":"", h);
2276 last_resolved_addr = *addr_out;
2277 if (hostname_out)
2278 *hostname_out = tor_strdup(hostname);
2279 return 0;
2282 /** Return true iff <b>ip</b> (in host order) is judged to be on the
2283 * same network as us, or on a private network.
2286 is_local_IP(uint32_t ip)
2288 if (is_internal_IP(ip, 0))
2289 return 1;
2290 /* Check whether ip is on the same /24 as we are. */
2291 if (get_options()->EnforceDistinctSubnets == 0)
2292 return 0;
2293 /* It's possible that this next check will hit before the first time
2294 * resolve_my_address actually succeeds. (For clients, it is likely that
2295 * resolve_my_address will never be called at all). In those cases,
2296 * last_resolved_addr will be 0, and so checking to see whether ip is on the
2297 * same /24 as last_resolved_addr will be the same as checking whether it
2298 * was on net 0, which is already done by is_internal_IP.
2300 if ((last_resolved_addr & 0xffffff00ul) == (ip & 0xffffff00ul))
2301 return 1;
2302 return 0;
2305 /** Called when we don't have a nickname set. Try to guess a good nickname
2306 * based on the hostname, and return it in a newly allocated string. If we
2307 * can't, return NULL and let the caller warn if it wants to. */
2308 static char *
2309 get_default_nickname(void)
2311 static const char * const bad_default_nicknames[] = {
2312 "localhost",
2313 NULL,
2315 char localhostname[256];
2316 char *cp, *out, *outp;
2317 int i;
2319 if (gethostname(localhostname, sizeof(localhostname)) < 0)
2320 return NULL;
2322 /* Put it in lowercase; stop at the first dot. */
2323 if ((cp = strchr(localhostname, '.')))
2324 *cp = '\0';
2325 tor_strlower(localhostname);
2327 /* Strip invalid characters. */
2328 cp = localhostname;
2329 out = outp = tor_malloc(strlen(localhostname) + 1);
2330 while (*cp) {
2331 if (strchr(LEGAL_NICKNAME_CHARACTERS, *cp))
2332 *outp++ = *cp++;
2333 else
2334 cp++;
2336 *outp = '\0';
2338 /* Enforce length. */
2339 if (strlen(out) > MAX_NICKNAME_LEN)
2340 out[MAX_NICKNAME_LEN]='\0';
2342 /* Check for dumb names. */
2343 for (i = 0; bad_default_nicknames[i]; ++i) {
2344 if (!strcmp(out, bad_default_nicknames[i])) {
2345 tor_free(out);
2346 return NULL;
2350 return out;
2353 /** Release storage held by <b>options</b>. */
2354 static void
2355 config_free(config_format_t *fmt, void *options)
2357 int i;
2359 tor_assert(options);
2361 for (i=0; fmt->vars[i].name; ++i)
2362 option_clear(fmt, options, &(fmt->vars[i]));
2363 if (fmt->extra) {
2364 config_line_t **linep = STRUCT_VAR_P(options, fmt->extra->var_offset);
2365 config_free_lines(*linep);
2366 *linep = NULL;
2368 tor_free(options);
2371 /** Return true iff a and b contain identical keys and values in identical
2372 * order. */
2373 static int
2374 config_lines_eq(config_line_t *a, config_line_t *b)
2376 while (a && b) {
2377 if (strcasecmp(a->key, b->key) || strcmp(a->value, b->value))
2378 return 0;
2379 a = a->next;
2380 b = b->next;
2382 if (a || b)
2383 return 0;
2384 return 1;
2387 /** Return true iff the option <b>name</b> has the same value in <b>o1</b>
2388 * and <b>o2</b>. Must not be called for LINELIST_S or OBSOLETE options.
2390 static int
2391 option_is_same(config_format_t *fmt,
2392 or_options_t *o1, or_options_t *o2, const char *name)
2394 config_line_t *c1, *c2;
2395 int r = 1;
2396 CHECK(fmt, o1);
2397 CHECK(fmt, o2);
2399 c1 = get_assigned_option(fmt, o1, name, 0);
2400 c2 = get_assigned_option(fmt, o2, name, 0);
2401 r = config_lines_eq(c1, c2);
2402 config_free_lines(c1);
2403 config_free_lines(c2);
2404 return r;
2407 /** Copy storage held by <b>old</b> into a new or_options_t and return it. */
2408 static or_options_t *
2409 options_dup(config_format_t *fmt, or_options_t *old)
2411 or_options_t *newopts;
2412 int i;
2413 config_line_t *line;
2415 newopts = config_alloc(fmt);
2416 for (i=0; fmt->vars[i].name; ++i) {
2417 if (fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
2418 continue;
2419 if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE)
2420 continue;
2421 line = get_assigned_option(fmt, old, fmt->vars[i].name, 0);
2422 if (line) {
2423 char *msg = NULL;
2424 if (config_assign(fmt, newopts, line, 0, 0, &msg) < 0) {
2425 log_err(LD_BUG, "Config_get_assigned_option() generated "
2426 "something we couldn't config_assign(): %s", msg);
2427 tor_free(msg);
2428 tor_assert(0);
2431 config_free_lines(line);
2433 return newopts;
2436 /** Return a new empty or_options_t. Used for testing. */
2437 or_options_t *
2438 options_new(void)
2440 return config_alloc(&options_format);
2443 /** Set <b>options</b> to hold reasonable defaults for most options.
2444 * Each option defaults to zero. */
2445 void
2446 options_init(or_options_t *options)
2448 config_init(&options_format, options);
2451 /** Set all vars in the configuration object <b>options</b> to their default
2452 * values. */
2453 static void
2454 config_init(config_format_t *fmt, void *options)
2456 int i;
2457 config_var_t *var;
2458 CHECK(fmt, options);
2460 for (i=0; fmt->vars[i].name; ++i) {
2461 var = &fmt->vars[i];
2462 if (!var->initvalue)
2463 continue; /* defaults to NULL or 0 */
2464 option_reset(fmt, options, var, 1);
2468 /** Allocate and return a new string holding the written-out values of the vars
2469 * in 'options'. If 'minimal', do not write out any default-valued vars.
2470 * Else, if comment_defaults, write default values as comments.
2472 static char *
2473 config_dump(config_format_t *fmt, void *options, int minimal,
2474 int comment_defaults)
2476 smartlist_t *elements;
2477 or_options_t *defaults;
2478 config_line_t *line, *assigned;
2479 char *result;
2480 int i;
2481 const char *desc;
2482 char *msg = NULL;
2484 defaults = config_alloc(fmt);
2485 config_init(fmt, defaults);
2487 /* XXX use a 1 here so we don't add a new log line while dumping */
2488 if (fmt->validate_fn(NULL,defaults, 1, &msg) < 0) {
2489 log_err(LD_BUG, "Failed to validate default config.");
2490 tor_free(msg);
2491 tor_assert(0);
2494 elements = smartlist_create();
2495 for (i=0; fmt->vars[i].name; ++i) {
2496 int comment_option = 0;
2497 if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE ||
2498 fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
2499 continue;
2500 /* Don't save 'hidden' control variables. */
2501 if (!strcmpstart(fmt->vars[i].name, "__"))
2502 continue;
2503 if (minimal && option_is_same(fmt, options, defaults, fmt->vars[i].name))
2504 continue;
2505 else if (comment_defaults &&
2506 option_is_same(fmt, options, defaults, fmt->vars[i].name))
2507 comment_option = 1;
2509 desc = config_find_description(fmt, fmt->vars[i].name);
2510 line = assigned = get_assigned_option(fmt, options, fmt->vars[i].name, 1);
2512 if (line && desc) {
2513 /* Only dump the description if there's something to describe. */
2514 wrap_string(elements, desc, 78, "# ", "# ");
2517 for (; line; line = line->next) {
2518 size_t len = strlen(line->key) + strlen(line->value) + 5;
2519 char *tmp;
2520 tmp = tor_malloc(len);
2521 if (tor_snprintf(tmp, len, "%s%s %s\n",
2522 comment_option ? "# " : "",
2523 line->key, line->value)<0) {
2524 log_err(LD_BUG,"Internal error writing option value");
2525 tor_assert(0);
2527 smartlist_add(elements, tmp);
2529 config_free_lines(assigned);
2532 if (fmt->extra) {
2533 line = *(config_line_t**)STRUCT_VAR_P(options, fmt->extra->var_offset);
2534 for (; line; line = line->next) {
2535 size_t len = strlen(line->key) + strlen(line->value) + 3;
2536 char *tmp;
2537 tmp = tor_malloc(len);
2538 if (tor_snprintf(tmp, len, "%s %s\n", line->key, line->value)<0) {
2539 log_err(LD_BUG,"Internal error writing option value");
2540 tor_assert(0);
2542 smartlist_add(elements, tmp);
2546 result = smartlist_join_strings(elements, "", 0, NULL);
2547 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
2548 smartlist_free(elements);
2549 config_free(fmt, defaults);
2550 return result;
2553 /** Return a string containing a possible configuration file that would give
2554 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
2555 * include options that are the same as Tor's defaults.
2557 static char *
2558 options_dump(or_options_t *options, int minimal)
2560 return config_dump(&options_format, options, minimal, 0);
2563 /** Return 0 if every element of sl is a string holding a decimal
2564 * representation of a port number, or if sl is NULL.
2565 * Otherwise set *msg and return -1. */
2566 static int
2567 validate_ports_csv(smartlist_t *sl, const char *name, char **msg)
2569 int i;
2570 char buf[1024];
2571 tor_assert(name);
2573 if (!sl)
2574 return 0;
2576 SMARTLIST_FOREACH(sl, const char *, cp,
2578 i = atoi(cp);
2579 if (i < 1 || i > 65535) {
2580 int r = tor_snprintf(buf, sizeof(buf),
2581 "Port '%s' out of range in %s", cp, name);
2582 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2583 return -1;
2586 return 0;
2589 /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
2590 * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
2591 * Else return 0.
2593 static int
2594 ensure_bandwidth_cap(uint64_t *value, const char *desc, char **msg)
2596 int r;
2597 char buf[1024];
2598 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2599 /* This handles an understandable special case where somebody says "2gb"
2600 * whereas our actual maximum is 2gb-1 (INT_MAX) */
2601 --*value;
2603 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2604 r = tor_snprintf(buf, sizeof(buf), "%s ("U64_FORMAT") must be at most %d",
2605 desc, U64_PRINTF_ARG(*value),
2606 ROUTER_MAX_DECLARED_BANDWIDTH);
2607 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2608 return -1;
2610 return 0;
2613 /** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
2614 * and write it to <b>options</b>-\>_PublishServerDescriptor. Treat "1"
2615 * as "v2,v3" unless BridgeRelay is 1, in which case treat it as "bridge".
2616 * Treat "0" as "".
2617 * Return 0 on success or -1 if not a recognized authority type (in which
2618 * case the value of _PublishServerDescriptor is undefined). */
2619 static int
2620 compute_publishserverdescriptor(or_options_t *options)
2622 smartlist_t *list = options->PublishServerDescriptor;
2623 authority_type_t *auth = &options->_PublishServerDescriptor;
2624 *auth = NO_AUTHORITY;
2625 if (!list) /* empty list, answer is none */
2626 return 0;
2627 SMARTLIST_FOREACH(list, const char *, string, {
2628 if (!strcasecmp(string, "v1"))
2629 *auth |= V1_AUTHORITY;
2630 else if (!strcmp(string, "1"))
2631 if (options->BridgeRelay)
2632 *auth |= BRIDGE_AUTHORITY;
2633 else
2634 *auth |= V2_AUTHORITY | V3_AUTHORITY;
2635 else if (!strcasecmp(string, "v2"))
2636 *auth |= V2_AUTHORITY;
2637 else if (!strcasecmp(string, "v3"))
2638 *auth |= V3_AUTHORITY;
2639 else if (!strcasecmp(string, "bridge"))
2640 *auth |= BRIDGE_AUTHORITY;
2641 else if (!strcasecmp(string, "hidserv"))
2642 *auth |= HIDSERV_AUTHORITY;
2643 else if (!strcasecmp(string, "") || !strcmp(string, "0"))
2644 /* no authority */;
2645 else
2646 return -1;
2648 return 0;
2651 /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
2652 * services can overload the directory system. */
2653 #define MIN_REND_POST_PERIOD (10*60)
2655 /** Highest allowable value for RendPostPeriod. */
2656 #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
2658 /** Return 0 if every setting in <b>options</b> is reasonable, and a
2659 * permissible transition from <b>old_options</b>. Else return -1.
2660 * Should have no side effects, except for normalizing the contents of
2661 * <b>options</b>.
2663 * On error, tor_strdup an error explanation into *<b>msg</b>.
2665 * XXX
2666 * If <b>from_setconf</b>, we were called by the controller, and our
2667 * Log line should stay empty. If it's 0, then give us a default log
2668 * if there are no logs defined.
2670 static int
2671 options_validate(or_options_t *old_options, or_options_t *options,
2672 int from_setconf, char **msg)
2674 int i, r;
2675 config_line_t *cl;
2676 const char *uname = get_uname();
2677 char buf[1024];
2678 #define REJECT(arg) \
2679 STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
2680 #define COMPLAIN(arg) STMT_BEGIN log(LOG_WARN, LD_CONFIG, arg); STMT_END
2682 tor_assert(msg);
2683 *msg = NULL;
2685 if (options->ORPort < 0 || options->ORPort > 65535)
2686 REJECT("ORPort option out of bounds.");
2688 if (server_mode(options) &&
2689 (!strcmpstart(uname, "Windows 95") ||
2690 !strcmpstart(uname, "Windows 98") ||
2691 !strcmpstart(uname, "Windows Me"))) {
2692 log(LOG_WARN, LD_CONFIG, "Tor is running as a server, but you are "
2693 "running %s; this probably won't work. See "
2694 "http://wiki.noreply.org/noreply/TheOnionRouter/TorFAQ#ServerOS "
2695 "for details.", uname);
2698 if (options->ORPort == 0 && options->ORListenAddress != NULL)
2699 REJECT("ORPort must be defined if ORListenAddress is defined.");
2701 if (options->DirPort == 0 && options->DirListenAddress != NULL)
2702 REJECT("DirPort must be defined if DirListenAddress is defined.");
2704 if (options->DNSPort == 0 && options->DNSListenAddress != NULL)
2705 REJECT("DNSPort must be defined if DNSListenAddress is defined.");
2707 if (options->ControlPort == 0 && options->ControlListenAddress != NULL)
2708 REJECT("ControlPort must be defined if ControlListenAddress is defined.");
2710 if (options->TransPort == 0 && options->TransListenAddress != NULL)
2711 REJECT("TransPort must be defined if TransListenAddress is defined.");
2713 if (options->NatdPort == 0 && options->NatdListenAddress != NULL)
2714 REJECT("NatdPort must be defined if NatdListenAddress is defined.");
2716 /* Don't gripe about SocksPort 0 with SocksListenAddress set; a standard
2717 * configuration does this. */
2719 for (i = 0; i < 3; ++i) {
2720 int is_socks = i==0;
2721 int is_trans = i==1;
2722 config_line_t *line, *opt, *old;
2723 const char *tp;
2724 if (is_socks) {
2725 opt = options->SocksListenAddress;
2726 old = old_options ? old_options->SocksListenAddress : NULL;
2727 tp = "SOCKS proxy";
2728 } else if (is_trans) {
2729 opt = options->TransListenAddress;
2730 old = old_options ? old_options->TransListenAddress : NULL;
2731 tp = "transparent proxy";
2732 } else {
2733 opt = options->NatdListenAddress;
2734 old = old_options ? old_options->NatdListenAddress : NULL;
2735 tp = "natd proxy";
2738 for (line = opt; line; line = line->next) {
2739 char *address = NULL;
2740 uint16_t port;
2741 uint32_t addr;
2742 if (parse_addr_port(LOG_WARN, line->value, &address, &addr, &port)<0)
2743 continue; /* We'll warn about this later. */
2744 if (!is_internal_IP(addr, 1) &&
2745 (!old_options || !config_lines_eq(old, opt))) {
2746 log_warn(LD_CONFIG,
2747 "You specified a public address '%s' for a %s. Other "
2748 "people on the Internet might find your computer and use it as "
2749 "an open %s. Please don't allow this unless you have "
2750 "a good reason.", address, tp, tp);
2752 tor_free(address);
2756 if (validate_data_directory(options)<0)
2757 REJECT("Invalid DataDirectory");
2759 if (options->Nickname == NULL) {
2760 if (server_mode(options)) {
2761 if (!(options->Nickname = get_default_nickname())) {
2762 log_notice(LD_CONFIG, "Couldn't pick a nickname based on "
2763 "our hostname; using %s instead.", UNNAMED_ROUTER_NICKNAME);
2764 options->Nickname = tor_strdup(UNNAMED_ROUTER_NICKNAME);
2765 } else {
2766 log_notice(LD_CONFIG, "Choosing default nickname '%s'",
2767 options->Nickname);
2770 } else {
2771 if (!is_legal_nickname(options->Nickname)) {
2772 r = tor_snprintf(buf, sizeof(buf),
2773 "Nickname '%s' is wrong length or contains illegal characters.",
2774 options->Nickname);
2775 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2776 return -1;
2780 if (server_mode(options) && !options->ContactInfo)
2781 log(LOG_NOTICE, LD_CONFIG, "Your ContactInfo config option is not set. "
2782 "Please consider setting it, so we can contact you if your server is "
2783 "misconfigured or something else goes wrong.");
2785 /* Special case on first boot if no Log options are given. */
2786 if (!options->Logs && !options->RunAsDaemon && !from_setconf)
2787 config_line_append(&options->Logs, "Log", "notice stdout");
2789 if (options_init_logs(options, 1)<0) /* Validate the log(s) */
2790 REJECT("Failed to validate Log options. See logs for details.");
2792 if (options->NoPublish) {
2793 log(LOG_WARN, LD_CONFIG,
2794 "NoPublish is obsolete. Use PublishServerDescriptor instead.");
2795 SMARTLIST_FOREACH(options->PublishServerDescriptor, char *, s,
2796 tor_free(s));
2797 smartlist_clear(options->PublishServerDescriptor);
2800 if (authdir_mode(options)) {
2801 /* confirm that our address isn't broken, so we can complain now */
2802 uint32_t tmp;
2803 if (resolve_my_address(LOG_WARN, options, &tmp, NULL) < 0)
2804 REJECT("Failed to resolve/guess local address. See logs for details.");
2807 #ifndef MS_WINDOWS
2808 if (options->RunAsDaemon && torrc_fname && path_is_relative(torrc_fname))
2809 REJECT("Can't use a relative path to torrc when RunAsDaemon is set.");
2810 #endif
2812 if (options->SocksPort < 0 || options->SocksPort > 65535)
2813 REJECT("SocksPort option out of bounds.");
2815 if (options->DNSPort < 0 || options->DNSPort > 65535)
2816 REJECT("DNSPort option out of bounds.");
2818 if (options->TransPort < 0 || options->TransPort > 65535)
2819 REJECT("TransPort option out of bounds.");
2821 if (options->NatdPort < 0 || options->NatdPort > 65535)
2822 REJECT("NatdPort option out of bounds.");
2824 if (options->SocksPort == 0 && options->TransPort == 0 &&
2825 options->NatdPort == 0 && options->ORPort == 0 &&
2826 options->DNSPort == 0 && !options->RendConfigLines)
2827 log(LOG_WARN, LD_CONFIG,
2828 "SocksPort, TransPort, NatdPort, DNSPort, and ORPort are all "
2829 "undefined, and there aren't any hidden services configured. "
2830 "Tor will still run, but probably won't do anything.");
2832 if (options->ControlPort < 0 || options->ControlPort > 65535)
2833 REJECT("ControlPort option out of bounds.");
2835 if (options->DirPort < 0 || options->DirPort > 65535)
2836 REJECT("DirPort option out of bounds.");
2838 #ifndef USE_TRANSPARENT
2839 if (options->TransPort || options->TransListenAddress)
2840 REJECT("TransPort and TransListenAddress are disabled in this build.");
2841 #endif
2843 if (options->StrictExitNodes &&
2844 (!options->ExitNodes || !strlen(options->ExitNodes)) &&
2845 (!old_options ||
2846 (old_options->StrictExitNodes != options->StrictExitNodes) ||
2847 (!opt_streq(old_options->ExitNodes, options->ExitNodes))))
2848 COMPLAIN("StrictExitNodes set, but no ExitNodes listed.");
2850 if (options->StrictEntryNodes &&
2851 (!options->EntryNodes || !strlen(options->EntryNodes)) &&
2852 (!old_options ||
2853 (old_options->StrictEntryNodes != options->StrictEntryNodes) ||
2854 (!opt_streq(old_options->EntryNodes, options->EntryNodes))))
2855 COMPLAIN("StrictEntryNodes set, but no EntryNodes listed.");
2857 if (options->AuthoritativeDir) {
2858 if (!options->ContactInfo)
2859 REJECT("Authoritative directory servers must set ContactInfo");
2860 if (options->V1AuthoritativeDir && !options->RecommendedVersions)
2861 REJECT("V1 auth dir servers must set RecommendedVersions.");
2862 if (!options->RecommendedClientVersions)
2863 options->RecommendedClientVersions =
2864 config_lines_dup(options->RecommendedVersions);
2865 if (!options->RecommendedServerVersions)
2866 options->RecommendedServerVersions =
2867 config_lines_dup(options->RecommendedVersions);
2868 if (options->VersioningAuthoritativeDir &&
2869 (!options->RecommendedClientVersions ||
2870 !options->RecommendedServerVersions))
2871 REJECT("Versioning auth dir servers must set Recommended*Versions.");
2872 if (options->UseEntryGuards) {
2873 log_info(LD_CONFIG, "Authoritative directory servers can't set "
2874 "UseEntryGuards. Disabling.");
2875 options->UseEntryGuards = 0;
2877 if (!options->DownloadExtraInfo && authdir_mode_any_main(options)) {
2878 log_info(LD_CONFIG, "Authoritative directories always try to download "
2879 "extra-info documents. Setting DownloadExtraInfo.");
2880 options->DownloadExtraInfo = 1;
2882 if (!(options->BridgeAuthoritativeDir || options->HSAuthoritativeDir ||
2883 options->V1AuthoritativeDir || options->V2AuthoritativeDir ||
2884 options->V3AuthoritativeDir))
2885 REJECT("AuthoritativeDir is set, but none of "
2886 "(Bridge/HS/V1/V2/V3)AuthoritativeDir is set.");
2889 if (options->AuthoritativeDir && !options->DirPort)
2890 REJECT("Running as authoritative directory, but no DirPort set.");
2892 if (options->AuthoritativeDir && !options->ORPort)
2893 REJECT("Running as authoritative directory, but no ORPort set.");
2895 if (options->AuthoritativeDir && options->ClientOnly)
2896 REJECT("Running as authoritative directory, but ClientOnly also set.");
2898 if (options->HSAuthorityRecordStats && !options->HSAuthoritativeDir)
2899 REJECT("HSAuthorityRecordStats is set but we're not running as "
2900 "a hidden service authority.");
2902 if (options->HidServDirectoryV2 && !options->DirPort)
2903 REJECT("Running as hidden service directory, but no DirPort set.");
2905 if (options->ConnLimit <= 0) {
2906 r = tor_snprintf(buf, sizeof(buf),
2907 "ConnLimit must be greater than 0, but was set to %d",
2908 options->ConnLimit);
2909 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2910 return -1;
2913 if (validate_ports_csv(options->FirewallPorts, "FirewallPorts", msg) < 0)
2914 return -1;
2916 if (validate_ports_csv(options->LongLivedPorts, "LongLivedPorts", msg) < 0)
2917 return -1;
2919 if (validate_ports_csv(options->RejectPlaintextPorts,
2920 "RejectPlaintextPorts", msg) < 0)
2921 return -1;
2923 if (validate_ports_csv(options->WarnPlaintextPorts,
2924 "WarnPlaintextPorts", msg) < 0)
2925 return -1;
2927 if (options->FascistFirewall && !options->ReachableAddresses) {
2928 if (options->FirewallPorts && smartlist_len(options->FirewallPorts)) {
2929 /* We already have firewall ports set, so migrate them to
2930 * ReachableAddresses, which will set ReachableORAddresses and
2931 * ReachableDirAddresses if they aren't set explicitly. */
2932 smartlist_t *instead = smartlist_create();
2933 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
2934 new_line->key = tor_strdup("ReachableAddresses");
2935 /* If we're configured with the old format, we need to prepend some
2936 * open ports. */
2937 SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
2939 int p = atoi(portno);
2940 char *s;
2941 if (p<0) continue;
2942 s = tor_malloc(16);
2943 tor_snprintf(s, 16, "*:%d", p);
2944 smartlist_add(instead, s);
2946 new_line->value = smartlist_join_strings(instead,",",0,NULL);
2947 /* These have been deprecated since 0.1.1.5-alpha-cvs */
2948 log(LOG_NOTICE, LD_CONFIG,
2949 "Converting FascistFirewall and FirewallPorts "
2950 "config options to new format: \"ReachableAddresses %s\"",
2951 new_line->value);
2952 options->ReachableAddresses = new_line;
2953 SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
2954 smartlist_free(instead);
2955 } else {
2956 /* We do not have FirewallPorts set, so add 80 to
2957 * ReachableDirAddresses, and 443 to ReachableORAddresses. */
2958 if (!options->ReachableDirAddresses) {
2959 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
2960 new_line->key = tor_strdup("ReachableDirAddresses");
2961 new_line->value = tor_strdup("*:80");
2962 options->ReachableDirAddresses = new_line;
2963 log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
2964 "to new format: \"ReachableDirAddresses *:80\"");
2966 if (!options->ReachableORAddresses) {
2967 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
2968 new_line->key = tor_strdup("ReachableORAddresses");
2969 new_line->value = tor_strdup("*:443");
2970 options->ReachableORAddresses = new_line;
2971 log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
2972 "to new format: \"ReachableORAddresses *:443\"");
2977 for (i=0; i<3; i++) {
2978 config_line_t **linep =
2979 (i==0) ? &options->ReachableAddresses :
2980 (i==1) ? &options->ReachableORAddresses :
2981 &options->ReachableDirAddresses;
2982 if (!*linep)
2983 continue;
2984 /* We need to end with a reject *:*, not an implicit accept *:* */
2985 for (;;) {
2986 if (!strcmp((*linep)->value, "reject *:*")) /* already there */
2987 break;
2988 linep = &((*linep)->next);
2989 if (!*linep) {
2990 *linep = tor_malloc_zero(sizeof(config_line_t));
2991 (*linep)->key = tor_strdup(
2992 (i==0) ? "ReachableAddresses" :
2993 (i==1) ? "ReachableORAddresses" :
2994 "ReachableDirAddresses");
2995 (*linep)->value = tor_strdup("reject *:*");
2996 break;
3001 if ((options->ReachableAddresses ||
3002 options->ReachableORAddresses ||
3003 options->ReachableDirAddresses) &&
3004 server_mode(options))
3005 REJECT("Servers must be able to freely connect to the rest "
3006 "of the Internet, so they must not set Reachable*Addresses "
3007 "or FascistFirewall.");
3009 if (options->UseBridges &&
3010 server_mode(options))
3011 REJECT("Servers must be able to freely connect to the rest "
3012 "of the Internet, so they must not set UseBridges.");
3014 options->_AllowInvalid = 0;
3015 if (options->AllowInvalidNodes) {
3016 SMARTLIST_FOREACH(options->AllowInvalidNodes, const char *, cp, {
3017 if (!strcasecmp(cp, "entry"))
3018 options->_AllowInvalid |= ALLOW_INVALID_ENTRY;
3019 else if (!strcasecmp(cp, "exit"))
3020 options->_AllowInvalid |= ALLOW_INVALID_EXIT;
3021 else if (!strcasecmp(cp, "middle"))
3022 options->_AllowInvalid |= ALLOW_INVALID_MIDDLE;
3023 else if (!strcasecmp(cp, "introduction"))
3024 options->_AllowInvalid |= ALLOW_INVALID_INTRODUCTION;
3025 else if (!strcasecmp(cp, "rendezvous"))
3026 options->_AllowInvalid |= ALLOW_INVALID_RENDEZVOUS;
3027 else {
3028 r = tor_snprintf(buf, sizeof(buf),
3029 "Unrecognized value '%s' in AllowInvalidNodes", cp);
3030 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3031 return -1;
3036 if (compute_publishserverdescriptor(options) < 0) {
3037 r = tor_snprintf(buf, sizeof(buf),
3038 "Unrecognized value in PublishServerDescriptor");
3039 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3040 return -1;
3043 if (options->MinUptimeHidServDirectoryV2 < 0) {
3044 log_warn(LD_CONFIG, "MinUptimeHidServDirectoryV2 option must be at "
3045 "least 0 seconds. Changing to 0.");
3046 options->MinUptimeHidServDirectoryV2 = 0;
3049 if (options->RendPostPeriod < MIN_REND_POST_PERIOD) {
3050 log(LOG_WARN,LD_CONFIG,"RendPostPeriod option must be at least %d seconds."
3051 " Clipping.", MIN_REND_POST_PERIOD);
3052 options->RendPostPeriod = MIN_REND_POST_PERIOD;
3055 if (options->RendPostPeriod > MAX_DIR_PERIOD) {
3056 log(LOG_WARN, LD_CONFIG, "RendPostPeriod is too large; clipping to %ds.",
3057 MAX_DIR_PERIOD);
3058 options->RendPostPeriod = MAX_DIR_PERIOD;
3061 if (options->KeepalivePeriod < 1)
3062 REJECT("KeepalivePeriod option must be positive.");
3064 if (ensure_bandwidth_cap(&options->BandwidthRate,
3065 "BandwidthRate", msg) < 0)
3066 return -1;
3067 if (ensure_bandwidth_cap(&options->BandwidthBurst,
3068 "BandwidthBurst", msg) < 0)
3069 return -1;
3070 if (ensure_bandwidth_cap(&options->MaxAdvertisedBandwidth,
3071 "MaxAdvertisedBandwidth", msg) < 0)
3072 return -1;
3073 if (ensure_bandwidth_cap(&options->RelayBandwidthRate,
3074 "RelayBandwidthRate", msg) < 0)
3075 return -1;
3076 if (ensure_bandwidth_cap(&options->RelayBandwidthBurst,
3077 "RelayBandwidthBurst", msg) < 0)
3078 return -1;
3080 if (server_mode(options)) {
3081 if (options->BandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH*2) {
3082 r = tor_snprintf(buf, sizeof(buf),
3083 "BandwidthRate is set to %d bytes/second. "
3084 "For servers, it must be at least %d.",
3085 (int)options->BandwidthRate,
3086 ROUTER_REQUIRED_MIN_BANDWIDTH*2);
3087 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3088 return -1;
3089 } else if (options->MaxAdvertisedBandwidth <
3090 ROUTER_REQUIRED_MIN_BANDWIDTH) {
3091 r = tor_snprintf(buf, sizeof(buf),
3092 "MaxAdvertisedBandwidth is set to %d bytes/second. "
3093 "For servers, it must be at least %d.",
3094 (int)options->MaxAdvertisedBandwidth,
3095 ROUTER_REQUIRED_MIN_BANDWIDTH);
3096 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3097 return -1;
3099 if (options->RelayBandwidthRate &&
3100 options->RelayBandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
3101 r = tor_snprintf(buf, sizeof(buf),
3102 "RelayBandwidthRate is set to %d bytes/second. "
3103 "For servers, it must be at least %d.",
3104 (int)options->RelayBandwidthRate,
3105 ROUTER_REQUIRED_MIN_BANDWIDTH);
3106 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3107 return -1;
3111 if (options->RelayBandwidthRate && !options->RelayBandwidthBurst)
3112 options->RelayBandwidthBurst = options->RelayBandwidthRate;
3114 if (options->RelayBandwidthRate > options->RelayBandwidthBurst)
3115 REJECT("RelayBandwidthBurst must be at least equal "
3116 "to RelayBandwidthRate.");
3118 if (options->BandwidthRate > options->BandwidthBurst)
3119 REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
3121 if (accounting_parse_options(options, 1)<0)
3122 REJECT("Failed to parse accounting options. See logs for details.");
3124 if (options->HttpProxy) { /* parse it now */
3125 if (parse_addr_port(LOG_WARN, options->HttpProxy, NULL,
3126 &options->HttpProxyAddr, &options->HttpProxyPort) < 0)
3127 REJECT("HttpProxy failed to parse or resolve. Please fix.");
3128 if (options->HttpProxyPort == 0) { /* give it a default */
3129 options->HttpProxyPort = 80;
3133 if (options->HttpProxyAuthenticator) {
3134 if (strlen(options->HttpProxyAuthenticator) >= 48)
3135 REJECT("HttpProxyAuthenticator is too long (>= 48 chars).");
3138 if (options->HttpsProxy) { /* parse it now */
3139 if (parse_addr_port(LOG_WARN, options->HttpsProxy, NULL,
3140 &options->HttpsProxyAddr, &options->HttpsProxyPort) <0)
3141 REJECT("HttpsProxy failed to parse or resolve. Please fix.");
3142 if (options->HttpsProxyPort == 0) { /* give it a default */
3143 options->HttpsProxyPort = 443;
3147 if (options->HttpsProxyAuthenticator) {
3148 if (strlen(options->HttpsProxyAuthenticator) >= 48)
3149 REJECT("HttpsProxyAuthenticator is too long (>= 48 chars).");
3152 if (options->HashedControlPassword) {
3153 smartlist_t *sl = decode_hashed_passwords(options->HashedControlPassword);
3154 if (!sl) {
3155 REJECT("Bad HashedControlPassword: wrong length or bad encoding");
3156 } else {
3157 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3158 smartlist_free(sl);
3162 if (options->HashedControlSessionPassword) {
3163 smartlist_t *sl = decode_hashed_passwords(
3164 options->HashedControlSessionPassword);
3165 if (!sl) {
3166 REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
3167 } else {
3168 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3169 smartlist_free(sl);
3173 if (options->ControlListenAddress) {
3174 int all_are_local = 1;
3175 config_line_t *ln;
3176 for (ln = options->ControlListenAddress; ln; ln = ln->next) {
3177 if (strcmpstart(ln->value, "127."))
3178 all_are_local = 0;
3180 if (!all_are_local) {
3181 if (!options->HashedControlPassword &&
3182 !options->HashedControlSessionPassword &&
3183 !options->CookieAuthentication) {
3184 log_warn(LD_CONFIG, "You have a ControlListenAddress set to accept "
3185 "connections from a non-local address. This means that "
3186 "any program on the internet can reconfigure your Tor. "
3187 "That's so bad that I'm closing your ControlPort for you.");
3188 options->ControlPort = 0;
3189 } else {
3190 log_warn(LD_CONFIG, "You have a ControlListenAddress set to accept "
3191 "connections from a non-local address. This means that "
3192 "programs not running on your computer can reconfigure your "
3193 "Tor. That's pretty bad!");
3198 if (options->ControlPort && !options->HashedControlPassword &&
3199 !options->HashedControlSessionPassword &&
3200 !options->CookieAuthentication) {
3201 log_warn(LD_CONFIG, "ControlPort is open, but no authentication method "
3202 "has been configured. This means that any program on your "
3203 "computer can reconfigure your Tor. That's bad! You should "
3204 "upgrade your Tor controller as soon as possible.");
3207 if (options->UseEntryGuards && ! options->NumEntryGuards)
3208 REJECT("Cannot enable UseEntryGuards with NumEntryGuards set to 0");
3210 if (check_nickname_list(options->ExitNodes, "ExitNodes", msg))
3211 return -1;
3212 if (check_nickname_list(options->EntryNodes, "EntryNodes", msg))
3213 return -1;
3214 if (check_nickname_list(options->ExcludeNodes, "ExcludeNodes", msg))
3215 return -1;
3216 if (check_nickname_list(options->RendNodes, "RendNodes", msg))
3217 return -1;
3218 if (check_nickname_list(options->RendNodes, "RendExcludeNodes", msg))
3219 return -1;
3220 if (check_nickname_list(options->TestVia, "TestVia", msg))
3221 return -1;
3222 if (check_nickname_list(options->MyFamily, "MyFamily", msg))
3223 return -1;
3224 for (cl = options->NodeFamilies; cl; cl = cl->next) {
3225 if (check_nickname_list(cl->value, "NodeFamily", msg))
3226 return -1;
3229 if (validate_addr_policies(options, msg) < 0)
3230 return -1;
3232 for (cl = options->RedirectExit; cl; cl = cl->next) {
3233 if (parse_redirect_line(NULL, cl, msg)<0)
3234 return -1;
3237 if (validate_dir_authorities(options, old_options) < 0)
3238 REJECT("Directory authority line did not parse. See logs for details.");
3240 if (options->UseBridges && !options->Bridges)
3241 REJECT("If you set UseBridges, you must specify at least one bridge.");
3242 if (options->UseBridges && !options->TunnelDirConns)
3243 REJECT("If you set UseBridges, you must set TunnelDirConns.");
3244 if (options->Bridges) {
3245 for (cl = options->Bridges; cl; cl = cl->next) {
3246 if (parse_bridge_line(cl->value, 1)<0)
3247 REJECT("Bridge line did not parse. See logs for details.");
3251 if (options->ConstrainedSockets) {
3252 /* If the user wants to constrain socket buffer use, make sure the desired
3253 * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
3254 if (options->ConstrainedSockSize < MIN_CONSTRAINED_TCP_BUFFER ||
3255 options->ConstrainedSockSize > MAX_CONSTRAINED_TCP_BUFFER ||
3256 options->ConstrainedSockSize % 1024) {
3257 r = tor_snprintf(buf, sizeof(buf),
3258 "ConstrainedSockSize is invalid. Must be a value between %d and %d "
3259 "in 1024 byte increments.",
3260 MIN_CONSTRAINED_TCP_BUFFER, MAX_CONSTRAINED_TCP_BUFFER);
3261 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3262 return -1;
3264 if (options->DirPort) {
3265 /* Providing cached directory entries while system TCP buffers are scarce
3266 * will exacerbate the socket errors. Suggest that this be disabled. */
3267 COMPLAIN("You have requested constrained socket buffers while also "
3268 "serving directory entries via DirPort. It is strongly "
3269 "suggested that you disable serving directory requests when "
3270 "system TCP buffer resources are scarce.");
3274 if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
3275 options->V3AuthVotingInterval/2) {
3276 REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
3277 "V3AuthVotingInterval");
3279 if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS)
3280 REJECT("V3AuthVoteDelay is way too low.");
3281 if (options->V3AuthDistDelay < MIN_DIST_SECONDS)
3282 REJECT("V3AuthDistDelay is way too low.");
3284 if (options->V3AuthNIntervalsValid < 2)
3285 REJECT("V3AuthNIntervalsValid must be at least 2.");
3287 if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL) {
3288 REJECT("V3AuthVotingInterval is insanely low.");
3289 } else if (options->V3AuthVotingInterval > 24*60*60) {
3290 REJECT("V3AuthVotingInterval is insanely high.");
3291 } else if (((24*60*60) % options->V3AuthVotingInterval) != 0) {
3292 COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
3295 if (rend_config_services(options, 1) < 0)
3296 REJECT("Failed to configure rendezvous options. See logs for details.");
3298 if (parse_virtual_addr_network(options->VirtualAddrNetwork, 1, NULL)<0)
3299 return -1;
3301 if (options->PreferTunneledDirConns && !options->TunnelDirConns)
3302 REJECT("Must set TunnelDirConns if PreferTunneledDirConns is set.");
3304 if (options->AutomapHostsSuffixes) {
3305 SMARTLIST_FOREACH(options->AutomapHostsSuffixes, char *, suf,
3307 size_t len = strlen(suf);
3308 if (len && suf[len-1] == '.')
3309 suf[len-1] = '\0';
3313 return 0;
3314 #undef REJECT
3315 #undef COMPLAIN
3318 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
3319 * equal strings. */
3320 static int
3321 opt_streq(const char *s1, const char *s2)
3323 if (!s1 && !s2)
3324 return 1;
3325 else if (s1 && s2 && !strcmp(s1,s2))
3326 return 1;
3327 else
3328 return 0;
3331 /** Check if any of the previous options have changed but aren't allowed to. */
3332 static int
3333 options_transition_allowed(or_options_t *old, or_options_t *new_val,
3334 char **msg)
3336 if (!old)
3337 return 0;
3339 if (!opt_streq(old->PidFile, new_val->PidFile)) {
3340 *msg = tor_strdup("PidFile is not allowed to change.");
3341 return -1;
3344 if (old->RunAsDaemon != new_val->RunAsDaemon) {
3345 *msg = tor_strdup("While Tor is running, changing RunAsDaemon "
3346 "is not allowed.");
3347 return -1;
3350 if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
3351 char buf[1024];
3352 int r = tor_snprintf(buf, sizeof(buf),
3353 "While Tor is running, changing DataDirectory "
3354 "(\"%s\"->\"%s\") is not allowed.",
3355 old->DataDirectory, new_val->DataDirectory);
3356 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3357 return -1;
3360 if (!opt_streq(old->User, new_val->User)) {
3361 *msg = tor_strdup("While Tor is running, changing User is not allowed.");
3362 return -1;
3365 if (!opt_streq(old->Group, new_val->Group)) {
3366 *msg = tor_strdup("While Tor is running, changing Group is not allowed.");
3367 return -1;
3370 if (old->HardwareAccel != new_val->HardwareAccel) {
3371 *msg = tor_strdup("While Tor is running, changing HardwareAccel is "
3372 "not allowed.");
3373 return -1;
3376 return 0;
3379 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3380 * will require us to rotate the cpu and dns workers; else return 0. */
3381 static int
3382 options_transition_affects_workers(or_options_t *old_options,
3383 or_options_t *new_options)
3385 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
3386 old_options->NumCpus != new_options->NumCpus ||
3387 old_options->ORPort != new_options->ORPort ||
3388 old_options->ServerDNSSearchDomains !=
3389 new_options->ServerDNSSearchDomains ||
3390 old_options->SafeLogging != new_options->SafeLogging ||
3391 old_options->ClientOnly != new_options->ClientOnly ||
3392 !config_lines_eq(old_options->Logs, new_options->Logs))
3393 return 1;
3395 /* Check whether log options match. */
3397 /* Nothing that changed matters. */
3398 return 0;
3401 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3402 * will require us to generate a new descriptor; else return 0. */
3403 static int
3404 options_transition_affects_descriptor(or_options_t *old_options,
3405 or_options_t *new_options)
3407 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
3408 !opt_streq(old_options->Nickname,new_options->Nickname) ||
3409 !opt_streq(old_options->Address,new_options->Address) ||
3410 !config_lines_eq(old_options->ExitPolicy,new_options->ExitPolicy) ||
3411 old_options->ExitPolicyRejectPrivate !=
3412 new_options->ExitPolicyRejectPrivate ||
3413 old_options->ORPort != new_options->ORPort ||
3414 old_options->DirPort != new_options->DirPort ||
3415 old_options->ClientOnly != new_options->ClientOnly ||
3416 old_options->NoPublish != new_options->NoPublish ||
3417 old_options->_PublishServerDescriptor !=
3418 new_options->_PublishServerDescriptor ||
3419 old_options->BandwidthRate != new_options->BandwidthRate ||
3420 old_options->BandwidthBurst != new_options->BandwidthBurst ||
3421 !opt_streq(old_options->ContactInfo, new_options->ContactInfo) ||
3422 !opt_streq(old_options->MyFamily, new_options->MyFamily) ||
3423 !opt_streq(old_options->AccountingStart, new_options->AccountingStart) ||
3424 old_options->AccountingMax != new_options->AccountingMax)
3425 return 1;
3427 return 0;
3430 #ifdef MS_WINDOWS
3431 /** Return the directory on windows where we expect to find our application
3432 * data. */
3433 static char *
3434 get_windows_conf_root(void)
3436 static int is_set = 0;
3437 static char path[MAX_PATH+1];
3439 LPITEMIDLIST idl;
3440 IMalloc *m;
3441 HRESULT result;
3443 if (is_set)
3444 return path;
3446 /* Find X:\documents and settings\username\application data\ .
3447 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
3449 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, CSIDL_APPDATA,
3450 &idl))) {
3451 GetCurrentDirectory(MAX_PATH, path);
3452 is_set = 1;
3453 log_warn(LD_CONFIG,
3454 "I couldn't find your application data folder: are you "
3455 "running an ancient version of Windows 95? Defaulting to \"%s\"",
3456 path);
3457 return path;
3459 /* Convert the path from an "ID List" (whatever that is!) to a path. */
3460 result = SHGetPathFromIDList(idl, path);
3461 /* Now we need to free the */
3462 SHGetMalloc(&m);
3463 if (m) {
3464 m->lpVtbl->Free(m, idl);
3465 m->lpVtbl->Release(m);
3467 if (!SUCCEEDED(result)) {
3468 return NULL;
3470 strlcat(path,"\\tor",MAX_PATH);
3471 is_set = 1;
3472 return path;
3474 #endif
3476 /** Return the default location for our torrc file. */
3477 static const char *
3478 get_default_conf_file(void)
3480 #ifdef MS_WINDOWS
3481 static char path[MAX_PATH+1];
3482 strlcpy(path, get_windows_conf_root(), MAX_PATH);
3483 strlcat(path,"\\torrc",MAX_PATH);
3484 return path;
3485 #else
3486 return (CONFDIR "/torrc");
3487 #endif
3490 /** Verify whether lst is a string containing valid-looking space-separated
3491 * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
3493 static int
3494 check_nickname_list(const char *lst, const char *name, char **msg)
3496 int r = 0;
3497 smartlist_t *sl;
3499 if (!lst)
3500 return 0;
3501 sl = smartlist_create();
3502 smartlist_split_string(sl, lst, ",", SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
3503 SMARTLIST_FOREACH(sl, const char *, s,
3505 if (!is_legal_nickname_or_hexdigest(s)) {
3506 char buf[1024];
3507 int tmp = tor_snprintf(buf, sizeof(buf),
3508 "Invalid nickname '%s' in %s line", s, name);
3509 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
3510 r = -1;
3511 break;
3514 SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
3515 smartlist_free(sl);
3516 return r;
3519 /** Read a configuration file into <b>options</b>, finding the configuration
3520 * file location based on the command line. After loading the options,
3521 * validate them for consistency, then take actions based on them.
3522 * Return 0 if success, -1 if failure. */
3524 options_init_from_torrc(int argc, char **argv)
3526 or_options_t *oldoptions, *newoptions;
3527 config_line_t *cl;
3528 char *cf=NULL, *fname=NULL, *errmsg=NULL;
3529 int i, retval;
3530 int using_default_torrc;
3531 int ignore_missing_torrc;
3532 static char **backup_argv;
3533 static int backup_argc;
3535 if (argv) { /* first time we're called. save commandline args */
3536 backup_argv = argv;
3537 backup_argc = argc;
3538 oldoptions = NULL;
3539 } else { /* we're reloading. need to clean up old options first. */
3540 argv = backup_argv;
3541 argc = backup_argc;
3542 oldoptions = get_options();
3544 if (argc > 1 && (!strcmp(argv[1], "-h") || !strcmp(argv[1],"--help"))) {
3545 print_usage();
3546 exit(0);
3548 if (argc > 1 && !strcmp(argv[1], "--list-torrc-options")) {
3549 /* For documenting validating whether we've documented everything. */
3550 list_torrc_options();
3551 exit(0);
3554 if (argc > 1 && (!strcmp(argv[1],"--version"))) {
3555 printf("Tor version %s.\n",get_version());
3556 if (argc > 2 && (!strcmp(argv[2],"--version"))) {
3557 print_svn_version();
3559 exit(0);
3562 newoptions = tor_malloc_zero(sizeof(or_options_t));
3563 newoptions->_magic = OR_OPTIONS_MAGIC;
3564 options_init(newoptions);
3566 /* learn config file name */
3567 fname = NULL;
3568 using_default_torrc = 1;
3569 ignore_missing_torrc = 0;
3570 newoptions->command = CMD_RUN_TOR;
3571 for (i = 1; i < argc; ++i) {
3572 if (i < argc-1 && !strcmp(argv[i],"-f")) {
3573 if (fname) {
3574 log(LOG_WARN, LD_CONFIG, "Duplicate -f options on command line.");
3575 tor_free(fname);
3577 #ifdef MS_WINDOWS
3578 /* XXX one day we might want to extend expand_filename to work
3579 * under Windows as well. */
3580 fname = tor_strdup(argv[i+1]);
3581 #else
3582 fname = expand_filename(argv[i+1]);
3583 #endif
3584 using_default_torrc = 0;
3585 ++i;
3586 } else if (!strcmp(argv[i],"--ignore-missing-torrc")) {
3587 ignore_missing_torrc = 1;
3588 } else if (!strcmp(argv[i],"--list-fingerprint")) {
3589 newoptions->command = CMD_LIST_FINGERPRINT;
3590 } else if (!strcmp(argv[i],"--hash-password")) {
3591 newoptions->command = CMD_HASH_PASSWORD;
3592 newoptions->command_arg = tor_strdup( (i < argc-1) ? argv[i+1] : "");
3593 ++i;
3594 } else if (!strcmp(argv[i],"--verify-config")) {
3595 newoptions->command = CMD_VERIFY_CONFIG;
3598 if (using_default_torrc) {
3599 /* didn't find one, try CONFDIR */
3600 const char *dflt = get_default_conf_file();
3601 if (dflt && file_status(dflt) == FN_FILE) {
3602 fname = tor_strdup(dflt);
3603 } else {
3604 #ifndef MS_WINDOWS
3605 char *fn;
3606 fn = expand_filename("~/.torrc");
3607 if (fn && file_status(fn) == FN_FILE) {
3608 fname = fn;
3609 } else {
3610 tor_free(fn);
3611 fname = tor_strdup(dflt);
3613 #else
3614 fname = tor_strdup(dflt);
3615 #endif
3618 tor_assert(fname);
3619 log(LOG_DEBUG, LD_CONFIG, "Opening config file \"%s\"", fname);
3621 tor_free(torrc_fname);
3622 torrc_fname = fname;
3624 /* get config lines, assign them */
3625 if (file_status(fname) != FN_FILE ||
3626 !(cf = read_file_to_str(fname,0,NULL))) {
3627 if (using_default_torrc == 1 || ignore_missing_torrc ) {
3628 log(LOG_NOTICE, LD_CONFIG, "Configuration file \"%s\" not present, "
3629 "using reasonable defaults.", fname);
3630 tor_free(fname); /* sets fname to NULL */
3631 torrc_fname = NULL;
3632 } else {
3633 log(LOG_WARN, LD_CONFIG,
3634 "Unable to open configuration file \"%s\".", fname);
3635 goto err;
3637 } else { /* it opened successfully. use it. */
3638 retval = config_get_lines(cf, &cl);
3639 tor_free(cf);
3640 if (retval < 0)
3641 goto err;
3642 retval = config_assign(&options_format, newoptions, cl, 0, 0, &errmsg);
3643 config_free_lines(cl);
3644 if (retval < 0)
3645 goto err;
3648 /* Go through command-line variables too */
3649 if (config_get_commandlines(argc, argv, &cl) < 0)
3650 goto err;
3651 retval = config_assign(&options_format, newoptions, cl, 0, 0, &errmsg);
3652 config_free_lines(cl);
3653 if (retval < 0)
3654 goto err;
3656 /* Validate newoptions */
3657 if (options_validate(oldoptions, newoptions, 0, &errmsg) < 0)
3658 goto err;
3660 if (options_transition_allowed(oldoptions, newoptions, &errmsg) < 0)
3661 goto err;
3663 if (set_options(newoptions, &errmsg))
3664 goto err; /* frees and replaces old options */
3666 return 0;
3667 err:
3668 tor_free(fname);
3669 torrc_fname = NULL;
3670 config_free(&options_format, newoptions);
3671 if (errmsg) {
3672 log(LOG_WARN,LD_CONFIG,"Failed to parse/validate config: %s", errmsg);
3673 tor_free(errmsg);
3675 return -1;
3678 /** Return the location for our configuration file.
3680 const char *
3681 get_torrc_fname(void)
3683 if (torrc_fname)
3684 return torrc_fname;
3685 else
3686 return get_default_conf_file();
3689 /** Adjust the address map mased on the MapAddress elements in the
3690 * configuration <b>options</b>
3692 static void
3693 config_register_addressmaps(or_options_t *options)
3695 smartlist_t *elts;
3696 config_line_t *opt;
3697 char *from, *to;
3699 addressmap_clear_configured();
3700 elts = smartlist_create();
3701 for (opt = options->AddressMap; opt; opt = opt->next) {
3702 smartlist_split_string(elts, opt->value, NULL,
3703 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
3704 if (smartlist_len(elts) >= 2) {
3705 from = smartlist_get(elts,0);
3706 to = smartlist_get(elts,1);
3707 if (address_is_invalid_destination(to, 1)) {
3708 log_warn(LD_CONFIG,
3709 "Skipping invalid argument '%s' to MapAddress", to);
3710 } else {
3711 addressmap_register(from, tor_strdup(to), 0, ADDRMAPSRC_TORRC);
3712 if (smartlist_len(elts)>2) {
3713 log_warn(LD_CONFIG,"Ignoring extra arguments to MapAddress.");
3716 } else {
3717 log_warn(LD_CONFIG,"MapAddress '%s' has too few arguments. Ignoring.",
3718 opt->value);
3720 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
3721 smartlist_clear(elts);
3723 smartlist_free(elts);
3727 * Initialize the logs based on the configuration file.
3729 static int
3730 options_init_logs(or_options_t *options, int validate_only)
3732 config_line_t *opt;
3733 int ok;
3734 smartlist_t *elts;
3735 int daemon =
3736 #ifdef MS_WINDOWS
3738 #else
3739 options->RunAsDaemon;
3740 #endif
3742 ok = 1;
3743 elts = smartlist_create();
3745 for (opt = options->Logs; opt; opt = opt->next) {
3746 log_severity_list_t *severity;
3747 const char *cfg = opt->value;
3748 severity = tor_malloc_zero(sizeof(log_severity_list_t));
3749 if (parse_log_severity_config(&cfg, severity) < 0) {
3750 log_warn(LD_CONFIG, "Couldn't parse log levels in Log option 'Log %s'",
3751 opt->value);
3752 ok = 0; goto cleanup;
3755 smartlist_split_string(elts, cfg, NULL,
3756 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
3758 if (smartlist_len(elts) == 0)
3759 smartlist_add(elts, tor_strdup("stdout"));
3761 if (smartlist_len(elts) == 1 &&
3762 (!strcasecmp(smartlist_get(elts,0), "stdout") ||
3763 !strcasecmp(smartlist_get(elts,0), "stderr"))) {
3764 int err = smartlist_len(elts) &&
3765 !strcasecmp(smartlist_get(elts,0), "stderr");
3766 if (!validate_only) {
3767 if (daemon) {
3768 log_warn(LD_CONFIG,
3769 "Can't log to %s with RunAsDaemon set; skipping stdout",
3770 err?"stderr":"stdout");
3771 } else {
3772 add_stream_log(severity, err?"<stderr>":"<stdout>",
3773 err?stderr:stdout);
3776 goto cleanup;
3778 if (smartlist_len(elts) == 1 &&
3779 !strcasecmp(smartlist_get(elts,0), "syslog")) {
3780 #ifdef HAVE_SYSLOG_H
3781 if (!validate_only) {
3782 add_syslog_log(severity);
3784 #else
3785 log_warn(LD_CONFIG, "Syslog is not supported on this system. Sorry.");
3786 #endif
3787 goto cleanup;
3790 if (smartlist_len(elts) == 2 &&
3791 !strcasecmp(smartlist_get(elts,0), "file")) {
3792 if (!validate_only) {
3793 if (add_file_log(severity, smartlist_get(elts, 1)) < 0) {
3794 log_warn(LD_CONFIG, "Couldn't open file for 'Log %s'", opt->value);
3795 ok = 0;
3798 goto cleanup;
3801 log_warn(LD_CONFIG, "Bad syntax on file Log option 'Log %s'",
3802 opt->value);
3803 ok = 0; goto cleanup;
3805 cleanup:
3806 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
3807 smartlist_clear(elts);
3808 tor_free(severity);
3810 smartlist_free(elts);
3812 return ok?0:-1;
3815 /** Parse a single RedirectExit line's contents from <b>line</b>. If
3816 * they are valid, and <b>result</b> is not NULL, add an element to
3817 * <b>result</b> and return 0. Else if they are valid, return 0.
3818 * Else set *msg and return -1. */
3819 static int
3820 parse_redirect_line(smartlist_t *result, config_line_t *line, char **msg)
3822 smartlist_t *elements = NULL;
3823 exit_redirect_t *r;
3825 tor_assert(line);
3827 r = tor_malloc_zero(sizeof(exit_redirect_t));
3828 elements = smartlist_create();
3829 smartlist_split_string(elements, line->value, NULL,
3830 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
3831 if (smartlist_len(elements) != 2) {
3832 *msg = tor_strdup("Wrong number of elements in RedirectExit line");
3833 goto err;
3835 if (parse_addr_and_port_range(smartlist_get(elements,0),&r->addr,
3836 &r->maskbits,&r->port_min,&r->port_max)) {
3837 *msg = tor_strdup("Error parsing source address in RedirectExit line");
3838 goto err;
3840 if (0==strcasecmp(smartlist_get(elements,1), "pass")) {
3841 r->is_redirect = 0;
3842 } else {
3843 if (parse_addr_port(LOG_WARN, smartlist_get(elements,1),NULL,
3844 &r->addr_dest, &r->port_dest)) {
3845 *msg = tor_strdup("Error parsing dest address in RedirectExit line");
3846 goto err;
3848 r->is_redirect = 1;
3851 goto done;
3852 err:
3853 tor_free(r);
3854 done:
3855 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
3856 smartlist_free(elements);
3857 if (r) {
3858 if (result)
3859 smartlist_add(result, r);
3860 else
3861 tor_free(r);
3862 return 0;
3863 } else {
3864 tor_assert(*msg);
3865 return -1;
3869 /** Read the contents of a Bridge line from <b>line</b>. Return 0
3870 * if the line is well-formed, and -1 if it isn't. If
3871 * <b>validate_only</b> is 0, and the line is well-formed, then add
3872 * the bridge described in the line to our internal bridge list. */
3873 static int
3874 parse_bridge_line(const char *line, int validate_only)
3876 smartlist_t *items = NULL;
3877 int r;
3878 char *addrport=NULL, *address=NULL, *fingerprint=NULL;
3879 uint32_t addr = 0;
3880 uint16_t port = 0;
3881 char digest[DIGEST_LEN];
3883 items = smartlist_create();
3884 smartlist_split_string(items, line, NULL,
3885 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
3886 if (smartlist_len(items) < 1) {
3887 log_warn(LD_CONFIG, "Too few arguments to Bridge line.");
3888 goto err;
3890 addrport = smartlist_get(items, 0);
3891 smartlist_del_keeporder(items, 0);
3892 if (parse_addr_port(LOG_WARN, addrport, &address, &addr, &port)<0) {
3893 log_warn(LD_CONFIG, "Error parsing Bridge address '%s'", addrport);
3894 goto err;
3896 if (!port) {
3897 log_warn(LD_CONFIG, "Missing port in Bridge address '%s'",addrport);
3898 goto err;
3901 if (smartlist_len(items)) {
3902 fingerprint = smartlist_join_strings(items, "", 0, NULL);
3903 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
3904 log_warn(LD_CONFIG, "Key digest for Bridge is wrong length.");
3905 goto err;
3907 if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
3908 log_warn(LD_CONFIG, "Unable to decode Bridge key digest.");
3909 goto err;
3913 if (!validate_only) {
3914 log_debug(LD_DIR, "Bridge at %s:%d (%s)", address,
3915 (int)port,
3916 fingerprint ? fingerprint : "no key listed");
3917 bridge_add_from_config(addr, port, fingerprint ? digest : NULL);
3920 r = 0;
3921 goto done;
3923 err:
3924 r = -1;
3926 done:
3927 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
3928 smartlist_free(items);
3929 tor_free(addrport);
3930 tor_free(address);
3931 tor_free(fingerprint);
3932 return r;
3935 /** Read the contents of a DirServer line from <b>line</b>. If
3936 * <b>validate_only</b> is 0, and the line is well-formed, and it
3937 * shares any bits with <b>required_type</b> or <b>required_type</b>
3938 * is 0, then add the dirserver described in the line (minus whatever
3939 * bits it's missing) as a valid authority. Return 0 on success,
3940 * or -1 if the line isn't well-formed or if we can't add it. */
3941 static int
3942 parse_dir_server_line(const char *line, authority_type_t required_type,
3943 int validate_only)
3945 smartlist_t *items = NULL;
3946 int r;
3947 char *addrport=NULL, *address=NULL, *nickname=NULL, *fingerprint=NULL;
3948 uint16_t dir_port = 0, or_port = 0;
3949 char digest[DIGEST_LEN];
3950 char v3_digest[DIGEST_LEN];
3951 authority_type_t type = V2_AUTHORITY;
3952 int is_not_hidserv_authority = 0, is_not_v2_authority = 0;
3954 items = smartlist_create();
3955 smartlist_split_string(items, line, NULL,
3956 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
3957 if (smartlist_len(items) < 1) {
3958 log_warn(LD_CONFIG, "No arguments on DirServer line.");
3959 goto err;
3962 if (is_legal_nickname(smartlist_get(items, 0))) {
3963 nickname = smartlist_get(items, 0);
3964 smartlist_del_keeporder(items, 0);
3967 while (smartlist_len(items)) {
3968 char *flag = smartlist_get(items, 0);
3969 if (TOR_ISDIGIT(flag[0]))
3970 break;
3971 if (!strcasecmp(flag, "v1")) {
3972 type |= (V1_AUTHORITY | HIDSERV_AUTHORITY);
3973 } else if (!strcasecmp(flag, "hs")) {
3974 type |= HIDSERV_AUTHORITY;
3975 } else if (!strcasecmp(flag, "no-hs")) {
3976 is_not_hidserv_authority = 1;
3977 } else if (!strcasecmp(flag, "bridge")) {
3978 type |= BRIDGE_AUTHORITY;
3979 } else if (!strcasecmp(flag, "no-v2")) {
3980 is_not_v2_authority = 1;
3981 } else if (!strcasecmpstart(flag, "orport=")) {
3982 int ok;
3983 char *portstring = flag + strlen("orport=");
3984 or_port = (uint16_t) tor_parse_long(portstring, 10, 1, 65535, &ok, NULL);
3985 if (!ok)
3986 log_warn(LD_CONFIG, "Invalid orport '%s' on DirServer line.",
3987 portstring);
3988 } else if (!strcasecmpstart(flag, "v3ident=")) {
3989 char *idstr = flag + strlen("v3ident=");
3990 if (strlen(idstr) != HEX_DIGEST_LEN ||
3991 base16_decode(v3_digest, DIGEST_LEN, idstr, HEX_DIGEST_LEN)<0) {
3992 log_warn(LD_CONFIG, "Bad v3 identity digest '%s' on DirServer line",
3993 flag);
3994 } else {
3995 type |= V3_AUTHORITY;
3997 } else {
3998 log_warn(LD_CONFIG, "Unrecognized flag '%s' on DirServer line",
3999 flag);
4001 tor_free(flag);
4002 smartlist_del_keeporder(items, 0);
4004 if (is_not_hidserv_authority)
4005 type &= ~HIDSERV_AUTHORITY;
4006 if (is_not_v2_authority)
4007 type &= ~V2_AUTHORITY;
4009 if (smartlist_len(items) < 2) {
4010 log_warn(LD_CONFIG, "Too few arguments to DirServer line.");
4011 goto err;
4013 addrport = smartlist_get(items, 0);
4014 smartlist_del_keeporder(items, 0);
4015 if (parse_addr_port(LOG_WARN, addrport, &address, NULL, &dir_port)<0) {
4016 log_warn(LD_CONFIG, "Error parsing DirServer address '%s'", addrport);
4017 goto err;
4019 if (!dir_port) {
4020 log_warn(LD_CONFIG, "Missing port in DirServer address '%s'",addrport);
4021 goto err;
4024 fingerprint = smartlist_join_strings(items, "", 0, NULL);
4025 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
4026 log_warn(LD_CONFIG, "Key digest for DirServer is wrong length %d.",
4027 (int)strlen(fingerprint));
4028 goto err;
4030 if (!strcmp(fingerprint, "E623F7625FBE0C87820F11EC5F6D5377ED816294")) {
4031 /* a known bad fingerprint. refuse to use it. We can remove this
4032 * clause once Tor 0.1.2.17 is obsolete. */
4033 log_warn(LD_CONFIG, "Dangerous dirserver line. To correct, erase your "
4034 "torrc file (%s), or reinstall Tor and use the default torrc.",
4035 get_torrc_fname());
4036 goto err;
4038 if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
4039 log_warn(LD_CONFIG, "Unable to decode DirServer key digest.");
4040 goto err;
4043 if (!validate_only && (!required_type || required_type & type)) {
4044 if (required_type)
4045 type &= required_type; /* pare down what we think of them as an
4046 * authority for. */
4047 log_debug(LD_DIR, "Trusted %d dirserver at %s:%d (%s)", (int)type,
4048 address, (int)dir_port, (char*)smartlist_get(items,0));
4049 if (!add_trusted_dir_server(nickname, address, dir_port, or_port,
4050 digest, v3_digest, type))
4051 goto err;
4054 r = 0;
4055 goto done;
4057 err:
4058 r = -1;
4060 done:
4061 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4062 smartlist_free(items);
4063 tor_free(addrport);
4064 tor_free(address);
4065 tor_free(nickname);
4066 tor_free(fingerprint);
4067 return r;
4070 /** Adjust the value of options->DataDirectory, or fill it in if it's
4071 * absent. Return 0 on success, -1 on failure. */
4072 static int
4073 normalize_data_directory(or_options_t *options)
4075 #ifdef MS_WINDOWS
4076 char *p;
4077 if (options->DataDirectory)
4078 return 0; /* all set */
4079 p = tor_malloc(MAX_PATH);
4080 strlcpy(p,get_windows_conf_root(),MAX_PATH);
4081 options->DataDirectory = p;
4082 return 0;
4083 #else
4084 const char *d = options->DataDirectory;
4085 if (!d)
4086 d = "~/.tor";
4088 if (strncmp(d,"~/",2) == 0) {
4089 char *fn = expand_filename(d);
4090 if (!fn) {
4091 log_warn(LD_CONFIG,"Failed to expand filename \"%s\".", d);
4092 return -1;
4094 if (!options->DataDirectory && !strcmp(fn,"/.tor")) {
4095 /* If our homedir is /, we probably don't want to use it. */
4096 /* Default to LOCALSTATEDIR/tor which is probably closer to what we
4097 * want. */
4098 log_warn(LD_CONFIG,
4099 "Default DataDirectory is \"~/.tor\". This expands to "
4100 "\"%s\", which is probably not what you want. Using "
4101 "\"%s"PATH_SEPARATOR"tor\" instead", fn, LOCALSTATEDIR);
4102 tor_free(fn);
4103 fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor");
4105 tor_free(options->DataDirectory);
4106 options->DataDirectory = fn;
4108 return 0;
4109 #endif
4112 /** Check and normalize the value of options->DataDirectory; return 0 if it
4113 * sane, -1 otherwise. */
4114 static int
4115 validate_data_directory(or_options_t *options)
4117 if (normalize_data_directory(options) < 0)
4118 return -1;
4119 tor_assert(options->DataDirectory);
4120 if (strlen(options->DataDirectory) > (512-128)) {
4121 log_warn(LD_CONFIG, "DataDirectory is too long.");
4122 return -1;
4124 return 0;
4127 /** This string must remain the same forevermore. It is how we
4128 * recognize that the torrc file doesn't need to be backed up. */
4129 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
4130 "if you edit it, comments will not be preserved"
4131 /** This string can change; it tries to give the reader an idea
4132 * that editing this file by hand is not a good plan. */
4133 #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
4134 "to torrc.orig.1 or similar, and Tor will ignore it"
4136 /** Save a configuration file for the configuration in <b>options</b>
4137 * into the file <b>fname</b>. If the file already exists, and
4138 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
4139 * replace it. Return 0 on success, -1 on failure. */
4140 static int
4141 write_configuration_file(const char *fname, or_options_t *options)
4143 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
4144 int rename_old = 0, r;
4145 size_t len;
4147 if (fname) {
4148 switch (file_status(fname)) {
4149 case FN_FILE:
4150 old_val = read_file_to_str(fname, 0, NULL);
4151 if (strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
4152 rename_old = 1;
4154 tor_free(old_val);
4155 break;
4156 case FN_NOENT:
4157 break;
4158 case FN_ERROR:
4159 case FN_DIR:
4160 default:
4161 log_warn(LD_CONFIG,
4162 "Config file \"%s\" is not a file? Failing.", fname);
4163 return -1;
4167 if (!(new_conf = options_dump(options, 1))) {
4168 log_warn(LD_BUG, "Couldn't get configuration string");
4169 goto err;
4172 len = strlen(new_conf)+256;
4173 new_val = tor_malloc(len);
4174 tor_snprintf(new_val, len, "%s\n%s\n\n%s",
4175 GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
4177 if (rename_old) {
4178 int i = 1;
4179 size_t fn_tmp_len = strlen(fname)+32;
4180 char *fn_tmp;
4181 tor_assert(fn_tmp_len > strlen(fname)); /*check for overflow*/
4182 fn_tmp = tor_malloc(fn_tmp_len);
4183 while (1) {
4184 if (tor_snprintf(fn_tmp, fn_tmp_len, "%s.orig.%d", fname, i)<0) {
4185 log_warn(LD_BUG, "tor_snprintf failed inexplicably");
4186 tor_free(fn_tmp);
4187 goto err;
4189 if (file_status(fn_tmp) == FN_NOENT)
4190 break;
4191 ++i;
4193 log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
4194 if (rename(fname, fn_tmp) < 0) {
4195 log_warn(LD_FS,
4196 "Couldn't rename configuration file \"%s\" to \"%s\": %s",
4197 fname, fn_tmp, strerror(errno));
4198 tor_free(fn_tmp);
4199 goto err;
4201 tor_free(fn_tmp);
4204 if (write_str_to_file(fname, new_val, 0) < 0)
4205 goto err;
4207 r = 0;
4208 goto done;
4209 err:
4210 r = -1;
4211 done:
4212 tor_free(new_val);
4213 tor_free(new_conf);
4214 return r;
4218 * Save the current configuration file value to disk. Return 0 on
4219 * success, -1 on failure.
4222 options_save_current(void)
4224 if (torrc_fname) {
4225 /* This fails if we can't write to our configuration file.
4227 * If we try falling back to datadirectory or something, we have a better
4228 * chance of saving the configuration, but a better chance of doing
4229 * something the user never expected. Let's just warn instead. */
4230 return write_configuration_file(torrc_fname, get_options());
4232 return write_configuration_file(get_default_conf_file(), get_options());
4235 /** Mapping from a unit name to a multiplier for converting that unit into a
4236 * base unit. */
4237 struct unit_table_t {
4238 const char *unit;
4239 uint64_t multiplier;
4242 static struct unit_table_t memory_units[] = {
4243 { "", 1 },
4244 { "b", 1<< 0 },
4245 { "byte", 1<< 0 },
4246 { "bytes", 1<< 0 },
4247 { "kb", 1<<10 },
4248 { "kbyte", 1<<10 },
4249 { "kbytes", 1<<10 },
4250 { "kilobyte", 1<<10 },
4251 { "kilobytes", 1<<10 },
4252 { "m", 1<<20 },
4253 { "mb", 1<<20 },
4254 { "mbyte", 1<<20 },
4255 { "mbytes", 1<<20 },
4256 { "megabyte", 1<<20 },
4257 { "megabytes", 1<<20 },
4258 { "gb", 1<<30 },
4259 { "gbyte", 1<<30 },
4260 { "gbytes", 1<<30 },
4261 { "gigabyte", 1<<30 },
4262 { "gigabytes", 1<<30 },
4263 { "tb", U64_LITERAL(1)<<40 },
4264 { "terabyte", U64_LITERAL(1)<<40 },
4265 { "terabytes", U64_LITERAL(1)<<40 },
4266 { NULL, 0 },
4269 static struct unit_table_t time_units[] = {
4270 { "", 1 },
4271 { "second", 1 },
4272 { "seconds", 1 },
4273 { "minute", 60 },
4274 { "minutes", 60 },
4275 { "hour", 60*60 },
4276 { "hours", 60*60 },
4277 { "day", 24*60*60 },
4278 { "days", 24*60*60 },
4279 { "week", 7*24*60*60 },
4280 { "weeks", 7*24*60*60 },
4281 { NULL, 0 },
4284 /** Parse a string <b>val</b> containing a number, zero or more
4285 * spaces, and an optional unit string. If the unit appears in the
4286 * table <b>u</b>, then multiply the number by the unit multiplier.
4287 * On success, set *<b>ok</b> to 1 and return this product.
4288 * Otherwise, set *<b>ok</b> to 0.
4290 static uint64_t
4291 config_parse_units(const char *val, struct unit_table_t *u, int *ok)
4293 uint64_t v;
4294 char *cp;
4296 tor_assert(ok);
4298 v = tor_parse_uint64(val, 10, 0, UINT64_MAX, ok, &cp);
4299 if (!*ok)
4300 return 0;
4301 if (!cp) {
4302 *ok = 1;
4303 return v;
4305 while (TOR_ISSPACE(*cp))
4306 ++cp;
4307 for ( ;u->unit;++u) {
4308 if (!strcasecmp(u->unit, cp)) {
4309 v *= u->multiplier;
4310 *ok = 1;
4311 return v;
4314 log_warn(LD_CONFIG, "Unknown unit '%s'.", cp);
4315 *ok = 0;
4316 return 0;
4319 /** Parse a string in the format "number unit", where unit is a unit of
4320 * information (byte, KB, M, etc). On success, set *<b>ok</b> to true
4321 * and return the number of bytes specified. Otherwise, set
4322 * *<b>ok</b> to false and return 0. */
4323 static uint64_t
4324 config_parse_memunit(const char *s, int *ok)
4326 return config_parse_units(s, memory_units, ok);
4329 /** Parse a string in the format "number unit", where unit is a unit of time.
4330 * On success, set *<b>ok</b> to true and return the number of seconds in
4331 * the provided interval. Otherwise, set *<b>ok</b> to 0 and return -1.
4333 static int
4334 config_parse_interval(const char *s, int *ok)
4336 uint64_t r;
4337 r = config_parse_units(s, time_units, ok);
4338 if (!ok)
4339 return -1;
4340 if (r > INT_MAX) {
4341 log_warn(LD_CONFIG, "Interval '%s' is too long", s);
4342 *ok = 0;
4343 return -1;
4345 return (int)r;
4349 * Initialize the libevent library.
4351 static void
4352 init_libevent(void)
4354 configure_libevent_logging();
4355 /* If the kernel complains that some method (say, epoll) doesn't
4356 * exist, we don't care about it, since libevent will cope.
4358 suppress_libevent_log_msg("Function not implemented");
4359 #ifdef __APPLE__
4360 if (decode_libevent_version() < LE_11B) {
4361 setenv("EVENT_NOKQUEUE","1",1);
4363 #endif
4364 event_init();
4365 suppress_libevent_log_msg(NULL);
4366 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
4367 /* Making this a NOTICE for now so we can link bugs to a libevent versions
4368 * or methods better. */
4369 log(LOG_NOTICE, LD_GENERAL,
4370 "Initialized libevent version %s using method %s. Good.",
4371 event_get_version(), event_get_method());
4372 check_libevent_version(event_get_method(), get_options()->ORPort != 0);
4373 #else
4374 log(LOG_NOTICE, LD_GENERAL,
4375 "Initialized old libevent (version 1.0b or earlier).");
4376 log(LOG_WARN, LD_GENERAL,
4377 "You have a *VERY* old version of libevent. It is likely to be buggy; "
4378 "please build Tor with a more recent version.");
4379 #endif
4382 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
4383 /** Table mapping return value of event_get_version() to le_version_t. */
4384 static const struct {
4385 const char *name; le_version_t version;
4386 } le_version_table[] = {
4387 /* earlier versions don't have get_version. */
4388 { "1.0c", LE_10C },
4389 { "1.0d", LE_10D },
4390 { "1.0e", LE_10E },
4391 { "1.1", LE_11 },
4392 { "1.1a", LE_11A },
4393 { "1.1b", LE_11B },
4394 { "1.2", LE_12 },
4395 { "1.2a", LE_12A },
4396 { "1.3", LE_13 },
4397 { "1.3a", LE_13A },
4398 { "1.3b", LE_13B },
4399 { "1.3c", LE_13C },
4400 { "1.3d", LE_13D },
4401 { NULL, LE_OTHER }
4404 /** Return the le_version_t for the current version of libevent. If the
4405 * version is very new, return LE_OTHER. If the version is so old that it
4406 * doesn't support event_get_version(), return LE_OLD. */
4407 static le_version_t
4408 decode_libevent_version(void)
4410 const char *v = event_get_version();
4411 int i;
4412 for (i=0; le_version_table[i].name; ++i) {
4413 if (!strcmp(le_version_table[i].name, v)) {
4414 return le_version_table[i].version;
4417 return LE_OTHER;
4421 * Compare the given libevent method and version to a list of versions
4422 * which are known not to work. Warn the user as appropriate.
4424 static void
4425 check_libevent_version(const char *m, int server)
4427 int buggy = 0, iffy = 0, slow = 0, thread_unsafe = 0;
4428 le_version_t version;
4429 const char *v = event_get_version();
4430 const char *badness = NULL;
4431 const char *sad_os = "";
4433 version = decode_libevent_version();
4435 /* XXX Would it be worthwhile disabling the methods that we know
4436 * are buggy, rather than just warning about them and then proceeding
4437 * to use them? If so, we should probably not wrap this whole thing
4438 * in HAVE_EVENT_GET_VERSION and HAVE_EVENT_GET_METHOD. -RD */
4439 /* XXXX The problem is that it's not trivial to get libevent to change it's
4440 * method once it's initialized, and it's not trivial to tell what method it
4441 * will use without initializing it. I guess we could preemptively disable
4442 * buggy libevent modes based on the version _before_ initializing it,
4443 * though, but then there's no good way (afaict) to warn "I would have used
4444 * kqueue, but instead I'm using select." -NM */
4445 if (!strcmp(m, "kqueue")) {
4446 if (version < LE_11B)
4447 buggy = 1;
4448 } else if (!strcmp(m, "epoll")) {
4449 if (version < LE_11)
4450 iffy = 1;
4451 } else if (!strcmp(m, "poll")) {
4452 if (version < LE_10E)
4453 buggy = 1;
4454 else if (version < LE_11)
4455 slow = 1;
4456 } else if (!strcmp(m, "select")) {
4457 if (version < LE_11)
4458 slow = 1;
4459 } else if (!strcmp(m, "win32")) {
4460 if (version < LE_11B)
4461 buggy = 1;
4464 /* Libevent versions before 1.3b do very badly on operating systems with
4465 * user-space threading implementations. */
4466 #if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__)
4467 if (server && version < LE_13B) {
4468 thread_unsafe = 1;
4469 sad_os = "BSD variants";
4471 #elif defined(__APPLE__) || defined(__darwin__)
4472 if (server && version < LE_13B) {
4473 thread_unsafe = 1;
4474 sad_os = "Mac OS X";
4476 #endif
4478 if (thread_unsafe) {
4479 log(LOG_WARN, LD_GENERAL,
4480 "Libevent version %s often crashes when running a Tor server with %s. "
4481 "Please use the latest version of libevent (1.3b or later)",v,sad_os);
4482 badness = "BROKEN";
4483 } else if (buggy) {
4484 log(LOG_WARN, LD_GENERAL,
4485 "There are serious bugs in using %s with libevent %s. "
4486 "Please use the latest version of libevent.", m, v);
4487 badness = "BROKEN";
4488 } else if (iffy) {
4489 log(LOG_WARN, LD_GENERAL,
4490 "There are minor bugs in using %s with libevent %s. "
4491 "You may want to use the latest version of libevent.", m, v);
4492 badness = "BUGGY";
4493 } else if (slow && server) {
4494 log(LOG_WARN, LD_GENERAL,
4495 "libevent %s can be very slow with %s. "
4496 "When running a server, please use the latest version of libevent.",
4497 v,m);
4498 badness = "SLOW";
4500 if (badness) {
4501 control_event_general_status(LOG_WARN,
4502 "BAD_LIBEVENT VERSION=%s METHOD=%s BADNESS=%s RECOVERED=NO",
4503 v, m, badness);
4507 #else
4508 static le_version_t
4509 decode_libevent_version(void)
4511 return LE_OLD;
4513 #endif
4515 /** Return the persistent state struct for this Tor. */
4516 or_state_t *
4517 get_or_state(void)
4519 tor_assert(global_state);
4520 return global_state;
4523 /** Return a newly allocated string holding a filename relative to the data
4524 * directory. If <b>sub1</b> is present, it is the first path component after
4525 * the data directory. If <b>sub2</b> is also present, it is the second path
4526 * component after the data directory. If <b>suffix</b> is present, it
4527 * is appended to the filename.
4529 * Examples:
4530 * get_datadir_fname2_suffix("a", NULL, NULL) -> $DATADIR/a
4531 * get_datadir_fname2_suffix("a", NULL, ".tmp") -> $DATADIR/a.tmp
4532 * get_datadir_fname2_suffix("a", "b", ".tmp") -> $DATADIR/a/b/.tmp
4533 * get_datadir_fname2_suffix("a", "b", NULL) -> $DATADIR/a/b
4535 * Note: Consider using the get_datadir_fname* macros in or.h.
4537 char *
4538 get_datadir_fname2_suffix(const char *sub1, const char *sub2,
4539 const char *suffix)
4541 or_options_t *options = get_options();
4542 char *fname = NULL;
4543 size_t len;
4544 tor_assert(options);
4545 tor_assert(options->DataDirectory);
4546 tor_assert(sub1 || !sub2); /* If sub2 is present, sub1 must be present. */
4547 len = strlen(options->DataDirectory);
4548 if (sub1) {
4549 len += strlen(sub1)+1;
4550 if (sub2)
4551 len += strlen(sub2)+1;
4553 if (suffix)
4554 len += strlen(suffix);
4555 len++;
4556 fname = tor_malloc(len);
4557 if (sub1) {
4558 if (sub2) {
4559 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s",
4560 options->DataDirectory, sub1, sub2);
4561 } else {
4562 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s",
4563 options->DataDirectory, sub1);
4565 } else {
4566 strlcpy(fname, options->DataDirectory, len);
4568 if (suffix)
4569 strlcat(fname, suffix, len);
4570 return fname;
4573 /** Return 0 if every setting in <b>state</b> is reasonable, and a
4574 * permissible transition from <b>old_state</b>. Else warn and return -1.
4575 * Should have no side effects, except for normalizing the contents of
4576 * <b>state</b>.
4578 /* XXX from_setconf is here because of bug 238 */
4579 static int
4580 or_state_validate(or_state_t *old_state, or_state_t *state,
4581 int from_setconf, char **msg)
4583 /* We don't use these; only options do. Still, we need to match that
4584 * signature. */
4585 (void) from_setconf;
4586 (void) old_state;
4588 if (entry_guards_parse_state(state, 0, msg)<0)
4589 return -1;
4591 return 0;
4594 /** Replace the current persistent state with <b>new_state</b> */
4595 static void
4596 or_state_set(or_state_t *new_state)
4598 char *err = NULL;
4599 tor_assert(new_state);
4600 if (global_state)
4601 config_free(&state_format, global_state);
4602 global_state = new_state;
4603 if (entry_guards_parse_state(global_state, 1, &err)<0) {
4604 log_warn(LD_GENERAL,"%s",err);
4605 tor_free(err);
4607 if (rep_hist_load_state(global_state, &err)<0) {
4608 log_warn(LD_GENERAL,"Unparseable bandwidth history state: %s",err);
4609 tor_free(err);
4613 /** Reload the persistent state from disk, generating a new state as needed.
4614 * Return 0 on success, less than 0 on failure.
4616 static int
4617 or_state_load(void)
4619 or_state_t *new_state = NULL;
4620 char *contents = NULL, *fname;
4621 char *errmsg = NULL;
4622 int r = -1, badstate = 0;
4624 fname = get_datadir_fname("state");
4625 switch (file_status(fname)) {
4626 case FN_FILE:
4627 if (!(contents = read_file_to_str(fname, 0, NULL))) {
4628 log_warn(LD_FS, "Unable to read state file \"%s\"", fname);
4629 goto done;
4631 break;
4632 case FN_NOENT:
4633 break;
4634 case FN_ERROR:
4635 case FN_DIR:
4636 default:
4637 log_warn(LD_GENERAL,"State file \"%s\" is not a file? Failing.", fname);
4638 goto done;
4640 new_state = tor_malloc_zero(sizeof(or_state_t));
4641 new_state->_magic = OR_STATE_MAGIC;
4642 config_init(&state_format, new_state);
4643 if (contents) {
4644 config_line_t *lines=NULL;
4645 int assign_retval;
4646 if (config_get_lines(contents, &lines)<0)
4647 goto done;
4648 assign_retval = config_assign(&state_format, new_state,
4649 lines, 0, 0, &errmsg);
4650 config_free_lines(lines);
4651 if (assign_retval<0)
4652 badstate = 1;
4653 if (errmsg) {
4654 log_warn(LD_GENERAL, "%s", errmsg);
4655 tor_free(errmsg);
4659 if (!badstate && or_state_validate(NULL, new_state, 1, &errmsg) < 0)
4660 badstate = 1;
4662 if (errmsg) {
4663 log_warn(LD_GENERAL, "%s", errmsg);
4664 tor_free(errmsg);
4667 if (badstate && !contents) {
4668 log_warn(LD_BUG, "Uh oh. We couldn't even validate our own default state."
4669 " This is a bug in Tor.");
4670 goto done;
4671 } else if (badstate && contents) {
4672 int i;
4673 file_status_t status;
4674 size_t len = strlen(fname)+16;
4675 char *fname2 = tor_malloc(len);
4676 for (i = 0; i < 100; ++i) {
4677 tor_snprintf(fname2, len, "%s.%d", fname, i);
4678 status = file_status(fname2);
4679 if (status == FN_NOENT)
4680 break;
4682 if (i == 100) {
4683 log_warn(LD_BUG, "Unable to parse state in \"%s\"; too many saved bad "
4684 "state files to move aside. Discarding the old state file.",
4685 fname);
4686 unlink(fname);
4687 } else {
4688 log_warn(LD_BUG, "Unable to parse state in \"%s\". Moving it aside "
4689 "to \"%s\". This could be a bug in Tor; please tell "
4690 "the developers.", fname, fname2);
4691 if (rename(fname, fname2) < 0) {
4692 log_warn(LD_BUG, "Weirdly, I couldn't even move the state aside. The "
4693 "OS gave an error of %s", strerror(errno));
4696 tor_free(fname2);
4697 tor_free(contents);
4698 config_free(&state_format, new_state);
4700 new_state = tor_malloc_zero(sizeof(or_state_t));
4701 new_state->_magic = OR_STATE_MAGIC;
4702 config_init(&state_format, new_state);
4703 } else if (contents) {
4704 log_info(LD_GENERAL, "Loaded state from \"%s\"", fname);
4705 } else {
4706 log_info(LD_GENERAL, "Initialized state");
4708 or_state_set(new_state);
4709 new_state = NULL;
4710 if (!contents) {
4711 global_state->next_write = 0;
4712 or_state_save(time(NULL));
4714 r = 0;
4716 done:
4717 tor_free(fname);
4718 tor_free(contents);
4719 if (new_state)
4720 config_free(&state_format, new_state);
4722 return r;
4725 /** Write the persistent state to disk. Return 0 for success, <0 on failure. */
4727 or_state_save(time_t now)
4729 char *state, *contents;
4730 char tbuf[ISO_TIME_LEN+1];
4731 size_t len;
4732 char *fname;
4734 tor_assert(global_state);
4736 if (global_state->next_write > now)
4737 return 0;
4739 /* Call everything else that might dirty the state even more, in order
4740 * to avoid redundant writes. */
4741 entry_guards_update_state(global_state);
4742 rep_hist_update_state(global_state);
4743 if (accounting_is_enabled(get_options()))
4744 accounting_run_housekeeping(now);
4746 global_state->LastWritten = time(NULL);
4747 tor_free(global_state->TorVersion);
4748 len = strlen(get_version())+8;
4749 global_state->TorVersion = tor_malloc(len);
4750 tor_snprintf(global_state->TorVersion, len, "Tor %s", get_version());
4752 state = config_dump(&state_format, global_state, 1, 0);
4753 len = strlen(state)+256;
4754 contents = tor_malloc(len);
4755 format_local_iso_time(tbuf, time(NULL));
4756 tor_snprintf(contents, len,
4757 "# Tor state file last generated on %s local time\n"
4758 "# Other times below are in GMT\n"
4759 "# You *do not* need to edit this file.\n\n%s",
4760 tbuf, state);
4761 tor_free(state);
4762 fname = get_datadir_fname("state");
4763 if (write_str_to_file(fname, contents, 0)<0) {
4764 log_warn(LD_FS, "Unable to write state to file \"%s\"", fname);
4765 tor_free(fname);
4766 tor_free(contents);
4767 return -1;
4769 log_info(LD_GENERAL, "Saved state to \"%s\"", fname);
4770 tor_free(fname);
4771 tor_free(contents);
4773 global_state->next_write = TIME_MAX;
4774 return 0;
4777 /** Given a file name check to see whether the file exists but has not been
4778 * modified for a very long time. If so, remove it. */
4779 void
4780 remove_file_if_very_old(const char *fname, time_t now)
4782 #define VERY_OLD_FILE_AGE (28*24*60*60)
4783 struct stat st;
4785 if (stat(fname, &st)==0 && st.st_mtime < now-VERY_OLD_FILE_AGE) {
4786 char buf[ISO_TIME_LEN+1];
4787 format_local_iso_time(buf, st.st_mtime);
4788 log_notice(LD_GENERAL, "Obsolete file %s hasn't been modified since %s. "
4789 "Removing it.", fname, buf);
4790 unlink(fname);
4794 /** Helper to implement GETINFO functions about configuration variables (not
4795 * their values). Given a "config/names" question, set *<b>answer</b> to a
4796 * new string describing the supported configuration variables and their
4797 * types. */
4799 getinfo_helper_config(control_connection_t *conn,
4800 const char *question, char **answer)
4802 (void) conn;
4803 if (!strcmp(question, "config/names")) {
4804 smartlist_t *sl = smartlist_create();
4805 int i;
4806 for (i = 0; _option_vars[i].name; ++i) {
4807 config_var_t *var = &_option_vars[i];
4808 const char *type, *desc;
4809 char *line;
4810 size_t len;
4811 desc = config_find_description(&options_format, var->name);
4812 switch (var->type) {
4813 case CONFIG_TYPE_STRING: type = "String"; break;
4814 case CONFIG_TYPE_UINT: type = "Integer"; break;
4815 case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
4816 case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
4817 case CONFIG_TYPE_DOUBLE: type = "Float"; break;
4818 case CONFIG_TYPE_BOOL: type = "Boolean"; break;
4819 case CONFIG_TYPE_ISOTIME: type = "Time"; break;
4820 case CONFIG_TYPE_CSV: type = "CommaList"; break;
4821 case CONFIG_TYPE_LINELIST: type = "LineList"; break;
4822 case CONFIG_TYPE_LINELIST_S: type = "Dependant"; break;
4823 case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
4824 default:
4825 case CONFIG_TYPE_OBSOLETE:
4826 type = NULL; break;
4828 if (!type)
4829 continue;
4830 len = strlen(var->name)+strlen(type)+16;
4831 if (desc)
4832 len += strlen(desc);
4833 line = tor_malloc(len);
4834 if (desc)
4835 tor_snprintf(line, len, "%s %s %s\n",var->name,type,desc);
4836 else
4837 tor_snprintf(line, len, "%s %s\n",var->name,type);
4838 smartlist_add(sl, line);
4840 *answer = smartlist_join_strings(sl, "", 0, NULL);
4841 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
4842 smartlist_free(sl);
4844 return 0;
4847 #include "aes.h"
4848 #include "ht.h"
4849 #include "test.h"
4851 extern const char aes_c_id[];
4852 extern const char compat_c_id[];
4853 extern const char container_c_id[];
4854 extern const char crypto_c_id[];
4855 extern const char log_c_id[];
4856 extern const char torgzip_c_id[];
4857 extern const char tortls_c_id[];
4858 extern const char util_c_id[];
4860 extern const char buffers_c_id[];
4861 extern const char circuitbuild_c_id[];
4862 extern const char circuitlist_c_id[];
4863 extern const char circuituse_c_id[];
4864 extern const char command_c_id[];
4865 // extern const char config_c_id[];
4866 extern const char connection_c_id[];
4867 extern const char connection_edge_c_id[];
4868 extern const char connection_or_c_id[];
4869 extern const char control_c_id[];
4870 extern const char cpuworker_c_id[];
4871 extern const char directory_c_id[];
4872 extern const char dirserv_c_id[];
4873 extern const char dns_c_id[];
4874 extern const char hibernate_c_id[];
4875 extern const char main_c_id[];
4876 #ifdef NT_SERVICE
4877 extern const char ntmain_c_id[];
4878 #endif
4879 extern const char onion_c_id[];
4880 extern const char policies_c_id[];
4881 extern const char relay_c_id[];
4882 extern const char rendclient_c_id[];
4883 extern const char rendcommon_c_id[];
4884 extern const char rendmid_c_id[];
4885 extern const char rendservice_c_id[];
4886 extern const char rephist_c_id[];
4887 extern const char router_c_id[];
4888 extern const char routerlist_c_id[];
4889 extern const char routerparse_c_id[];
4891 /** Dump the version of every file to the log. */
4892 static void
4893 print_svn_version(void)
4895 puts(AES_H_ID);
4896 puts(COMPAT_H_ID);
4897 puts(CONTAINER_H_ID);
4898 puts(CRYPTO_H_ID);
4899 puts(HT_H_ID);
4900 puts(TEST_H_ID);
4901 puts(LOG_H_ID);
4902 puts(TORGZIP_H_ID);
4903 puts(TORINT_H_ID);
4904 puts(TORTLS_H_ID);
4905 puts(UTIL_H_ID);
4906 puts(aes_c_id);
4907 puts(compat_c_id);
4908 puts(container_c_id);
4909 puts(crypto_c_id);
4910 puts(log_c_id);
4911 puts(torgzip_c_id);
4912 puts(tortls_c_id);
4913 puts(util_c_id);
4915 puts(OR_H_ID);
4916 puts(buffers_c_id);
4917 puts(circuitbuild_c_id);
4918 puts(circuitlist_c_id);
4919 puts(circuituse_c_id);
4920 puts(command_c_id);
4921 puts(config_c_id);
4922 puts(connection_c_id);
4923 puts(connection_edge_c_id);
4924 puts(connection_or_c_id);
4925 puts(control_c_id);
4926 puts(cpuworker_c_id);
4927 puts(directory_c_id);
4928 puts(dirserv_c_id);
4929 puts(dns_c_id);
4930 puts(hibernate_c_id);
4931 puts(main_c_id);
4932 #ifdef NT_SERVICE
4933 puts(ntmain_c_id);
4934 #endif
4935 puts(onion_c_id);
4936 puts(policies_c_id);
4937 puts(relay_c_id);
4938 puts(rendclient_c_id);
4939 puts(rendcommon_c_id);
4940 puts(rendmid_c_id);
4941 puts(rendservice_c_id);
4942 puts(rephist_c_id);
4943 puts(router_c_id);
4944 puts(routerlist_c_id);
4945 puts(routerparse_c_id);