gabelmoo has a new IP address.
[tor/rransom.git] / src / or / config.c
bloba704b7e6ca86a05ffb63950b85ba373fbbb2b364
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_FILENAME, /**< A filename: some prefixes get expanded. */
26 CONFIG_TYPE_UINT, /**< A non-negative integer less than MAX_INT */
27 CONFIG_TYPE_INTERVAL, /**< A number of seconds, with optional units*/
28 CONFIG_TYPE_MEMUNIT, /**< A number of bytes, with optional units*/
29 CONFIG_TYPE_DOUBLE, /**< A floating-point value */
30 CONFIG_TYPE_BOOL, /**< A boolean value, expressed as 0 or 1. */
31 CONFIG_TYPE_ISOTIME, /**< An ISO-formated time relative to GMT. */
32 CONFIG_TYPE_CSV, /**< A list of strings, separated by commas and
33 * optional whitespace. */
34 CONFIG_TYPE_LINELIST, /**< Uninterpreted config lines */
35 CONFIG_TYPE_LINELIST_S, /**< Uninterpreted, context-sensitive config lines,
36 * mixed with other keywords. */
37 CONFIG_TYPE_LINELIST_V, /**< Catch-all "virtual" option to summarize
38 * context-sensitive config lines when fetching.
40 CONFIG_TYPE_ROUTERSET, /**< A list of router names, addrs, and fps,
41 * parsed into a routerset_t. */
42 CONFIG_TYPE_OBSOLETE, /**< Obsolete (ignored) option. */
43 } config_type_t;
45 /** An abbreviation for a configuration option allowed on the command line. */
46 typedef struct config_abbrev_t {
47 const char *abbreviated;
48 const char *full;
49 int commandline_only;
50 int warn;
51 } config_abbrev_t;
53 /* Handy macro for declaring "In the config file or on the command line,
54 * you can abbreviate <b>tok</b>s as <b>tok</b>". */
55 #define PLURAL(tok) { #tok, #tok "s", 0, 0 }
57 /* A list of command-line abbreviations. */
58 static config_abbrev_t _option_abbrevs[] = {
59 PLURAL(ExitNode),
60 PLURAL(EntryNode),
61 PLURAL(ExcludeNode),
62 PLURAL(FirewallPort),
63 PLURAL(LongLivedPort),
64 PLURAL(HiddenServiceNode),
65 PLURAL(HiddenServiceExcludeNode),
66 PLURAL(NumCpu),
67 PLURAL(RendNode),
68 PLURAL(RendExcludeNode),
69 PLURAL(StrictEntryNode),
70 PLURAL(StrictExitNode),
71 { "l", "Log", 1, 0},
72 { "AllowUnverifiedNodes", "AllowInvalidNodes", 0, 0},
73 { "AutomapHostSuffixes", "AutomapHostsSuffixes", 0, 0},
74 { "AutomapHostOnResolve", "AutomapHostsOnResolve", 0, 0},
75 { "BandwidthRateBytes", "BandwidthRate", 0, 0},
76 { "BandwidthBurstBytes", "BandwidthBurst", 0, 0},
77 { "DirFetchPostPeriod", "StatusFetchPeriod", 0, 0},
78 { "MaxConn", "ConnLimit", 0, 1},
79 { "ORBindAddress", "ORListenAddress", 0, 0},
80 { "DirBindAddress", "DirListenAddress", 0, 0},
81 { "SocksBindAddress", "SocksListenAddress", 0, 0},
82 { "UseHelperNodes", "UseEntryGuards", 0, 0},
83 { "NumHelperNodes", "NumEntryGuards", 0, 0},
84 { "UseEntryNodes", "UseEntryGuards", 0, 0},
85 { "NumEntryNodes", "NumEntryGuards", 0, 0},
86 { "ResolvConf", "ServerDNSResolvConfFile", 0, 1},
87 { "SearchDomains", "ServerDNSSearchDomains", 0, 1},
88 { "PreferTunnelledDirConns", "PreferTunneledDirConns", 0, 0},
89 { "BridgeAuthoritativeDirectory", "BridgeAuthoritativeDir", 0, 0},
90 { "HashedControlPassword", "__HashedControlSessionPassword", 1, 0},
91 { NULL, NULL, 0, 0},
93 /* A list of state-file abbreviations, for compatibility. */
94 static config_abbrev_t _state_abbrevs[] = {
95 { "AccountingBytesReadInterval", "AccountingBytesReadInInterval", 0, 0 },
96 { "HelperNode", "EntryGuard", 0, 0 },
97 { "HelperNodeDownSince", "EntryGuardDownSince", 0, 0 },
98 { "HelperNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
99 { "EntryNode", "EntryGuard", 0, 0 },
100 { "EntryNodeDownSince", "EntryGuardDownSince", 0, 0 },
101 { "EntryNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
102 { NULL, NULL, 0, 0},
104 #undef PLURAL
106 /** A variable allowed in the configuration file or on the command line. */
107 typedef struct config_var_t {
108 const char *name; /**< The full keyword (case insensitive). */
109 config_type_t type; /**< How to interpret the type and turn it into a
110 * value. */
111 off_t var_offset; /**< Offset of the corresponding member of or_options_t. */
112 const char *initvalue; /**< String (or null) describing initial value. */
113 } config_var_t;
115 /** An entry for config_vars: "The option <b>name</b> has type
116 * CONFIG_TYPE_<b>conftype</b>, and corresponds to
117 * or_options_t.<b>member</b>"
119 #define VAR(name,conftype,member,initvalue) \
120 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_options_t, member), \
121 initvalue }
122 /** As VAR, but the option name and member name are the same. */
123 #define V(member,conftype,initvalue) \
124 VAR(#member, conftype, member, initvalue)
125 /** An entry for config_vars: "The option <b>name</b> is obsolete." */
126 #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL }
128 /** Array of configuration options. Until we disallow nonstandard
129 * abbreviations, order is significant, since the first matching option will
130 * be chosen first.
132 static config_var_t _option_vars[] = {
133 OBSOLETE("AccountingMaxKB"),
134 V(AccountingMax, MEMUNIT, "0 bytes"),
135 V(AccountingStart, STRING, NULL),
136 V(Address, STRING, NULL),
137 V(AllowInvalidNodes, CSV, "middle,rendezvous"),
138 V(AllowNonRFC953Hostnames, BOOL, "0"),
139 V(AllowSingleHopCircuits, BOOL, "0"),
140 V(AllowSingleHopExits, BOOL, "0"),
141 V(AlternateBridgeAuthority, LINELIST, NULL),
142 V(AlternateDirAuthority, LINELIST, NULL),
143 V(AlternateHSAuthority, LINELIST, NULL),
144 V(AssumeReachable, BOOL, "0"),
145 V(AuthDirBadDir, LINELIST, NULL),
146 V(AuthDirBadExit, LINELIST, NULL),
147 V(AuthDirInvalid, LINELIST, NULL),
148 V(AuthDirReject, LINELIST, NULL),
149 V(AuthDirRejectUnlisted, BOOL, "0"),
150 V(AuthDirListBadDirs, BOOL, "0"),
151 V(AuthDirListBadExits, BOOL, "0"),
152 V(AuthDirMaxServersPerAddr, UINT, "2"),
153 V(AuthDirMaxServersPerAuthAddr,UINT, "5"),
154 VAR("AuthoritativeDirectory", BOOL, AuthoritativeDir, "0"),
155 V(AutomapHostsOnResolve, BOOL, "0"),
156 V(AutomapHostsSuffixes, CSV, ".onion,.exit"),
157 V(AvoidDiskWrites, BOOL, "0"),
158 V(BandwidthBurst, MEMUNIT, "10 MB"),
159 V(BandwidthRate, MEMUNIT, "5 MB"),
160 V(BridgeAuthoritativeDir, BOOL, "0"),
161 VAR("Bridge", LINELIST, Bridges, NULL),
162 V(BridgePassword, STRING, NULL),
163 V(BridgeRecordUsageByCountry, BOOL, "1"),
164 V(BridgeRelay, BOOL, "0"),
165 V(CircuitBuildTimeout, INTERVAL, "1 minute"),
166 V(CircuitIdleTimeout, INTERVAL, "1 hour"),
167 V(ClientDNSRejectInternalAddresses, BOOL,"1"),
168 V(ClientOnly, BOOL, "0"),
169 V(ConnLimit, UINT, "1000"),
170 V(ConstrainedSockets, BOOL, "0"),
171 V(ConstrainedSockSize, MEMUNIT, "8192"),
172 V(ContactInfo, STRING, NULL),
173 V(ControlListenAddress, LINELIST, NULL),
174 V(ControlPort, UINT, "0"),
175 V(ControlSocket, LINELIST, NULL),
176 V(CookieAuthentication, BOOL, "0"),
177 V(CookieAuthFileGroupReadable, BOOL, "0"),
178 V(CookieAuthFile, STRING, NULL),
179 V(DataDirectory, FILENAME, NULL),
180 OBSOLETE("DebugLogFile"),
181 V(DirAllowPrivateAddresses, BOOL, NULL),
182 V(TestingAuthDirTimeToLearnReachability, INTERVAL, "30 minutes"),
183 V(DirListenAddress, LINELIST, NULL),
184 OBSOLETE("DirFetchPeriod"),
185 V(DirPolicy, LINELIST, NULL),
186 V(DirPort, UINT, "0"),
187 OBSOLETE("DirPostPeriod"),
188 #ifdef ENABLE_GEOIP_STATS
189 V(DirRecordUsageByCountry, BOOL, "0"),
190 V(DirRecordUsageGranularity, UINT, "4"),
191 V(DirRecordUsageRetainIPs, INTERVAL, "14 days"),
192 V(DirRecordUsageSaveInterval, INTERVAL, "6 hours"),
193 #endif
194 VAR("DirServer", LINELIST, DirServers, NULL),
195 V(DNSPort, UINT, "0"),
196 V(DNSListenAddress, LINELIST, NULL),
197 V(DownloadExtraInfo, BOOL, "0"),
198 V(EnforceDistinctSubnets, BOOL, "1"),
199 V(EntryNodes, ROUTERSET, NULL),
200 V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "10 minutes"),
201 V(ExcludeNodes, ROUTERSET, NULL),
202 V(ExcludeExitNodes, ROUTERSET, NULL),
203 V(ExcludeSingleHopRelays, BOOL, "1"),
204 V(ExitNodes, ROUTERSET, NULL),
205 V(ExitPolicy, LINELIST, NULL),
206 V(ExitPolicyRejectPrivate, BOOL, "1"),
207 V(FallbackNetworkstatusFile, FILENAME,
208 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "fallback-consensus"),
209 V(FascistFirewall, BOOL, "0"),
210 V(FirewallPorts, CSV, ""),
211 V(FastFirstHopPK, BOOL, "1"),
212 V(FetchDirInfoEarly, BOOL, "0"),
213 V(FetchServerDescriptors, BOOL, "1"),
214 V(FetchHidServDescriptors, BOOL, "1"),
215 V(FetchUselessDescriptors, BOOL, "0"),
216 #ifdef WIN32
217 V(GeoIPFile, FILENAME, "<default>"),
218 #else
219 V(GeoIPFile, FILENAME,
220 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip"),
221 #endif
222 V(Group, STRING, NULL),
223 V(HardwareAccel, BOOL, "0"),
224 V(HashedControlPassword, LINELIST, NULL),
225 V(HidServDirectoryV2, BOOL, "1"),
226 VAR("HiddenServiceDir", LINELIST_S, RendConfigLines, NULL),
227 OBSOLETE("HiddenServiceExcludeNodes"),
228 OBSOLETE("HiddenServiceNodes"),
229 VAR("HiddenServiceOptions",LINELIST_V, RendConfigLines, NULL),
230 VAR("HiddenServicePort", LINELIST_S, RendConfigLines, NULL),
231 VAR("HiddenServiceVersion",LINELIST_S, RendConfigLines, NULL),
232 VAR("HiddenServiceAuthorizeClient",LINELIST_S,RendConfigLines, NULL),
233 V(HidServAuth, LINELIST, NULL),
234 V(HSAuthoritativeDir, BOOL, "0"),
235 V(HSAuthorityRecordStats, BOOL, "0"),
236 V(HttpProxy, STRING, NULL),
237 V(HttpProxyAuthenticator, STRING, NULL),
238 V(HttpsProxy, STRING, NULL),
239 V(HttpsProxyAuthenticator, STRING, NULL),
240 OBSOLETE("IgnoreVersion"),
241 V(KeepalivePeriod, INTERVAL, "5 minutes"),
242 VAR("Log", LINELIST, Logs, NULL),
243 OBSOLETE("LinkPadding"),
244 OBSOLETE("LogLevel"),
245 OBSOLETE("LogFile"),
246 V(LongLivedPorts, CSV,
247 "21,22,706,1863,5050,5190,5222,5223,6667,6697,8300"),
248 VAR("MapAddress", LINELIST, AddressMap, NULL),
249 V(MaxAdvertisedBandwidth, MEMUNIT, "1 GB"),
250 V(MaxCircuitDirtiness, INTERVAL, "10 minutes"),
251 V(MaxOnionsPending, UINT, "100"),
252 OBSOLETE("MonthlyAccountingStart"),
253 V(MyFamily, STRING, NULL),
254 V(NewCircuitPeriod, INTERVAL, "30 seconds"),
255 VAR("NamingAuthoritativeDirectory",BOOL, NamingAuthoritativeDir, "0"),
256 V(NatdListenAddress, LINELIST, NULL),
257 V(NatdPort, UINT, "0"),
258 V(Nickname, STRING, NULL),
259 V(NoPublish, BOOL, "0"),
260 VAR("NodeFamily", LINELIST, NodeFamilies, NULL),
261 V(NumCpus, UINT, "1"),
262 V(NumEntryGuards, UINT, "3"),
263 V(ORListenAddress, LINELIST, NULL),
264 V(ORPort, UINT, "0"),
265 V(OutboundBindAddress, STRING, NULL),
266 OBSOLETE("PathlenCoinWeight"),
267 V(PidFile, STRING, NULL),
268 V(TestingTorNetwork, BOOL, "0"),
269 V(PreferTunneledDirConns, BOOL, "1"),
270 V(ProtocolWarnings, BOOL, "0"),
271 V(PublishServerDescriptor, CSV, "1"),
272 V(PublishHidServDescriptors, BOOL, "1"),
273 V(ReachableAddresses, LINELIST, NULL),
274 V(ReachableDirAddresses, LINELIST, NULL),
275 V(ReachableORAddresses, LINELIST, NULL),
276 V(RecommendedVersions, LINELIST, NULL),
277 V(RecommendedClientVersions, LINELIST, NULL),
278 V(RecommendedServerVersions, LINELIST, NULL),
279 V(RedirectExit, LINELIST, NULL),
280 V(RejectPlaintextPorts, CSV, ""),
281 V(RelayBandwidthBurst, MEMUNIT, "0"),
282 V(RelayBandwidthRate, MEMUNIT, "0"),
283 OBSOLETE("RendExcludeNodes"),
284 OBSOLETE("RendNodes"),
285 V(RendPostPeriod, INTERVAL, "1 hour"),
286 V(RephistTrackTime, INTERVAL, "24 hours"),
287 OBSOLETE("RouterFile"),
288 V(RunAsDaemon, BOOL, "0"),
289 V(RunTesting, BOOL, "0"),
290 V(SafeLogging, BOOL, "1"),
291 V(SafeSocks, BOOL, "0"),
292 V(ServerDNSAllowBrokenResolvConf, BOOL, "0"),
293 V(ServerDNSAllowNonRFC953Hostnames, BOOL,"0"),
294 V(ServerDNSDetectHijacking, BOOL, "1"),
295 V(ServerDNSResolvConfFile, STRING, NULL),
296 V(ServerDNSSearchDomains, BOOL, "0"),
297 V(ServerDNSTestAddresses, CSV,
298 "www.google.com,www.mit.edu,www.yahoo.com,www.slashdot.org"),
299 V(ShutdownWaitLength, INTERVAL, "30 seconds"),
300 V(SocksListenAddress, LINELIST, NULL),
301 V(SocksPolicy, LINELIST, NULL),
302 V(SocksPort, UINT, "9050"),
303 V(SocksTimeout, INTERVAL, "2 minutes"),
304 OBSOLETE("StatusFetchPeriod"),
305 V(StrictEntryNodes, BOOL, "0"),
306 V(StrictExitNodes, BOOL, "0"),
307 OBSOLETE("SysLog"),
308 V(TestSocks, BOOL, "0"),
309 OBSOLETE("TestVia"),
310 V(TrackHostExits, CSV, NULL),
311 V(TrackHostExitsExpire, INTERVAL, "30 minutes"),
312 OBSOLETE("TrafficShaping"),
313 V(TransListenAddress, LINELIST, NULL),
314 V(TransPort, UINT, "0"),
315 V(TunnelDirConns, BOOL, "1"),
316 V(UpdateBridgesFromAuthority, BOOL, "0"),
317 V(UseBridges, BOOL, "0"),
318 V(UseEntryGuards, BOOL, "1"),
319 V(User, STRING, NULL),
320 VAR("V1AuthoritativeDirectory",BOOL, V1AuthoritativeDir, "0"),
321 VAR("V2AuthoritativeDirectory",BOOL, V2AuthoritativeDir, "0"),
322 VAR("V3AuthoritativeDirectory",BOOL, V3AuthoritativeDir, "0"),
323 V(TestingV3AuthInitialVotingInterval, INTERVAL, "30 minutes"),
324 V(TestingV3AuthInitialVoteDelay, INTERVAL, "5 minutes"),
325 V(TestingV3AuthInitialDistDelay, INTERVAL, "5 minutes"),
326 V(V3AuthVotingInterval, INTERVAL, "1 hour"),
327 V(V3AuthVoteDelay, INTERVAL, "5 minutes"),
328 V(V3AuthDistDelay, INTERVAL, "5 minutes"),
329 V(V3AuthNIntervalsValid, UINT, "3"),
330 V(V3AuthUseLegacyKey, BOOL, "0"),
331 VAR("VersioningAuthoritativeDirectory",BOOL,VersioningAuthoritativeDir, "0"),
332 V(VirtualAddrNetwork, STRING, "127.192.0.0/10"),
333 V(WarnPlaintextPorts, CSV, "23,109,110,143"),
334 VAR("__AllDirActionsPrivate", BOOL, AllDirActionsPrivate, "0"),
335 VAR("__DisablePredictedCircuits",BOOL,DisablePredictedCircuits, "0"),
336 VAR("__LeaveStreamsUnattached",BOOL, LeaveStreamsUnattached, "0"),
337 VAR("__HashedControlSessionPassword", LINELIST, HashedControlSessionPassword,
338 NULL),
339 V(MinUptimeHidServDirectoryV2, INTERVAL, "24 hours"),
340 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
343 /* Keep defaults synchronous with man page and config value check. */
344 static config_var_t testing_tor_network_defaults[] = {
345 V(ServerDNSAllowBrokenResolvConf, BOOL, "1"),
346 V(DirAllowPrivateAddresses, BOOL, "1"),
347 V(EnforceDistinctSubnets, BOOL, "0"),
348 V(AssumeReachable, BOOL, "1"),
349 V(AuthDirMaxServersPerAddr, UINT, "0"),
350 V(AuthDirMaxServersPerAuthAddr,UINT, "0"),
351 V(ClientDNSRejectInternalAddresses, BOOL,"0"),
352 V(ExitPolicyRejectPrivate, BOOL, "0"),
353 V(V3AuthVotingInterval, INTERVAL, "5 minutes"),
354 V(V3AuthVoteDelay, INTERVAL, "20 seconds"),
355 V(V3AuthDistDelay, INTERVAL, "20 seconds"),
356 V(TestingV3AuthInitialVotingInterval, INTERVAL, "5 minutes"),
357 V(TestingV3AuthInitialVoteDelay, INTERVAL, "20 seconds"),
358 V(TestingV3AuthInitialDistDelay, INTERVAL, "20 seconds"),
359 V(TestingAuthDirTimeToLearnReachability, INTERVAL, "0 minutes"),
360 V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "0 minutes"),
361 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
363 #undef VAR
365 #define VAR(name,conftype,member,initvalue) \
366 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_state_t, member), \
367 initvalue }
368 static config_var_t _state_vars[] = {
369 V(AccountingBytesReadInInterval, MEMUNIT, NULL),
370 V(AccountingBytesWrittenInInterval, MEMUNIT, NULL),
371 V(AccountingExpectedUsage, MEMUNIT, NULL),
372 V(AccountingIntervalStart, ISOTIME, NULL),
373 V(AccountingSecondsActive, INTERVAL, NULL),
375 VAR("EntryGuard", LINELIST_S, EntryGuards, NULL),
376 VAR("EntryGuardDownSince", LINELIST_S, EntryGuards, NULL),
377 VAR("EntryGuardUnlistedSince", LINELIST_S, EntryGuards, NULL),
378 VAR("EntryGuardAddedBy", LINELIST_S, EntryGuards, NULL),
379 V(EntryGuards, LINELIST_V, NULL),
381 V(BWHistoryReadEnds, ISOTIME, NULL),
382 V(BWHistoryReadInterval, UINT, "900"),
383 V(BWHistoryReadValues, CSV, ""),
384 V(BWHistoryWriteEnds, ISOTIME, NULL),
385 V(BWHistoryWriteInterval, UINT, "900"),
386 V(BWHistoryWriteValues, CSV, ""),
388 V(TorVersion, STRING, NULL),
390 V(LastRotatedOnionKey, ISOTIME, NULL),
391 V(LastWritten, ISOTIME, NULL),
393 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
396 #undef VAR
397 #undef V
398 #undef OBSOLETE
400 /** Represents an English description of a configuration variable; used when
401 * generating configuration file comments. */
402 typedef struct config_var_description_t {
403 const char *name;
404 const char *description;
405 } config_var_description_t;
407 static config_var_description_t options_description[] = {
408 /* ==== general options */
409 { "AvoidDiskWrites", "If non-zero, try to write to disk less frequently than"
410 " we would otherwise." },
411 { "BandwidthRate", "A token bucket limits the average incoming bandwidth on "
412 "this node to the specified number of bytes per second." },
413 { "BandwidthBurst", "Limit the maximum token buffer size (also known as "
414 "burst) to the given number of bytes." },
415 { "ConnLimit", "Minimum number of simultaneous sockets we must have." },
416 { "ConstrainedSockets", "Shrink tx and rx buffers for sockets to avoid "
417 "system limits on vservers and related environments. See man page for "
418 "more information regarding this option." },
419 { "ConstrainedSockSize", "Limit socket buffers to this size when "
420 "ConstrainedSockets is enabled." },
421 /* ControlListenAddress */
422 { "ControlPort", "If set, Tor will accept connections from the same machine "
423 "(localhost only) on this port, and allow those connections to control "
424 "the Tor process using the Tor Control Protocol (described in "
425 "control-spec.txt).", },
426 { "CookieAuthentication", "If this option is set to 1, don't allow any "
427 "connections to the control port except when the connecting process "
428 "can read a file that Tor creates in its data directory." },
429 { "DataDirectory", "Store working data, state, keys, and caches here." },
430 { "DirServer", "Tor only trusts directories signed with one of these "
431 "servers' keys. Used to override the standard list of directory "
432 "authorities." },
433 /* { "FastFirstHopPK", "" }, */
434 /* FetchServerDescriptors, FetchHidServDescriptors,
435 * FetchUselessDescriptors */
436 { "Group", "On startup, setgid to this group." },
437 { "HardwareAccel", "If set, Tor tries to use hardware crypto accelerators "
438 "when it can." },
439 /* HashedControlPassword */
440 { "HTTPProxy", "Force Tor to make all HTTP directory requests through this "
441 "host:port (or host:80 if port is not set)." },
442 { "HTTPProxyAuthenticator", "A username:password pair to be used with "
443 "HTTPProxy." },
444 { "HTTPSProxy", "Force Tor to make all TLS (SSL) connectinos through this "
445 "host:port (or host:80 if port is not set)." },
446 { "HTTPSProxyAuthenticator", "A username:password pair to be used with "
447 "HTTPSProxy." },
448 { "KeepalivePeriod", "Send a padding cell every N seconds to keep firewalls "
449 "from closing our connections while Tor is not in use." },
450 { "Log", "Where to send logging messages. Format is "
451 "minSeverity[-maxSeverity] (stderr|stdout|syslog|file FILENAME)." },
452 { "OutboundBindAddress", "Make all outbound connections originate from the "
453 "provided IP address (only useful for multiple network interfaces)." },
454 { "PIDFile", "On startup, write our PID to this file. On clean shutdown, "
455 "remove the file." },
456 { "PreferTunneledDirConns", "If non-zero, avoid directory servers that "
457 "don't support tunneled connections." },
458 /* PreferTunneledDirConns */
459 /* ProtocolWarnings */
460 /* RephistTrackTime */
461 { "RunAsDaemon", "If set, Tor forks and daemonizes to the background when "
462 "started. Unix only." },
463 { "SafeLogging", "If set to 0, Tor logs potentially sensitive strings "
464 "rather than replacing them with the string [scrubbed]." },
465 { "TunnelDirConns", "If non-zero, when a directory server we contact "
466 "supports it, we will build a one-hop circuit and make an encrypted "
467 "connection via its ORPort." },
468 { "User", "On startup, setuid to this user." },
470 /* ==== client options */
471 { "AllowInvalidNodes", "Where on our circuits should Tor allow servers "
472 "that the directory authorities haven't called \"valid\"?" },
473 { "AllowNonRFC953Hostnames", "If set to 1, we don't automatically reject "
474 "hostnames for having invalid characters." },
475 /* CircuitBuildTimeout, CircuitIdleTimeout */
476 { "ClientOnly", "If set to 1, Tor will under no circumstances run as a "
477 "server, even if ORPort is enabled." },
478 { "EntryNodes", "A list of preferred entry nodes to use for the first hop "
479 "in circuits, when possible." },
480 /* { "EnforceDistinctSubnets" , "" }, */
481 { "ExitNodes", "A list of preferred nodes to use for the last hop in "
482 "circuits, when possible." },
483 { "ExcludeNodes", "A list of nodes never to use when building a circuit." },
484 { "FascistFirewall", "If set, Tor will only create outgoing connections to "
485 "servers running on the ports listed in FirewallPorts." },
486 { "FirewallPorts", "A list of ports that we can connect to. Only used "
487 "when FascistFirewall is set." },
488 { "LongLivedPorts", "A list of ports for services that tend to require "
489 "high-uptime connections." },
490 { "MapAddress", "Force Tor to treat all requests for one address as if "
491 "they were for another." },
492 { "NewCircuitPeriod", "Force Tor to consider whether to build a new circuit "
493 "every NUM seconds." },
494 { "MaxCircuitDirtiness", "Do not attach new streams to a circuit that has "
495 "been used more than this many seconds ago." },
496 /* NatdPort, NatdListenAddress */
497 { "NodeFamily", "A list of servers that constitute a 'family' and should "
498 "never be used in the same circuit." },
499 { "NumEntryGuards", "How many entry guards should we keep at a time?" },
500 /* PathlenCoinWeight */
501 { "ReachableAddresses", "Addresses we can connect to, as IP/bits:port-port. "
502 "By default, we assume all addresses are reachable." },
503 /* reachablediraddresses, reachableoraddresses. */
504 /* SafeSOCKS */
505 { "SOCKSPort", "The port where we listen for SOCKS connections from "
506 "applications." },
507 { "SOCKSListenAddress", "Bind to this address to listen to connections from "
508 "SOCKS-speaking applications." },
509 { "SOCKSPolicy", "Set an entry policy to limit which addresses can connect "
510 "to the SOCKSPort." },
511 /* SocksTimeout */
512 { "StrictExitNodes", "If set, Tor will fail to operate when none of the "
513 "configured ExitNodes can be used." },
514 { "StrictEntryNodes", "If set, Tor will fail to operate when none of the "
515 "configured EntryNodes can be used." },
516 /* TestSocks */
517 { "TrackHostsExit", "Hosts and domains which should, if possible, be "
518 "accessed from the same exit node each time we connect to them." },
519 { "TrackHostsExitExpire", "Time after which we forget which exit we were "
520 "using to connect to hosts in TrackHostsExit." },
521 /* "TransPort", "TransListenAddress */
522 { "UseEntryGuards", "Set to 0 if we want to pick from the whole set of "
523 "servers for the first position in each circuit, rather than picking a "
524 "set of 'Guards' to prevent profiling attacks." },
526 /* === server options */
527 { "Address", "The advertised (external) address we should use." },
528 /* Accounting* options. */
529 /* AssumeReachable */
530 { "ContactInfo", "Administrative contact information to advertise for this "
531 "server." },
532 { "ExitPolicy", "Address/port ranges for which to accept or reject outgoing "
533 "connections on behalf of Tor users." },
534 /* { "ExitPolicyRejectPrivate, "" }, */
535 { "MaxAdvertisedBandwidth", "If set, we will not advertise more than this "
536 "amount of bandwidth for our bandwidth rate, regardless of how much "
537 "bandwidth we actually detect." },
538 { "MaxOnionsPending", "Reject new attempts to extend circuits when we "
539 "already have this many pending." },
540 { "MyFamily", "Declare a list of other servers as belonging to the same "
541 "family as this one, so that clients will not use two from the same "
542 "family in the same circuit." },
543 { "Nickname", "Set the server nickname." },
544 { "NoPublish", "{DEPRECATED}" },
545 { "NumCPUs", "How many processes to use at once for public-key crypto." },
546 { "ORPort", "Advertise this port to listen for connections from Tor clients "
547 "and servers." },
548 { "ORListenAddress", "Bind to this address to listen for connections from "
549 "clients and servers, instead of the default 0.0.0.0:ORPort." },
550 { "PublishServerDescriptor", "Set to 0 to keep the server from "
551 "uploading info to the directory authorities." },
552 /*{ "RedirectExit", "When an outgoing connection tries to connect to a "
553 *"given address, redirect it to another address instead." },
555 /* ServerDNS: DetectHijacking, ResolvConfFile, SearchDomains */
556 { "ShutdownWaitLength", "Wait this long for clients to finish when "
557 "shutting down because of a SIGINT." },
559 /* === directory cache options */
560 { "DirPort", "Serve directory information from this port, and act as a "
561 "directory cache." },
562 { "DirListenAddress", "Bind to this address to listen for connections from "
563 "clients and servers, instead of the default 0.0.0.0:DirPort." },
564 { "DirPolicy", "Set a policy to limit who can connect to the directory "
565 "port." },
567 /* Authority options: AuthDirBadExit, AuthDirInvalid, AuthDirReject,
568 * AuthDirRejectUnlisted, AuthDirListBadExits, AuthoritativeDirectory,
569 * DirAllowPrivateAddresses, HSAuthoritativeDir,
570 * NamingAuthoritativeDirectory, RecommendedVersions,
571 * RecommendedClientVersions, RecommendedServerVersions, RendPostPeriod,
572 * RunTesting, V1AuthoritativeDirectory, VersioningAuthoritativeDirectory, */
574 /* Hidden service options: HiddenService: dir,excludenodes, nodes,
575 * options, port. PublishHidServDescriptor */
577 /* Nonpersistent options: __LeaveStreamsUnattached, __AllDirActionsPrivate */
578 { NULL, NULL },
581 static config_var_description_t state_description[] = {
582 { "AccountingBytesReadInInterval",
583 "How many bytes have we read in this accounting period?" },
584 { "AccountingBytesWrittenInInterval",
585 "How many bytes have we written in this accounting period?" },
586 { "AccountingExpectedUsage",
587 "How many bytes did we expect to use per minute? (0 for no estimate.)" },
588 { "AccountingIntervalStart", "When did this accounting period begin?" },
589 { "AccountingSecondsActive", "How long have we been awake in this period?" },
591 { "BWHistoryReadEnds", "When does the last-recorded read-interval end?" },
592 { "BWHistoryReadInterval", "How long is each read-interval (in seconds)?" },
593 { "BWHistoryReadValues", "Number of bytes read in each interval." },
594 { "BWHistoryWriteEnds", "When does the last-recorded write-interval end?" },
595 { "BWHistoryWriteInterval", "How long is each write-interval (in seconds)?"},
596 { "BWHistoryWriteValues", "Number of bytes written in each interval." },
598 { "EntryGuard", "One of the nodes we have chosen as a fixed entry" },
599 { "EntryGuardDownSince",
600 "The last entry guard has been unreachable since this time." },
601 { "EntryGuardUnlistedSince",
602 "The last entry guard has been unusable since this time." },
604 { "LastRotatedOnionKey",
605 "The last time at which we changed the medium-term private key used for "
606 "building circuits." },
607 { "LastWritten", "When was this state file last regenerated?" },
609 { "TorVersion", "Which version of Tor generated this state file?" },
610 { NULL, NULL },
613 /** Type of a callback to validate whether a given configuration is
614 * well-formed and consistent. See options_trial_assign() for documentation
615 * of arguments. */
616 typedef int (*validate_fn_t)(void*,void*,int,char**);
618 /** Information on the keys, value types, key-to-struct-member mappings,
619 * variable descriptions, validation functions, and abbreviations for a
620 * configuration or storage format. */
621 typedef struct {
622 size_t size; /**< Size of the struct that everything gets parsed into. */
623 uint32_t magic; /**< Required 'magic value' to make sure we have a struct
624 * of the right type. */
625 off_t magic_offset; /**< Offset of the magic value within the struct. */
626 config_abbrev_t *abbrevs; /**< List of abbreviations that we expand when
627 * parsing this format. */
628 config_var_t *vars; /**< List of variables we recognize, their default
629 * values, and where we stick them in the structure. */
630 validate_fn_t validate_fn; /**< Function to validate config. */
631 /** Documentation for configuration variables. */
632 config_var_description_t *descriptions;
633 /** If present, extra is a LINELIST variable for unrecognized
634 * lines. Otherwise, unrecognized lines are an error. */
635 config_var_t *extra;
636 } config_format_t;
638 /** Macro: assert that <b>cfg</b> has the right magic field for format
639 * <b>fmt</b>. */
640 #define CHECK(fmt, cfg) STMT_BEGIN \
641 tor_assert(fmt && cfg); \
642 tor_assert((fmt)->magic == \
643 *(uint32_t*)STRUCT_VAR_P(cfg,fmt->magic_offset)); \
644 STMT_END
646 #ifdef MS_WINDOWS
647 static char *get_windows_conf_root(void);
648 #endif
649 static void config_line_append(config_line_t **lst,
650 const char *key, const char *val);
651 static void option_clear(config_format_t *fmt, or_options_t *options,
652 config_var_t *var);
653 static void option_reset(config_format_t *fmt, or_options_t *options,
654 config_var_t *var, int use_defaults);
655 static void config_free(config_format_t *fmt, void *options);
656 static int config_lines_eq(config_line_t *a, config_line_t *b);
657 static int option_is_same(config_format_t *fmt,
658 or_options_t *o1, or_options_t *o2,
659 const char *name);
660 static or_options_t *options_dup(config_format_t *fmt, or_options_t *old);
661 static int options_validate(or_options_t *old_options, or_options_t *options,
662 int from_setconf, char **msg);
663 static int options_act_reversible(or_options_t *old_options, char **msg);
664 static int options_act(or_options_t *old_options);
665 static int options_transition_allowed(or_options_t *old, or_options_t *new,
666 char **msg);
667 static int options_transition_affects_workers(or_options_t *old_options,
668 or_options_t *new_options);
669 static int options_transition_affects_descriptor(or_options_t *old_options,
670 or_options_t *new_options);
671 static int check_nickname_list(const char *lst, const char *name, char **msg);
672 static void config_register_addressmaps(or_options_t *options);
674 static int parse_bridge_line(const char *line, int validate_only);
675 static int parse_dir_server_line(const char *line,
676 authority_type_t required_type,
677 int validate_only);
678 static int parse_redirect_line(smartlist_t *result,
679 config_line_t *line, char **msg);
680 static int validate_data_directory(or_options_t *options);
681 static int write_configuration_file(const char *fname, or_options_t *options);
682 static config_line_t *get_assigned_option(config_format_t *fmt,
683 or_options_t *options, const char *key,
684 int escape_val);
685 static void config_init(config_format_t *fmt, void *options);
686 static int or_state_validate(or_state_t *old_options, or_state_t *options,
687 int from_setconf, char **msg);
688 static int or_state_load(void);
689 static int options_init_logs(or_options_t *options, int validate_only);
691 static uint64_t config_parse_memunit(const char *s, int *ok);
692 static int config_parse_interval(const char *s, int *ok);
693 static void print_svn_version(void);
694 static void init_libevent(void);
695 static int opt_streq(const char *s1, const char *s2);
696 /** Versions of libevent. */
697 typedef enum {
698 /* Note: we compare these, so it's important that "old" precede everything,
699 * and that "other" come last. */
700 LE_OLD=0, LE_10C, LE_10D, LE_10E, LE_11, LE_11A, LE_11B, LE_12, LE_12A,
701 LE_13, LE_13A, LE_13B, LE_13C, LE_13D,
702 LE_OTHER
703 } le_version_t;
704 static le_version_t decode_libevent_version(void);
705 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
706 static void check_libevent_version(const char *m, int server);
707 #endif
709 /** Magic value for or_options_t. */
710 #define OR_OPTIONS_MAGIC 9090909
712 /** Configuration format for or_options_t. */
713 static config_format_t options_format = {
714 sizeof(or_options_t),
715 OR_OPTIONS_MAGIC,
716 STRUCT_OFFSET(or_options_t, _magic),
717 _option_abbrevs,
718 _option_vars,
719 (validate_fn_t)options_validate,
720 options_description,
721 NULL
724 /** Magic value for or_state_t. */
725 #define OR_STATE_MAGIC 0x57A73f57
727 /** "Extra" variable in the state that receives lines we can't parse. This
728 * lets us preserve options from versions of Tor newer than us. */
729 static config_var_t state_extra_var = {
730 "__extra", CONFIG_TYPE_LINELIST, STRUCT_OFFSET(or_state_t, ExtraLines), NULL
733 /** Configuration format for or_state_t. */
734 static config_format_t state_format = {
735 sizeof(or_state_t),
736 OR_STATE_MAGIC,
737 STRUCT_OFFSET(or_state_t, _magic),
738 _state_abbrevs,
739 _state_vars,
740 (validate_fn_t)or_state_validate,
741 state_description,
742 &state_extra_var,
746 * Functions to read and write the global options pointer.
749 /** Command-line and config-file options. */
750 static or_options_t *global_options = NULL;
751 /** Name of most recently read torrc file. */
752 static char *torrc_fname = NULL;
753 /** Persistent serialized state. */
754 static or_state_t *global_state = NULL;
755 /** Configuration Options set by command line. */
756 static config_line_t *global_cmdline_options = NULL;
758 /** Allocate an empty configuration object of a given format type. */
759 static void *
760 config_alloc(config_format_t *fmt)
762 void *opts = tor_malloc_zero(fmt->size);
763 *(uint32_t*)STRUCT_VAR_P(opts, fmt->magic_offset) = fmt->magic;
764 CHECK(fmt, opts);
765 return opts;
768 /** Return the currently configured options. */
769 or_options_t *
770 get_options(void)
772 tor_assert(global_options);
773 return global_options;
776 /** Change the current global options to contain <b>new_val</b> instead of
777 * their current value; take action based on the new value; free the old value
778 * as necessary. Returns 0 on success, -1 on failure.
781 set_options(or_options_t *new_val, char **msg)
783 or_options_t *old_options = global_options;
784 global_options = new_val;
785 /* Note that we pass the *old* options below, for comparison. It
786 * pulls the new options directly out of global_options. */
787 if (options_act_reversible(old_options, msg)<0) {
788 tor_assert(*msg);
789 global_options = old_options;
790 return -1;
792 if (options_act(old_options) < 0) { /* acting on the options failed. die. */
793 log_err(LD_BUG,
794 "Acting on config options left us in a broken state. Dying.");
795 exit(1);
797 if (old_options)
798 config_free(&options_format, old_options);
800 return 0;
803 extern const char tor_svn_revision[]; /* from tor_main.c */
805 static char *_version = NULL;
807 /** Return the current Tor version, possibly */
808 const char *
809 get_version(void)
811 if (_version == NULL) {
812 if (strlen(tor_svn_revision)) {
813 size_t len = strlen(VERSION)+strlen(tor_svn_revision)+8;
814 _version = tor_malloc(len);
815 tor_snprintf(_version, len, "%s (r%s)", VERSION, tor_svn_revision);
816 } else {
817 _version = tor_strdup(VERSION);
820 return _version;
823 /** Release additional memory allocated in options
825 static void
826 or_options_free(or_options_t *options)
828 if (options->_ExcludeExitNodesUnion)
829 routerset_free(options->_ExcludeExitNodesUnion);
830 config_free(&options_format, options);
833 /** Release all memory and resources held by global configuration structures.
835 void
836 config_free_all(void)
838 if (global_options) {
839 or_options_free(global_options);
840 global_options = NULL;
842 if (global_state) {
843 config_free(&state_format, global_state);
844 global_state = NULL;
846 if (global_cmdline_options) {
847 config_free_lines(global_cmdline_options);
848 global_cmdline_options = NULL;
850 tor_free(torrc_fname);
851 tor_free(_version);
854 /** If options->SafeLogging is on, return a not very useful string,
855 * else return address.
857 const char *
858 safe_str(const char *address)
860 tor_assert(address);
861 if (get_options()->SafeLogging)
862 return "[scrubbed]";
863 else
864 return address;
867 /** Equivalent to escaped(safe_str(address)). See reentrancy note on
868 * escaped(): don't use this outside the main thread, or twice in the same
869 * log statement. */
870 const char *
871 escaped_safe_str(const char *address)
873 if (get_options()->SafeLogging)
874 return "[scrubbed]";
875 else
876 return escaped(address);
879 /** Add the default directory authorities directly into the trusted dir list,
880 * but only add them insofar as they share bits with <b>type</b>. */
881 static void
882 add_default_trusted_dir_authorities(authority_type_t type)
884 int i;
885 const char *dirservers[] = {
886 "moria1 v1 orport=9001 v3ident=E2A2AF570166665D738736D0DD58169CC61D8A8B "
887 "128.31.0.34:9031 FFCB 46DB 1339 DA84 674C 70D7 CB58 6434 C437 0441",
888 "moria2 v1 orport=9002 128.31.0.34:9032 "
889 "719B E45D E224 B607 C537 07D0 E214 3E2D 423E 74CF",
890 "tor26 v1 orport=443 v3ident=14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4 "
891 "86.59.21.38:80 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D",
892 "dizum orport=443 v3ident=E8A9C45EDE6D711294FADF8E7951F4DE6CA56B58 "
893 "194.109.206.212:80 7EA6 EAD6 FD83 083C 538F 4403 8BBF A077 587D D755",
894 "Tonga orport=443 bridge no-v2 82.94.251.206:80 "
895 "4A0C CD2D DC79 9508 3D73 F5D6 6710 0C8A 5831 F16D",
896 "ides orport=9090 no-v2 v3ident=27B6B5996C426270A5C95488AA5BCEB6BCC86956 "
897 "216.224.124.114:9030 F397 038A DC51 3361 35E7 B80B D99C A384 4360 292B",
898 "gabelmoo orport=443 no-v2 "
899 "v3ident=81349FC1F2DBA2C2C11B45CB9706637D480AB913 "
900 "141.13.4.202:80 6833 3D07 61BC F397 A587 A0C0 B963 E4A9 E99E C4D3",
901 "dannenberg orport=443 no-v2 "
902 "v3ident=585769C78764D58426B8B52B6651A5A71137189A "
903 "213.73.91.31:80 7BE6 83E6 5D48 1413 21C5 ED92 F075 C553 64AC 7123",
904 NULL
906 for (i=0; dirservers[i]; i++) {
907 if (parse_dir_server_line(dirservers[i], type, 0)<0) {
908 log_err(LD_BUG, "Couldn't parse internal dirserver line %s",
909 dirservers[i]);
914 /** Look at all the config options for using alternate directory
915 * authorities, and make sure none of them are broken. Also, warn the
916 * user if we changed any dangerous ones.
918 static int
919 validate_dir_authorities(or_options_t *options, or_options_t *old_options)
921 config_line_t *cl;
923 if (options->DirServers &&
924 (options->AlternateDirAuthority || options->AlternateBridgeAuthority ||
925 options->AlternateHSAuthority)) {
926 log_warn(LD_CONFIG,
927 "You cannot set both DirServers and Alternate*Authority.");
928 return -1;
931 /* do we want to complain to the user about being partitionable? */
932 if ((options->DirServers &&
933 (!old_options ||
934 !config_lines_eq(options->DirServers, old_options->DirServers))) ||
935 (options->AlternateDirAuthority &&
936 (!old_options ||
937 !config_lines_eq(options->AlternateDirAuthority,
938 old_options->AlternateDirAuthority)))) {
939 log_warn(LD_CONFIG,
940 "You have used DirServer or AlternateDirAuthority to "
941 "specify alternate directory authorities in "
942 "your configuration. This is potentially dangerous: it can "
943 "make you look different from all other Tor users, and hurt "
944 "your anonymity. Even if you've specified the same "
945 "authorities as Tor uses by default, the defaults could "
946 "change in the future. Be sure you know what you're doing.");
949 /* Now go through the four ways you can configure an alternate
950 * set of directory authorities, and make sure none are broken. */
951 for (cl = options->DirServers; cl; cl = cl->next)
952 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
953 return -1;
954 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
955 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
956 return -1;
957 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
958 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
959 return -1;
960 for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
961 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
962 return -1;
963 return 0;
966 /** Look at all the config options and assign new dir authorities
967 * as appropriate.
969 static int
970 consider_adding_dir_authorities(or_options_t *options,
971 or_options_t *old_options)
973 config_line_t *cl;
974 int need_to_update =
975 !smartlist_len(router_get_trusted_dir_servers()) || !old_options ||
976 !config_lines_eq(options->DirServers, old_options->DirServers) ||
977 !config_lines_eq(options->AlternateBridgeAuthority,
978 old_options->AlternateBridgeAuthority) ||
979 !config_lines_eq(options->AlternateDirAuthority,
980 old_options->AlternateDirAuthority) ||
981 !config_lines_eq(options->AlternateHSAuthority,
982 old_options->AlternateHSAuthority);
984 if (!need_to_update)
985 return 0; /* all done */
987 /* Start from a clean slate. */
988 clear_trusted_dir_servers();
990 if (!options->DirServers) {
991 /* then we may want some of the defaults */
992 authority_type_t type = NO_AUTHORITY;
993 if (!options->AlternateBridgeAuthority)
994 type |= BRIDGE_AUTHORITY;
995 if (!options->AlternateDirAuthority)
996 type |= V1_AUTHORITY | V2_AUTHORITY | V3_AUTHORITY;
997 if (!options->AlternateHSAuthority)
998 type |= HIDSERV_AUTHORITY;
999 add_default_trusted_dir_authorities(type);
1002 for (cl = options->DirServers; cl; cl = cl->next)
1003 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1004 return -1;
1005 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
1006 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1007 return -1;
1008 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
1009 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1010 return -1;
1011 for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
1012 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1013 return -1;
1014 return 0;
1017 /** Fetch the active option list, and take actions based on it. All of the
1018 * things we do should survive being done repeatedly. If present,
1019 * <b>old_options</b> contains the previous value of the options.
1021 * Return 0 if all goes well, return -1 if things went badly.
1023 static int
1024 options_act_reversible(or_options_t *old_options, char **msg)
1026 smartlist_t *new_listeners = smartlist_create();
1027 smartlist_t *replaced_listeners = smartlist_create();
1028 static int libevent_initialized = 0;
1029 or_options_t *options = get_options();
1030 int running_tor = options->command == CMD_RUN_TOR;
1031 int set_conn_limit = 0;
1032 int r = -1;
1033 int logs_marked = 0;
1035 /* Daemonize _first_, since we only want to open most of this stuff in
1036 * the subprocess. Libevent bases can't be reliably inherited across
1037 * processes. */
1038 if (running_tor && options->RunAsDaemon) {
1039 /* No need to roll back, since you can't change the value. */
1040 start_daemon();
1043 #ifndef HAVE_SYS_UN_H
1044 if (options->ControlSocket) {
1045 *msg = tor_strdup("Unix domain sockets (ControlSocket) not supported"
1046 " on this OS/with this build.");
1047 goto rollback;
1049 #endif
1051 if (running_tor) {
1052 /* We need to set the connection limit before we can open the listeners. */
1053 if (set_max_file_descriptors((unsigned)options->ConnLimit,
1054 &options->_ConnLimit) < 0) {
1055 *msg = tor_strdup("Problem with ConnLimit value. See logs for details.");
1056 goto rollback;
1058 set_conn_limit = 1;
1060 /* Set up libevent. (We need to do this before we can register the
1061 * listeners as listeners.) */
1062 if (running_tor && !libevent_initialized) {
1063 init_libevent();
1064 libevent_initialized = 1;
1067 /* Launch the listeners. (We do this before we setuid, so we can bind to
1068 * ports under 1024.) */
1069 if (retry_all_listeners(replaced_listeners, new_listeners) < 0) {
1070 *msg = tor_strdup("Failed to bind one of the listener ports.");
1071 goto rollback;
1075 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
1076 /* Open /dev/pf before dropping privileges. */
1077 if (options->TransPort) {
1078 if (get_pf_socket() < 0) {
1079 *msg = tor_strdup("Unable to open /dev/pf for transparent proxy.");
1080 goto rollback;
1083 #endif
1085 /* Setuid/setgid as appropriate */
1086 if (options->User || options->Group) {
1087 /* XXXX021 We should only do this the first time through, not on
1088 * every setconf. */
1089 if (switch_id(options->User, options->Group) != 0) {
1090 /* No need to roll back, since you can't change the value. */
1091 *msg = tor_strdup("Problem with User or Group value. "
1092 "See logs for details.");
1093 goto done;
1097 /* Ensure data directory is private; create if possible. */
1098 if (check_private_dir(options->DataDirectory,
1099 running_tor ? CPD_CREATE : CPD_CHECK)<0) {
1100 char buf[1024];
1101 int tmp = tor_snprintf(buf, sizeof(buf),
1102 "Couldn't access/create private data directory \"%s\"",
1103 options->DataDirectory);
1104 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1105 goto done;
1106 /* No need to roll back, since you can't change the value. */
1109 if (directory_caches_v2_dir_info(options)) {
1110 size_t len = strlen(options->DataDirectory)+32;
1111 char *fn = tor_malloc(len);
1112 tor_snprintf(fn, len, "%s"PATH_SEPARATOR"cached-status",
1113 options->DataDirectory);
1114 if (check_private_dir(fn, running_tor ? CPD_CREATE : CPD_CHECK) < 0) {
1115 char buf[1024];
1116 int tmp = tor_snprintf(buf, sizeof(buf),
1117 "Couldn't access/create private data directory \"%s\"", fn);
1118 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1119 tor_free(fn);
1120 goto done;
1122 tor_free(fn);
1125 /* Bail out at this point if we're not going to be a client or server:
1126 * we don't run Tor itself. */
1127 if (!running_tor)
1128 goto commit;
1130 mark_logs_temp(); /* Close current logs once new logs are open. */
1131 logs_marked = 1;
1132 if (options_init_logs(options, 0)<0) { /* Configure the log(s) */
1133 *msg = tor_strdup("Failed to init Log options. See logs for details.");
1134 goto rollback;
1137 commit:
1138 r = 0;
1139 if (logs_marked) {
1140 log_severity_list_t *severity =
1141 tor_malloc_zero(sizeof(log_severity_list_t));
1142 close_temp_logs();
1143 add_callback_log(severity, control_event_logmsg);
1144 control_adjust_event_log_severity();
1145 tor_free(severity);
1147 SMARTLIST_FOREACH(replaced_listeners, connection_t *, conn,
1149 log_notice(LD_NET, "Closing old %s on %s:%d",
1150 conn_type_to_string(conn->type), conn->address, conn->port);
1151 connection_close_immediate(conn);
1152 connection_mark_for_close(conn);
1154 goto done;
1156 rollback:
1157 r = -1;
1158 tor_assert(*msg);
1160 if (logs_marked) {
1161 rollback_log_changes();
1162 control_adjust_event_log_severity();
1165 if (set_conn_limit && old_options)
1166 set_max_file_descriptors((unsigned)old_options->ConnLimit,
1167 &options->_ConnLimit);
1169 SMARTLIST_FOREACH(new_listeners, connection_t *, conn,
1171 log_notice(LD_NET, "Closing partially-constructed listener %s on %s:%d",
1172 conn_type_to_string(conn->type), conn->address, conn->port);
1173 connection_close_immediate(conn);
1174 connection_mark_for_close(conn);
1177 done:
1178 smartlist_free(new_listeners);
1179 smartlist_free(replaced_listeners);
1180 return r;
1183 /** DOCDOC */
1185 options_need_geoip_info(or_options_t *options, const char **reason_out)
1187 int bridge_usage =
1188 options->BridgeRelay && options->BridgeRecordUsageByCountry;
1189 int routerset_usage =
1190 routerset_needs_geoip(options->EntryNodes) ||
1191 routerset_needs_geoip(options->ExitNodes) ||
1192 routerset_needs_geoip(options->ExcludeExitNodes) ||
1193 routerset_needs_geoip(options->ExcludeNodes);
1195 if (routerset_usage && reason_out) {
1196 *reason_out = "We've been configured to use (or avoid) nodes in certain "
1197 "contries, and we need GEOIP information to figure out which ones they "
1198 "are.";
1199 } else if (bridge_usage && reason_out) {
1200 *reason_out = "We've been configured to see which countries can access "
1201 "us as a bridge, and we need GEOIP information to tell which countries "
1202 "clients are in.";
1204 return bridge_usage || routerset_usage;
1207 /** Fetch the active option list, and take actions based on it. All of the
1208 * things we do should survive being done repeatedly. If present,
1209 * <b>old_options</b> contains the previous value of the options.
1211 * Return 0 if all goes well, return -1 if it's time to die.
1213 * Note: We haven't moved all the "act on new configuration" logic
1214 * here yet. Some is still in do_hup() and other places.
1216 static int
1217 options_act(or_options_t *old_options)
1219 config_line_t *cl;
1220 or_options_t *options = get_options();
1221 int running_tor = options->command == CMD_RUN_TOR;
1222 char *msg;
1224 if (running_tor && !have_lockfile()) {
1225 if (try_locking(options, 1) < 0)
1226 return -1;
1229 if (consider_adding_dir_authorities(options, old_options) < 0)
1230 return -1;
1232 if (options->Bridges) {
1233 clear_bridge_list();
1234 for (cl = options->Bridges; cl; cl = cl->next) {
1235 if (parse_bridge_line(cl->value, 0)<0) {
1236 log_warn(LD_BUG,
1237 "Previously validated Bridge line could not be added!");
1238 return -1;
1243 if (running_tor && rend_config_services(options, 0)<0) {
1244 log_warn(LD_BUG,
1245 "Previously validated hidden services line could not be added!");
1246 return -1;
1249 if (running_tor && rend_parse_service_authorization(options, 0) < 0) {
1250 log_warn(LD_BUG, "Previously validated client authorization for "
1251 "hidden services could not be added!");
1252 return -1;
1255 /* Load state */
1256 if (! global_state && running_tor) {
1257 if (or_state_load())
1258 return -1;
1259 rep_hist_load_mtbf_data(time(NULL));
1262 /* Bail out at this point if we're not going to be a client or server:
1263 * we want to not fork, and to log stuff to stderr. */
1264 if (!running_tor)
1265 return 0;
1268 smartlist_t *sl = smartlist_create();
1269 char *errmsg = NULL;
1270 for (cl = options->RedirectExit; cl; cl = cl->next) {
1271 if (parse_redirect_line(sl, cl, &errmsg)<0) {
1272 log_warn(LD_CONFIG, "%s", errmsg);
1273 tor_free(errmsg);
1274 SMARTLIST_FOREACH(sl, exit_redirect_t *, er, tor_free(er));
1275 smartlist_free(sl);
1276 return -1;
1279 set_exit_redirects(sl);
1282 /* Finish backgrounding the process */
1283 if (running_tor && options->RunAsDaemon) {
1284 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
1285 finish_daemon(options->DataDirectory);
1288 /* Write our pid to the pid file. If we do not have write permissions we
1289 * will log a warning */
1290 if (running_tor && options->PidFile)
1291 write_pidfile(options->PidFile);
1293 /* Register addressmap directives */
1294 config_register_addressmaps(options);
1295 parse_virtual_addr_network(options->VirtualAddrNetwork, 0, &msg);
1297 /* Update address policies. */
1298 if (policies_parse_from_options(options) < 0) {
1299 /* This should be impossible, but let's be sure. */
1300 log_warn(LD_BUG,"Error parsing already-validated policy options.");
1301 return -1;
1304 if (init_cookie_authentication(options->CookieAuthentication) < 0) {
1305 log_warn(LD_CONFIG,"Error creating cookie authentication file.");
1306 return -1;
1309 /* reload keys as needed for rendezvous services. */
1310 if (rend_service_load_keys()<0) {
1311 log_warn(LD_GENERAL,"Error loading rendezvous service keys");
1312 return -1;
1315 /* Set up accounting */
1316 if (accounting_parse_options(options, 0)<0) {
1317 log_warn(LD_CONFIG,"Error in accounting options");
1318 return -1;
1320 if (accounting_is_enabled(options))
1321 configure_accounting(time(NULL));
1323 /* Check for transitions that need action. */
1324 if (old_options) {
1325 if (options->UseEntryGuards && !old_options->UseEntryGuards) {
1326 log_info(LD_CIRC,
1327 "Switching to entry guards; abandoning previous circuits");
1328 circuit_mark_all_unused_circs();
1329 circuit_expire_all_dirty_circs();
1332 if (options_transition_affects_workers(old_options, options)) {
1333 log_info(LD_GENERAL,
1334 "Worker-related options changed. Rotating workers.");
1335 if (server_mode(options) && !server_mode(old_options)) {
1336 if (init_keys() < 0) {
1337 log_warn(LD_BUG,"Error initializing keys; exiting");
1338 return -1;
1340 ip_address_changed(0);
1341 if (has_completed_circuit || !any_predicted_circuits(time(NULL)))
1342 inform_testing_reachability();
1344 cpuworkers_rotate();
1345 if (dns_reset())
1346 return -1;
1347 } else {
1348 if (dns_reset())
1349 return -1;
1352 if (options->V3AuthoritativeDir && !old_options->V3AuthoritativeDir)
1353 init_keys();
1356 /* Maybe load geoip file */
1357 if (options->GeoIPFile &&
1358 ((!old_options || !opt_streq(old_options->GeoIPFile, options->GeoIPFile))
1359 || !geoip_is_loaded())) {
1360 /** XXXX021 Don't use this "<default>" junk; make our filename options
1361 * understand prefixes somehow. -NM */
1362 /** XXXX021 Reload GeoIPFile on SIGHUP. -NM */
1363 char *actual_fname = tor_strdup(options->GeoIPFile);
1364 #ifdef WIN32
1365 if (!strcmp(actual_fname, "<default>")) {
1366 const char *conf_root = get_windows_conf_root();
1367 size_t len = strlen(conf_root)+16;
1368 tor_free(actual_fname);
1369 actual_fname = tor_malloc(len+1);
1370 tor_snprintf(actual_fname, len, "%s\\geoip", conf_root);
1372 #endif
1373 geoip_load_file(actual_fname, options);
1374 tor_free(actual_fname);
1376 /* XXXX Would iterating through all option_var's routersets be better? */
1377 if (options->EntryNodes)
1378 routerset_refresh_countries(options->EntryNodes);
1379 if (options->ExitNodes)
1380 routerset_refresh_countries(options->ExitNodes);
1381 if (options->ExcludeNodes)
1382 routerset_refresh_countries(options->ExcludeNodes);
1383 if (options->ExcludeExitNodes)
1384 routerset_refresh_countries(options->ExcludeExitNodes);
1385 routerlist_refresh_countries();
1387 /* Check if we need to parse and add the EntryNodes config option. */
1388 if (options->EntryNodes &&
1389 (!old_options ||
1390 (!routerset_equal(old_options->EntryNodes,options->EntryNodes))))
1391 entry_nodes_should_be_added();
1393 /* Since our options changed, we might need to regenerate and upload our
1394 * server descriptor.
1396 if (!old_options ||
1397 options_transition_affects_descriptor(old_options, options))
1398 mark_my_descriptor_dirty();
1400 /* We may need to reschedule some directory stuff if our status changed. */
1401 if (old_options) {
1402 if (authdir_mode_v3(options) && !authdir_mode_v3(old_options))
1403 dirvote_recalculate_timing(options, time(NULL));
1404 if (!bool_eq(directory_fetches_dir_info_early(options),
1405 directory_fetches_dir_info_early(old_options)) ||
1406 !bool_eq(directory_fetches_dir_info_later(options),
1407 directory_fetches_dir_info_later(old_options))) {
1408 /* Make sure update_router_have_min_dir_info gets called. */
1409 router_dir_info_changed();
1410 /* We might need to download a new consensus status later or sooner than
1411 * we had expected. */
1412 update_consensus_networkstatus_fetch_time(time(NULL));
1416 return 0;
1420 * Functions to parse config options
1423 /** If <b>option</b> is an official abbreviation for a longer option,
1424 * return the longer option. Otherwise return <b>option</b>.
1425 * If <b>command_line</b> is set, apply all abbreviations. Otherwise, only
1426 * apply abbreviations that work for the config file and the command line.
1427 * If <b>warn_obsolete</b> is set, warn about deprecated names. */
1428 static const char *
1429 expand_abbrev(config_format_t *fmt, const char *option, int command_line,
1430 int warn_obsolete)
1432 int i;
1433 if (! fmt->abbrevs)
1434 return option;
1435 for (i=0; fmt->abbrevs[i].abbreviated; ++i) {
1436 /* Abbreviations are casei. */
1437 if (!strcasecmp(option,fmt->abbrevs[i].abbreviated) &&
1438 (command_line || !fmt->abbrevs[i].commandline_only)) {
1439 if (warn_obsolete && fmt->abbrevs[i].warn) {
1440 log_warn(LD_CONFIG,
1441 "The configuration option '%s' is deprecated; "
1442 "use '%s' instead.",
1443 fmt->abbrevs[i].abbreviated,
1444 fmt->abbrevs[i].full);
1446 return fmt->abbrevs[i].full;
1449 return option;
1452 /** Helper: Read a list of configuration options from the command line.
1453 * If successful, put them in *<b>result</b> and return 0, and return
1454 * -1 and leave *<b>result</b> alone. */
1455 static int
1456 config_get_commandlines(int argc, char **argv, config_line_t **result)
1458 config_line_t *front = NULL;
1459 config_line_t **new = &front;
1460 char *s;
1461 int i = 1;
1463 while (i < argc) {
1464 if (!strcmp(argv[i],"-f") ||
1465 !strcmp(argv[i],"--hash-password")) {
1466 i += 2; /* command-line option with argument. ignore them. */
1467 continue;
1468 } else if (!strcmp(argv[i],"--list-fingerprint") ||
1469 !strcmp(argv[i],"--verify-config") ||
1470 !strcmp(argv[i],"--ignore-missing-torrc") ||
1471 !strcmp(argv[i],"--quiet") ||
1472 !strcmp(argv[i],"--hush")) {
1473 i += 1; /* command-line option. ignore it. */
1474 continue;
1475 } else if (!strcmp(argv[i],"--nt-service") ||
1476 !strcmp(argv[i],"-nt-service")) {
1477 i += 1;
1478 continue;
1481 if (i == argc-1) {
1482 log_warn(LD_CONFIG,"Command-line option '%s' with no value. Failing.",
1483 argv[i]);
1484 config_free_lines(front);
1485 return -1;
1488 *new = tor_malloc_zero(sizeof(config_line_t));
1489 s = argv[i];
1491 while (*s == '-')
1492 s++;
1494 (*new)->key = tor_strdup(expand_abbrev(&options_format, s, 1, 1));
1495 (*new)->value = tor_strdup(argv[i+1]);
1496 (*new)->next = NULL;
1497 log(LOG_DEBUG, LD_CONFIG, "Commandline: parsed keyword '%s', value '%s'",
1498 (*new)->key, (*new)->value);
1500 new = &((*new)->next);
1501 i += 2;
1503 *result = front;
1504 return 0;
1507 /** Helper: allocate a new configuration option mapping 'key' to 'val',
1508 * append it to *<b>lst</b>. */
1509 static void
1510 config_line_append(config_line_t **lst,
1511 const char *key,
1512 const char *val)
1514 config_line_t *newline;
1516 newline = tor_malloc(sizeof(config_line_t));
1517 newline->key = tor_strdup(key);
1518 newline->value = tor_strdup(val);
1519 newline->next = NULL;
1520 while (*lst)
1521 lst = &((*lst)->next);
1523 (*lst) = newline;
1526 /** Helper: parse the config string and strdup into key/value
1527 * strings. Set *result to the list, or NULL if parsing the string
1528 * failed. Return 0 on success, -1 on failure. Warn and ignore any
1529 * misformatted lines. */
1531 config_get_lines(const char *string, config_line_t **result)
1533 config_line_t *list = NULL, **next;
1534 char *k, *v;
1536 next = &list;
1537 do {
1538 k = v = NULL;
1539 string = parse_config_line_from_str(string, &k, &v);
1540 if (!string) {
1541 config_free_lines(list);
1542 tor_free(k);
1543 tor_free(v);
1544 return -1;
1546 if (k && v) {
1547 /* This list can get long, so we keep a pointer to the end of it
1548 * rather than using config_line_append over and over and getting
1549 * n^2 performance. */
1550 *next = tor_malloc(sizeof(config_line_t));
1551 (*next)->key = k;
1552 (*next)->value = v;
1553 (*next)->next = NULL;
1554 next = &((*next)->next);
1555 } else {
1556 tor_free(k);
1557 tor_free(v);
1559 } while (*string);
1561 *result = list;
1562 return 0;
1566 * Free all the configuration lines on the linked list <b>front</b>.
1568 void
1569 config_free_lines(config_line_t *front)
1571 config_line_t *tmp;
1573 while (front) {
1574 tmp = front;
1575 front = tmp->next;
1577 tor_free(tmp->key);
1578 tor_free(tmp->value);
1579 tor_free(tmp);
1583 /** Return the description for a given configuration variable, or NULL if no
1584 * description exists. */
1585 static const char *
1586 config_find_description(config_format_t *fmt, const char *name)
1588 int i;
1589 for (i=0; fmt->descriptions[i].name; ++i) {
1590 if (!strcasecmp(name, fmt->descriptions[i].name))
1591 return fmt->descriptions[i].description;
1593 return NULL;
1596 /** If <b>key</b> is a configuration option, return the corresponding
1597 * config_var_t. Otherwise, if <b>key</b> is a non-standard abbreviation,
1598 * warn, and return the corresponding config_var_t. Otherwise return NULL.
1600 static config_var_t *
1601 config_find_option(config_format_t *fmt, const char *key)
1603 int i;
1604 size_t keylen = strlen(key);
1605 if (!keylen)
1606 return NULL; /* if they say "--" on the commandline, it's not an option */
1607 /* First, check for an exact (case-insensitive) match */
1608 for (i=0; fmt->vars[i].name; ++i) {
1609 if (!strcasecmp(key, fmt->vars[i].name)) {
1610 return &fmt->vars[i];
1613 /* If none, check for an abbreviated match */
1614 for (i=0; fmt->vars[i].name; ++i) {
1615 if (!strncasecmp(key, fmt->vars[i].name, keylen)) {
1616 log_warn(LD_CONFIG, "The abbreviation '%s' is deprecated. "
1617 "Please use '%s' instead",
1618 key, fmt->vars[i].name);
1619 return &fmt->vars[i];
1622 /* Okay, unrecognized option */
1623 return NULL;
1627 * Functions to assign config options.
1630 /** <b>c</b>-\>key is known to be a real key. Update <b>options</b>
1631 * with <b>c</b>-\>value and return 0, or return -1 if bad value.
1633 * Called from config_assign_line() and option_reset().
1635 static int
1636 config_assign_value(config_format_t *fmt, or_options_t *options,
1637 config_line_t *c, char **msg)
1639 int i, r, ok;
1640 char buf[1024];
1641 config_var_t *var;
1642 void *lvalue;
1644 CHECK(fmt, options);
1646 var = config_find_option(fmt, c->key);
1647 tor_assert(var);
1649 lvalue = STRUCT_VAR_P(options, var->var_offset);
1651 switch (var->type) {
1653 case CONFIG_TYPE_UINT:
1654 i = (int)tor_parse_long(c->value, 10, 0, INT_MAX, &ok, NULL);
1655 if (!ok) {
1656 r = tor_snprintf(buf, sizeof(buf),
1657 "Int keyword '%s %s' is malformed or out of bounds.",
1658 c->key, c->value);
1659 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1660 return -1;
1662 *(int *)lvalue = i;
1663 break;
1665 case CONFIG_TYPE_INTERVAL: {
1666 i = config_parse_interval(c->value, &ok);
1667 if (!ok) {
1668 r = tor_snprintf(buf, sizeof(buf),
1669 "Interval '%s %s' is malformed or out of bounds.",
1670 c->key, c->value);
1671 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1672 return -1;
1674 *(int *)lvalue = i;
1675 break;
1678 case CONFIG_TYPE_MEMUNIT: {
1679 uint64_t u64 = config_parse_memunit(c->value, &ok);
1680 if (!ok) {
1681 r = tor_snprintf(buf, sizeof(buf),
1682 "Value '%s %s' is malformed or out of bounds.",
1683 c->key, c->value);
1684 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1685 return -1;
1687 *(uint64_t *)lvalue = u64;
1688 break;
1691 case CONFIG_TYPE_BOOL:
1692 i = (int)tor_parse_long(c->value, 10, 0, 1, &ok, NULL);
1693 if (!ok) {
1694 r = tor_snprintf(buf, sizeof(buf),
1695 "Boolean '%s %s' expects 0 or 1.",
1696 c->key, c->value);
1697 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1698 return -1;
1700 *(int *)lvalue = i;
1701 break;
1703 case CONFIG_TYPE_STRING:
1704 case CONFIG_TYPE_FILENAME:
1705 tor_free(*(char **)lvalue);
1706 *(char **)lvalue = tor_strdup(c->value);
1707 break;
1709 case CONFIG_TYPE_DOUBLE:
1710 *(double *)lvalue = atof(c->value);
1711 break;
1713 case CONFIG_TYPE_ISOTIME:
1714 if (parse_iso_time(c->value, (time_t *)lvalue)) {
1715 r = tor_snprintf(buf, sizeof(buf),
1716 "Invalid time '%s' for keyword '%s'", c->value, c->key);
1717 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1718 return -1;
1720 break;
1722 case CONFIG_TYPE_ROUTERSET:
1723 if (*(routerset_t**)lvalue) {
1724 routerset_free(*(routerset_t**)lvalue);
1726 *(routerset_t**)lvalue = routerset_new();
1727 if (routerset_parse(*(routerset_t**)lvalue, c->value, c->key)<0) {
1728 tor_snprintf(buf, sizeof(buf), "Invalid exit list '%s' for option '%s'",
1729 c->value, c->key);
1730 *msg = tor_strdup(buf);
1731 return -1;
1733 break;
1735 case CONFIG_TYPE_CSV:
1736 if (*(smartlist_t**)lvalue) {
1737 SMARTLIST_FOREACH(*(smartlist_t**)lvalue, char *, cp, tor_free(cp));
1738 smartlist_clear(*(smartlist_t**)lvalue);
1739 } else {
1740 *(smartlist_t**)lvalue = smartlist_create();
1743 smartlist_split_string(*(smartlist_t**)lvalue, c->value, ",",
1744 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1745 break;
1747 case CONFIG_TYPE_LINELIST:
1748 case CONFIG_TYPE_LINELIST_S:
1749 config_line_append((config_line_t**)lvalue, c->key, c->value);
1750 break;
1751 case CONFIG_TYPE_OBSOLETE:
1752 log_warn(LD_CONFIG, "Skipping obsolete configuration option '%s'", c->key);
1753 break;
1754 case CONFIG_TYPE_LINELIST_V:
1755 r = tor_snprintf(buf, sizeof(buf),
1756 "You may not provide a value for virtual option '%s'", c->key);
1757 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1758 return -1;
1759 default:
1760 tor_assert(0);
1761 break;
1763 return 0;
1766 /** If <b>c</b> is a syntactically valid configuration line, update
1767 * <b>options</b> with its value and return 0. Otherwise return -1 for bad
1768 * key, -2 for bad value.
1770 * If <b>clear_first</b> is set, clear the value first. Then if
1771 * <b>use_defaults</b> is set, set the value to the default.
1773 * Called from config_assign().
1775 static int
1776 config_assign_line(config_format_t *fmt, or_options_t *options,
1777 config_line_t *c, int use_defaults,
1778 int clear_first, char **msg)
1780 config_var_t *var;
1782 CHECK(fmt, options);
1784 var = config_find_option(fmt, c->key);
1785 if (!var) {
1786 if (fmt->extra) {
1787 void *lvalue = STRUCT_VAR_P(options, fmt->extra->var_offset);
1788 log_info(LD_CONFIG,
1789 "Found unrecognized option '%s'; saving it.", c->key);
1790 config_line_append((config_line_t**)lvalue, c->key, c->value);
1791 return 0;
1792 } else {
1793 char buf[1024];
1794 int tmp = tor_snprintf(buf, sizeof(buf),
1795 "Unknown option '%s'. Failing.", c->key);
1796 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1797 return -1;
1800 /* Put keyword into canonical case. */
1801 if (strcmp(var->name, c->key)) {
1802 tor_free(c->key);
1803 c->key = tor_strdup(var->name);
1806 if (!strlen(c->value)) {
1807 /* reset or clear it, then return */
1808 if (!clear_first) {
1809 if (var->type == CONFIG_TYPE_LINELIST ||
1810 var->type == CONFIG_TYPE_LINELIST_S) {
1811 /* We got an empty linelist from the torrc or commandline.
1812 As a special case, call this an error. Warn and ignore. */
1813 log_warn(LD_CONFIG,
1814 "Linelist option '%s' has no value. Skipping.", c->key);
1815 } else { /* not already cleared */
1816 option_reset(fmt, options, var, use_defaults);
1819 return 0;
1822 if (config_assign_value(fmt, options, c, msg) < 0)
1823 return -2;
1824 return 0;
1827 /** Restore the option named <b>key</b> in options to its default value.
1828 * Called from config_assign(). */
1829 static void
1830 config_reset_line(config_format_t *fmt, or_options_t *options,
1831 const char *key, int use_defaults)
1833 config_var_t *var;
1835 CHECK(fmt, options);
1837 var = config_find_option(fmt, key);
1838 if (!var)
1839 return; /* give error on next pass. */
1841 option_reset(fmt, options, var, use_defaults);
1844 /** Return true iff key is a valid configuration option. */
1846 option_is_recognized(const char *key)
1848 config_var_t *var = config_find_option(&options_format, key);
1849 return (var != NULL);
1852 /** Return the canonical name of a configuration option, or NULL
1853 * if no such option exists. */
1854 const char *
1855 option_get_canonical_name(const char *key)
1857 config_var_t *var = config_find_option(&options_format, key);
1858 return var ? var->name : NULL;
1861 /** Return a canonicalized list of the options assigned for key.
1863 config_line_t *
1864 option_get_assignment(or_options_t *options, const char *key)
1866 return get_assigned_option(&options_format, options, key, 1);
1869 /** Return true iff value needs to be quoted and escaped to be used in
1870 * a configuration file. */
1871 static int
1872 config_value_needs_escape(const char *value)
1874 if (*value == '\"')
1875 return 1;
1876 while (*value) {
1877 switch (*value)
1879 case '\r':
1880 case '\n':
1881 case '#':
1882 /* Note: quotes and backspaces need special handling when we are using
1883 * quotes, not otherwise, so they don't trigger escaping on their
1884 * own. */
1885 return 1;
1886 default:
1887 if (!TOR_ISPRINT(*value))
1888 return 1;
1890 ++value;
1892 return 0;
1895 /** Return a newly allocated deep copy of the lines in <b>inp</b>. */
1896 static config_line_t *
1897 config_lines_dup(const config_line_t *inp)
1899 config_line_t *result = NULL;
1900 config_line_t **next_out = &result;
1901 while (inp) {
1902 *next_out = tor_malloc(sizeof(config_line_t));
1903 (*next_out)->key = tor_strdup(inp->key);
1904 (*next_out)->value = tor_strdup(inp->value);
1905 inp = inp->next;
1906 next_out = &((*next_out)->next);
1908 (*next_out) = NULL;
1909 return result;
1912 /** Return newly allocated line or lines corresponding to <b>key</b> in the
1913 * configuration <b>options</b>. If <b>escape_val</b> is true and a
1914 * value needs to be quoted before it's put in a config file, quote and
1915 * escape that value. Return NULL if no such key exists. */
1916 static config_line_t *
1917 get_assigned_option(config_format_t *fmt, or_options_t *options,
1918 const char *key, int escape_val)
1919 /* XXXX argument is options, but fmt is provided. Inconsistent. */
1921 config_var_t *var;
1922 const void *value;
1923 char buf[32];
1924 config_line_t *result;
1925 tor_assert(options && key);
1927 CHECK(fmt, options);
1929 var = config_find_option(fmt, key);
1930 if (!var) {
1931 log_warn(LD_CONFIG, "Unknown option '%s'. Failing.", key);
1932 return NULL;
1934 value = STRUCT_VAR_P(options, var->var_offset);
1936 result = tor_malloc_zero(sizeof(config_line_t));
1937 result->key = tor_strdup(var->name);
1938 switch (var->type)
1940 case CONFIG_TYPE_STRING:
1941 case CONFIG_TYPE_FILENAME:
1942 if (*(char**)value) {
1943 result->value = tor_strdup(*(char**)value);
1944 } else {
1945 tor_free(result->key);
1946 tor_free(result);
1947 return NULL;
1949 break;
1950 case CONFIG_TYPE_ISOTIME:
1951 if (*(time_t*)value) {
1952 result->value = tor_malloc(ISO_TIME_LEN+1);
1953 format_iso_time(result->value, *(time_t*)value);
1954 } else {
1955 tor_free(result->key);
1956 tor_free(result);
1958 escape_val = 0; /* Can't need escape. */
1959 break;
1960 case CONFIG_TYPE_INTERVAL:
1961 case CONFIG_TYPE_UINT:
1962 /* This means every or_options_t uint or bool element
1963 * needs to be an int. Not, say, a uint16_t or char. */
1964 tor_snprintf(buf, sizeof(buf), "%d", *(int*)value);
1965 result->value = tor_strdup(buf);
1966 escape_val = 0; /* Can't need escape. */
1967 break;
1968 case CONFIG_TYPE_MEMUNIT:
1969 tor_snprintf(buf, sizeof(buf), U64_FORMAT,
1970 U64_PRINTF_ARG(*(uint64_t*)value));
1971 result->value = tor_strdup(buf);
1972 escape_val = 0; /* Can't need escape. */
1973 break;
1974 case CONFIG_TYPE_DOUBLE:
1975 tor_snprintf(buf, sizeof(buf), "%f", *(double*)value);
1976 result->value = tor_strdup(buf);
1977 escape_val = 0; /* Can't need escape. */
1978 break;
1979 case CONFIG_TYPE_BOOL:
1980 result->value = tor_strdup(*(int*)value ? "1" : "0");
1981 escape_val = 0; /* Can't need escape. */
1982 break;
1983 case CONFIG_TYPE_ROUTERSET:
1984 result->value = routerset_to_string(*(routerset_t**)value);
1985 break;
1986 case CONFIG_TYPE_CSV:
1987 if (*(smartlist_t**)value)
1988 result->value =
1989 smartlist_join_strings(*(smartlist_t**)value, ",", 0, NULL);
1990 else
1991 result->value = tor_strdup("");
1992 break;
1993 case CONFIG_TYPE_OBSOLETE:
1994 log_warn(LD_CONFIG,
1995 "You asked me for the value of an obsolete config option '%s'.",
1996 key);
1997 tor_free(result->key);
1998 tor_free(result);
1999 return NULL;
2000 case CONFIG_TYPE_LINELIST_S:
2001 log_warn(LD_CONFIG,
2002 "Can't return context-sensitive '%s' on its own", key);
2003 tor_free(result->key);
2004 tor_free(result);
2005 return NULL;
2006 case CONFIG_TYPE_LINELIST:
2007 case CONFIG_TYPE_LINELIST_V:
2008 tor_free(result->key);
2009 tor_free(result);
2010 result = config_lines_dup(*(const config_line_t**)value);
2011 break;
2012 default:
2013 tor_free(result->key);
2014 tor_free(result);
2015 log_warn(LD_BUG,"Unknown type %d for known key '%s'",
2016 var->type, key);
2017 return NULL;
2020 if (escape_val) {
2021 config_line_t *line;
2022 for (line = result; line; line = line->next) {
2023 if (line->value && config_value_needs_escape(line->value)) {
2024 char *newval = esc_for_log(line->value);
2025 tor_free(line->value);
2026 line->value = newval;
2031 return result;
2034 /** Iterate through the linked list of requested options <b>list</b>.
2035 * For each item, convert as appropriate and assign to <b>options</b>.
2036 * If an item is unrecognized, set *msg and return -1 immediately,
2037 * else return 0 for success.
2039 * If <b>clear_first</b>, interpret config options as replacing (not
2040 * extending) their previous values. If <b>clear_first</b> is set,
2041 * then <b>use_defaults</b> to decide if you set to defaults after
2042 * clearing, or make the value 0 or NULL.
2044 * Here are the use cases:
2045 * 1. A non-empty AllowInvalid line in your torrc. Appends to current
2046 * if linelist, replaces current if csv.
2047 * 2. An empty AllowInvalid line in your torrc. Should clear it.
2048 * 3. "RESETCONF AllowInvalid" sets it to default.
2049 * 4. "SETCONF AllowInvalid" makes it NULL.
2050 * 5. "SETCONF AllowInvalid=foo" clears it and sets it to "foo".
2052 * Use_defaults Clear_first
2053 * 0 0 "append"
2054 * 1 0 undefined, don't use
2055 * 0 1 "set to null first"
2056 * 1 1 "set to defaults first"
2057 * Return 0 on success, -1 on bad key, -2 on bad value.
2059 * As an additional special case, if a LINELIST config option has
2060 * no value and clear_first is 0, then warn and ignore it.
2064 There are three call cases for config_assign() currently.
2066 Case one: Torrc entry
2067 options_init_from_torrc() calls config_assign(0, 0)
2068 calls config_assign_line(0, 0).
2069 if value is empty, calls option_reset(0) and returns.
2070 calls config_assign_value(), appends.
2072 Case two: setconf
2073 options_trial_assign() calls config_assign(0, 1)
2074 calls config_reset_line(0)
2075 calls option_reset(0)
2076 calls option_clear().
2077 calls config_assign_line(0, 1).
2078 if value is empty, returns.
2079 calls config_assign_value(), appends.
2081 Case three: resetconf
2082 options_trial_assign() calls config_assign(1, 1)
2083 calls config_reset_line(1)
2084 calls option_reset(1)
2085 calls option_clear().
2086 calls config_assign_value(default)
2087 calls config_assign_line(1, 1).
2088 returns.
2090 static int
2091 config_assign(config_format_t *fmt, void *options, config_line_t *list,
2092 int use_defaults, int clear_first, char **msg)
2094 config_line_t *p;
2096 CHECK(fmt, options);
2098 /* pass 1: normalize keys */
2099 for (p = list; p; p = p->next) {
2100 const char *full = expand_abbrev(fmt, p->key, 0, 1);
2101 if (strcmp(full,p->key)) {
2102 tor_free(p->key);
2103 p->key = tor_strdup(full);
2107 /* pass 2: if we're reading from a resetting source, clear all
2108 * mentioned config options, and maybe set to their defaults. */
2109 if (clear_first) {
2110 for (p = list; p; p = p->next)
2111 config_reset_line(fmt, options, p->key, use_defaults);
2114 /* pass 3: assign. */
2115 while (list) {
2116 int r;
2117 if ((r=config_assign_line(fmt, options, list, use_defaults,
2118 clear_first, msg)))
2119 return r;
2120 list = list->next;
2122 return 0;
2125 /** Try assigning <b>list</b> to the global options. You do this by duping
2126 * options, assigning list to the new one, then validating it. If it's
2127 * ok, then throw out the old one and stick with the new one. Else,
2128 * revert to old and return failure. Return SETOPT_OK on success, or
2129 * a setopt_err_t on failure.
2131 * If not success, point *<b>msg</b> to a newly allocated string describing
2132 * what went wrong.
2134 setopt_err_t
2135 options_trial_assign(config_line_t *list, int use_defaults,
2136 int clear_first, char **msg)
2138 int r;
2139 or_options_t *trial_options = options_dup(&options_format, get_options());
2141 if ((r=config_assign(&options_format, trial_options,
2142 list, use_defaults, clear_first, msg)) < 0) {
2143 config_free(&options_format, trial_options);
2144 return r;
2147 if (options_validate(get_options(), trial_options, 1, msg) < 0) {
2148 config_free(&options_format, trial_options);
2149 return SETOPT_ERR_PARSE; /*XXX021 make this separate. */
2152 if (options_transition_allowed(get_options(), trial_options, msg) < 0) {
2153 config_free(&options_format, trial_options);
2154 return SETOPT_ERR_TRANSITION;
2157 if (set_options(trial_options, msg)<0) {
2158 config_free(&options_format, trial_options);
2159 return SETOPT_ERR_SETTING;
2162 /* we liked it. put it in place. */
2163 return SETOPT_OK;
2166 /** Reset config option <b>var</b> to 0, 0.0, NULL, or the equivalent.
2167 * Called from option_reset() and config_free(). */
2168 static void
2169 option_clear(config_format_t *fmt, or_options_t *options, config_var_t *var)
2171 void *lvalue = STRUCT_VAR_P(options, var->var_offset);
2172 (void)fmt; /* unused */
2173 switch (var->type) {
2174 case CONFIG_TYPE_STRING:
2175 case CONFIG_TYPE_FILENAME:
2176 tor_free(*(char**)lvalue);
2177 break;
2178 case CONFIG_TYPE_DOUBLE:
2179 *(double*)lvalue = 0.0;
2180 break;
2181 case CONFIG_TYPE_ISOTIME:
2182 *(time_t*)lvalue = 0;
2183 case CONFIG_TYPE_INTERVAL:
2184 case CONFIG_TYPE_UINT:
2185 case CONFIG_TYPE_BOOL:
2186 *(int*)lvalue = 0;
2187 break;
2188 case CONFIG_TYPE_MEMUNIT:
2189 *(uint64_t*)lvalue = 0;
2190 break;
2191 case CONFIG_TYPE_ROUTERSET:
2192 if (*(routerset_t**)lvalue) {
2193 routerset_free(*(routerset_t**)lvalue);
2194 *(routerset_t**)lvalue = NULL;
2196 case CONFIG_TYPE_CSV:
2197 if (*(smartlist_t**)lvalue) {
2198 SMARTLIST_FOREACH(*(smartlist_t **)lvalue, char *, cp, tor_free(cp));
2199 smartlist_free(*(smartlist_t **)lvalue);
2200 *(smartlist_t **)lvalue = NULL;
2202 break;
2203 case CONFIG_TYPE_LINELIST:
2204 case CONFIG_TYPE_LINELIST_S:
2205 config_free_lines(*(config_line_t **)lvalue);
2206 *(config_line_t **)lvalue = NULL;
2207 break;
2208 case CONFIG_TYPE_LINELIST_V:
2209 /* handled by linelist_s. */
2210 break;
2211 case CONFIG_TYPE_OBSOLETE:
2212 break;
2216 /** Clear the option indexed by <b>var</b> in <b>options</b>. Then if
2217 * <b>use_defaults</b>, set it to its default value.
2218 * Called by config_init() and option_reset_line() and option_assign_line(). */
2219 static void
2220 option_reset(config_format_t *fmt, or_options_t *options,
2221 config_var_t *var, int use_defaults)
2223 config_line_t *c;
2224 char *msg = NULL;
2225 CHECK(fmt, options);
2226 option_clear(fmt, options, var); /* clear it first */
2227 if (!use_defaults)
2228 return; /* all done */
2229 if (var->initvalue) {
2230 c = tor_malloc_zero(sizeof(config_line_t));
2231 c->key = tor_strdup(var->name);
2232 c->value = tor_strdup(var->initvalue);
2233 if (config_assign_value(fmt, options, c, &msg) < 0) {
2234 log_warn(LD_BUG, "Failed to assign default: %s", msg);
2235 tor_free(msg); /* if this happens it's a bug */
2237 config_free_lines(c);
2241 /** Print a usage message for tor. */
2242 static void
2243 print_usage(void)
2245 printf(
2246 "Copyright (c) 2001-2004, Roger Dingledine\n"
2247 "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
2248 "Copyright (c) 2007-2008, The Tor Project, Inc.\n\n"
2249 "tor -f <torrc> [args]\n"
2250 "See man page for options, or https://www.torproject.org/ for "
2251 "documentation.\n");
2254 /** Print all non-obsolete torrc options. */
2255 static void
2256 list_torrc_options(void)
2258 int i;
2259 smartlist_t *lines = smartlist_create();
2260 for (i = 0; _option_vars[i].name; ++i) {
2261 config_var_t *var = &_option_vars[i];
2262 const char *desc;
2263 if (var->type == CONFIG_TYPE_OBSOLETE ||
2264 var->type == CONFIG_TYPE_LINELIST_V)
2265 continue;
2266 desc = config_find_description(&options_format, var->name);
2267 printf("%s\n", var->name);
2268 if (desc) {
2269 wrap_string(lines, desc, 76, " ", " ");
2270 SMARTLIST_FOREACH(lines, char *, cp, {
2271 printf("%s", cp);
2272 tor_free(cp);
2274 smartlist_clear(lines);
2277 smartlist_free(lines);
2280 /** Last value actually set by resolve_my_address. */
2281 static uint32_t last_resolved_addr = 0;
2283 * Based on <b>options-\>Address</b>, guess our public IP address and put it
2284 * (in host order) into *<b>addr_out</b>. If <b>hostname_out</b> is provided,
2285 * set *<b>hostname_out</b> to a new string holding the hostname we used to
2286 * get the address. Return 0 if all is well, or -1 if we can't find a suitable
2287 * public IP address.
2290 resolve_my_address(int warn_severity, or_options_t *options,
2291 uint32_t *addr_out, char **hostname_out)
2293 struct in_addr in;
2294 struct hostent *rent;
2295 char hostname[256];
2296 int explicit_ip=1;
2297 int explicit_hostname=1;
2298 int from_interface=0;
2299 char tmpbuf[INET_NTOA_BUF_LEN];
2300 const char *address = options->Address;
2301 int notice_severity = warn_severity <= LOG_NOTICE ?
2302 LOG_NOTICE : warn_severity;
2304 tor_assert(addr_out);
2306 if (address && *address) {
2307 strlcpy(hostname, address, sizeof(hostname));
2308 } else { /* then we need to guess our address */
2309 explicit_ip = 0; /* it's implicit */
2310 explicit_hostname = 0; /* it's implicit */
2312 if (gethostname(hostname, sizeof(hostname)) < 0) {
2313 log_fn(warn_severity, LD_NET,"Error obtaining local hostname");
2314 return -1;
2316 log_debug(LD_CONFIG,"Guessed local host name as '%s'",hostname);
2319 /* now we know hostname. resolve it and keep only the IP address */
2321 if (tor_inet_aton(hostname, &in) == 0) {
2322 /* then we have to resolve it */
2323 explicit_ip = 0;
2324 rent = (struct hostent *)gethostbyname(hostname);
2325 if (!rent) {
2326 uint32_t interface_ip;
2328 if (explicit_hostname) {
2329 log_fn(warn_severity, LD_CONFIG,
2330 "Could not resolve local Address '%s'. Failing.", hostname);
2331 return -1;
2333 log_fn(notice_severity, LD_CONFIG,
2334 "Could not resolve guessed local hostname '%s'. "
2335 "Trying something else.", hostname);
2336 if (get_interface_address(warn_severity, &interface_ip)) {
2337 log_fn(warn_severity, LD_CONFIG,
2338 "Could not get local interface IP address. Failing.");
2339 return -1;
2341 from_interface = 1;
2342 in.s_addr = htonl(interface_ip);
2343 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2344 log_fn(notice_severity, LD_CONFIG, "Learned IP address '%s' for "
2345 "local interface. Using that.", tmpbuf);
2346 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2347 } else {
2348 tor_assert(rent->h_length == 4);
2349 memcpy(&in.s_addr, rent->h_addr, rent->h_length);
2351 if (!explicit_hostname &&
2352 is_internal_IP(ntohl(in.s_addr), 0)) {
2353 uint32_t interface_ip;
2355 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2356 log_fn(notice_severity, LD_CONFIG, "Guessed local hostname '%s' "
2357 "resolves to a private IP address (%s). Trying something "
2358 "else.", hostname, tmpbuf);
2360 if (get_interface_address(warn_severity, &interface_ip)) {
2361 log_fn(warn_severity, LD_CONFIG,
2362 "Could not get local interface IP address. Too bad.");
2363 } else if (is_internal_IP(interface_ip, 0)) {
2364 struct in_addr in2;
2365 in2.s_addr = htonl(interface_ip);
2366 tor_inet_ntoa(&in2,tmpbuf,sizeof(tmpbuf));
2367 log_fn(notice_severity, LD_CONFIG,
2368 "Interface IP address '%s' is a private address too. "
2369 "Ignoring.", tmpbuf);
2370 } else {
2371 from_interface = 1;
2372 in.s_addr = htonl(interface_ip);
2373 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2374 log_fn(notice_severity, LD_CONFIG,
2375 "Learned IP address '%s' for local interface."
2376 " Using that.", tmpbuf);
2377 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2383 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2384 if (is_internal_IP(ntohl(in.s_addr), 0) &&
2385 options->_PublishServerDescriptor) {
2386 /* make sure we're ok with publishing an internal IP */
2387 if (!options->DirServers && !options->AlternateDirAuthority) {
2388 /* if they are using the default dirservers, disallow internal IPs
2389 * always. */
2390 log_fn(warn_severity, LD_CONFIG,
2391 "Address '%s' resolves to private IP address '%s'. "
2392 "Tor servers that use the default DirServers must have public "
2393 "IP addresses.", hostname, tmpbuf);
2394 return -1;
2396 if (!explicit_ip) {
2397 /* even if they've set their own dirservers, require an explicit IP if
2398 * they're using an internal address. */
2399 log_fn(warn_severity, LD_CONFIG, "Address '%s' resolves to private "
2400 "IP address '%s'. Please set the Address config option to be "
2401 "the IP address you want to use.", hostname, tmpbuf);
2402 return -1;
2406 log_debug(LD_CONFIG, "Resolved Address to '%s'.", tmpbuf);
2407 *addr_out = ntohl(in.s_addr);
2408 if (last_resolved_addr && last_resolved_addr != *addr_out) {
2409 /* Leave this as a notice, regardless of the requested severity,
2410 * at least until dynamic IP address support becomes bulletproof. */
2411 log_notice(LD_NET,
2412 "Your IP address seems to have changed to %s. Updating.",
2413 tmpbuf);
2414 ip_address_changed(0);
2416 if (last_resolved_addr != *addr_out) {
2417 const char *method;
2418 const char *h = hostname;
2419 if (explicit_ip) {
2420 method = "CONFIGURED";
2421 h = NULL;
2422 } else if (explicit_hostname) {
2423 method = "RESOLVED";
2424 } else if (from_interface) {
2425 method = "INTERFACE";
2426 h = NULL;
2427 } else {
2428 method = "GETHOSTNAME";
2430 control_event_server_status(LOG_NOTICE,
2431 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s %s%s",
2432 tmpbuf, method, h?"HOSTNAME=":"", h);
2434 last_resolved_addr = *addr_out;
2435 if (hostname_out)
2436 *hostname_out = tor_strdup(hostname);
2437 return 0;
2440 /** Return true iff <b>addr</b> is judged to be on the same network as us, or
2441 * on a private network.
2444 is_local_addr(const tor_addr_t *addr)
2446 if (tor_addr_is_internal(addr, 0))
2447 return 1;
2448 /* Check whether ip is on the same /24 as we are. */
2449 if (get_options()->EnforceDistinctSubnets == 0)
2450 return 0;
2451 if (tor_addr_family(addr) == AF_INET) {
2452 /*XXXX021 IP6 what corresponds to an /24? */
2453 uint32_t ip = tor_addr_to_ipv4h(addr);
2455 /* It's possible that this next check will hit before the first time
2456 * resolve_my_address actually succeeds. (For clients, it is likely that
2457 * resolve_my_address will never be called at all). In those cases,
2458 * last_resolved_addr will be 0, and so checking to see whether ip is on
2459 * the same /24 as last_resolved_addr will be the same as checking whether
2460 * it was on net 0, which is already done by is_internal_IP.
2462 if ((last_resolved_addr & 0xffffff00ul) == (ip & 0xffffff00ul))
2463 return 1;
2465 return 0;
2468 /** Called when we don't have a nickname set. Try to guess a good nickname
2469 * based on the hostname, and return it in a newly allocated string. If we
2470 * can't, return NULL and let the caller warn if it wants to. */
2471 static char *
2472 get_default_nickname(void)
2474 static const char * const bad_default_nicknames[] = {
2475 "localhost",
2476 NULL,
2478 char localhostname[256];
2479 char *cp, *out, *outp;
2480 int i;
2482 if (gethostname(localhostname, sizeof(localhostname)) < 0)
2483 return NULL;
2485 /* Put it in lowercase; stop at the first dot. */
2486 if ((cp = strchr(localhostname, '.')))
2487 *cp = '\0';
2488 tor_strlower(localhostname);
2490 /* Strip invalid characters. */
2491 cp = localhostname;
2492 out = outp = tor_malloc(strlen(localhostname) + 1);
2493 while (*cp) {
2494 if (strchr(LEGAL_NICKNAME_CHARACTERS, *cp))
2495 *outp++ = *cp++;
2496 else
2497 cp++;
2499 *outp = '\0';
2501 /* Enforce length. */
2502 if (strlen(out) > MAX_NICKNAME_LEN)
2503 out[MAX_NICKNAME_LEN]='\0';
2505 /* Check for dumb names. */
2506 for (i = 0; bad_default_nicknames[i]; ++i) {
2507 if (!strcmp(out, bad_default_nicknames[i])) {
2508 tor_free(out);
2509 return NULL;
2513 return out;
2516 /** Release storage held by <b>options</b>. */
2517 static void
2518 config_free(config_format_t *fmt, void *options)
2520 int i;
2522 tor_assert(options);
2524 for (i=0; fmt->vars[i].name; ++i)
2525 option_clear(fmt, options, &(fmt->vars[i]));
2526 if (fmt->extra) {
2527 config_line_t **linep = STRUCT_VAR_P(options, fmt->extra->var_offset);
2528 config_free_lines(*linep);
2529 *linep = NULL;
2531 tor_free(options);
2534 /** Return true iff a and b contain identical keys and values in identical
2535 * order. */
2536 static int
2537 config_lines_eq(config_line_t *a, config_line_t *b)
2539 while (a && b) {
2540 if (strcasecmp(a->key, b->key) || strcmp(a->value, b->value))
2541 return 0;
2542 a = a->next;
2543 b = b->next;
2545 if (a || b)
2546 return 0;
2547 return 1;
2550 /** Return true iff the option <b>name</b> has the same value in <b>o1</b>
2551 * and <b>o2</b>. Must not be called for LINELIST_S or OBSOLETE options.
2553 static int
2554 option_is_same(config_format_t *fmt,
2555 or_options_t *o1, or_options_t *o2, const char *name)
2557 config_line_t *c1, *c2;
2558 int r = 1;
2559 CHECK(fmt, o1);
2560 CHECK(fmt, o2);
2562 c1 = get_assigned_option(fmt, o1, name, 0);
2563 c2 = get_assigned_option(fmt, o2, name, 0);
2564 r = config_lines_eq(c1, c2);
2565 config_free_lines(c1);
2566 config_free_lines(c2);
2567 return r;
2570 /** Copy storage held by <b>old</b> into a new or_options_t and return it. */
2571 static or_options_t *
2572 options_dup(config_format_t *fmt, or_options_t *old)
2574 or_options_t *newopts;
2575 int i;
2576 config_line_t *line;
2578 newopts = config_alloc(fmt);
2579 for (i=0; fmt->vars[i].name; ++i) {
2580 if (fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
2581 continue;
2582 if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE)
2583 continue;
2584 line = get_assigned_option(fmt, old, fmt->vars[i].name, 0);
2585 if (line) {
2586 char *msg = NULL;
2587 if (config_assign(fmt, newopts, line, 0, 0, &msg) < 0) {
2588 log_err(LD_BUG, "Config_get_assigned_option() generated "
2589 "something we couldn't config_assign(): %s", msg);
2590 tor_free(msg);
2591 tor_assert(0);
2594 config_free_lines(line);
2596 return newopts;
2599 /** Return a new empty or_options_t. Used for testing. */
2600 or_options_t *
2601 options_new(void)
2603 return config_alloc(&options_format);
2606 /** Set <b>options</b> to hold reasonable defaults for most options.
2607 * Each option defaults to zero. */
2608 void
2609 options_init(or_options_t *options)
2611 config_init(&options_format, options);
2614 /** Set all vars in the configuration object <b>options</b> to their default
2615 * values. */
2616 static void
2617 config_init(config_format_t *fmt, void *options)
2619 int i;
2620 config_var_t *var;
2621 CHECK(fmt, options);
2623 for (i=0; fmt->vars[i].name; ++i) {
2624 var = &fmt->vars[i];
2625 if (!var->initvalue)
2626 continue; /* defaults to NULL or 0 */
2627 option_reset(fmt, options, var, 1);
2631 /** Allocate and return a new string holding the written-out values of the vars
2632 * in 'options'. If 'minimal', do not write out any default-valued vars.
2633 * Else, if comment_defaults, write default values as comments.
2635 static char *
2636 config_dump(config_format_t *fmt, void *options, int minimal,
2637 int comment_defaults)
2639 smartlist_t *elements;
2640 or_options_t *defaults;
2641 config_line_t *line, *assigned;
2642 char *result;
2643 int i;
2644 const char *desc;
2645 char *msg = NULL;
2647 defaults = config_alloc(fmt);
2648 config_init(fmt, defaults);
2650 /* XXX use a 1 here so we don't add a new log line while dumping */
2651 if (fmt->validate_fn(NULL,defaults, 1, &msg) < 0) {
2652 log_err(LD_BUG, "Failed to validate default config.");
2653 tor_free(msg);
2654 tor_assert(0);
2657 elements = smartlist_create();
2658 for (i=0; fmt->vars[i].name; ++i) {
2659 int comment_option = 0;
2660 if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE ||
2661 fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
2662 continue;
2663 /* Don't save 'hidden' control variables. */
2664 if (!strcmpstart(fmt->vars[i].name, "__"))
2665 continue;
2666 if (minimal && option_is_same(fmt, options, defaults, fmt->vars[i].name))
2667 continue;
2668 else if (comment_defaults &&
2669 option_is_same(fmt, options, defaults, fmt->vars[i].name))
2670 comment_option = 1;
2672 desc = config_find_description(fmt, fmt->vars[i].name);
2673 line = assigned = get_assigned_option(fmt, options, fmt->vars[i].name, 1);
2675 if (line && desc) {
2676 /* Only dump the description if there's something to describe. */
2677 wrap_string(elements, desc, 78, "# ", "# ");
2680 for (; line; line = line->next) {
2681 size_t len = strlen(line->key) + strlen(line->value) + 5;
2682 char *tmp;
2683 tmp = tor_malloc(len);
2684 if (tor_snprintf(tmp, len, "%s%s %s\n",
2685 comment_option ? "# " : "",
2686 line->key, line->value)<0) {
2687 log_err(LD_BUG,"Internal error writing option value");
2688 tor_assert(0);
2690 smartlist_add(elements, tmp);
2692 config_free_lines(assigned);
2695 if (fmt->extra) {
2696 line = *(config_line_t**)STRUCT_VAR_P(options, fmt->extra->var_offset);
2697 for (; line; line = line->next) {
2698 size_t len = strlen(line->key) + strlen(line->value) + 3;
2699 char *tmp;
2700 tmp = tor_malloc(len);
2701 if (tor_snprintf(tmp, len, "%s %s\n", line->key, line->value)<0) {
2702 log_err(LD_BUG,"Internal error writing option value");
2703 tor_assert(0);
2705 smartlist_add(elements, tmp);
2709 result = smartlist_join_strings(elements, "", 0, NULL);
2710 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
2711 smartlist_free(elements);
2712 config_free(fmt, defaults);
2713 return result;
2716 /** Return a string containing a possible configuration file that would give
2717 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
2718 * include options that are the same as Tor's defaults.
2720 static char *
2721 options_dump(or_options_t *options, int minimal)
2723 return config_dump(&options_format, options, minimal, 0);
2726 /** Return 0 if every element of sl is a string holding a decimal
2727 * representation of a port number, or if sl is NULL.
2728 * Otherwise set *msg and return -1. */
2729 static int
2730 validate_ports_csv(smartlist_t *sl, const char *name, char **msg)
2732 int i;
2733 char buf[1024];
2734 tor_assert(name);
2736 if (!sl)
2737 return 0;
2739 SMARTLIST_FOREACH(sl, const char *, cp,
2741 i = atoi(cp);
2742 if (i < 1 || i > 65535) {
2743 int r = tor_snprintf(buf, sizeof(buf),
2744 "Port '%s' out of range in %s", cp, name);
2745 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2746 return -1;
2749 return 0;
2752 /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
2753 * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
2754 * Else return 0.
2756 static int
2757 ensure_bandwidth_cap(uint64_t *value, const char *desc, char **msg)
2759 int r;
2760 char buf[1024];
2761 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2762 /* This handles an understandable special case where somebody says "2gb"
2763 * whereas our actual maximum is 2gb-1 (INT_MAX) */
2764 --*value;
2766 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2767 r = tor_snprintf(buf, sizeof(buf), "%s ("U64_FORMAT") must be at most %d",
2768 desc, U64_PRINTF_ARG(*value),
2769 ROUTER_MAX_DECLARED_BANDWIDTH);
2770 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2771 return -1;
2773 return 0;
2776 /** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
2777 * and write it to <b>options</b>-\>_PublishServerDescriptor. Treat "1"
2778 * as "v2,v3" unless BridgeRelay is 1, in which case treat it as "bridge".
2779 * Treat "0" as "".
2780 * Return 0 on success or -1 if not a recognized authority type (in which
2781 * case the value of _PublishServerDescriptor is undefined). */
2782 static int
2783 compute_publishserverdescriptor(or_options_t *options)
2785 smartlist_t *list = options->PublishServerDescriptor;
2786 authority_type_t *auth = &options->_PublishServerDescriptor;
2787 *auth = NO_AUTHORITY;
2788 if (!list) /* empty list, answer is none */
2789 return 0;
2790 SMARTLIST_FOREACH(list, const char *, string, {
2791 if (!strcasecmp(string, "v1"))
2792 *auth |= V1_AUTHORITY;
2793 else if (!strcmp(string, "1"))
2794 if (options->BridgeRelay)
2795 *auth |= BRIDGE_AUTHORITY;
2796 else
2797 *auth |= V2_AUTHORITY | V3_AUTHORITY;
2798 else if (!strcasecmp(string, "v2"))
2799 *auth |= V2_AUTHORITY;
2800 else if (!strcasecmp(string, "v3"))
2801 *auth |= V3_AUTHORITY;
2802 else if (!strcasecmp(string, "bridge"))
2803 *auth |= BRIDGE_AUTHORITY;
2804 else if (!strcasecmp(string, "hidserv"))
2805 *auth |= HIDSERV_AUTHORITY;
2806 else if (!strcasecmp(string, "") || !strcmp(string, "0"))
2807 /* no authority */;
2808 else
2809 return -1;
2811 return 0;
2814 /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
2815 * services can overload the directory system. */
2816 #define MIN_REND_POST_PERIOD (10*60)
2818 /** Highest allowable value for RendPostPeriod. */
2819 #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
2821 /** Return 0 if every setting in <b>options</b> is reasonable, and a
2822 * permissible transition from <b>old_options</b>. Else return -1.
2823 * Should have no side effects, except for normalizing the contents of
2824 * <b>options</b>.
2826 * On error, tor_strdup an error explanation into *<b>msg</b>.
2828 * XXX
2829 * If <b>from_setconf</b>, we were called by the controller, and our
2830 * Log line should stay empty. If it's 0, then give us a default log
2831 * if there are no logs defined.
2833 static int
2834 options_validate(or_options_t *old_options, or_options_t *options,
2835 int from_setconf, char **msg)
2837 int i, r;
2838 config_line_t *cl;
2839 const char *uname = get_uname();
2840 char buf[1024];
2841 #define REJECT(arg) \
2842 STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
2843 #define COMPLAIN(arg) STMT_BEGIN log(LOG_WARN, LD_CONFIG, arg); STMT_END
2845 tor_assert(msg);
2846 *msg = NULL;
2848 if (options->ORPort < 0 || options->ORPort > 65535)
2849 REJECT("ORPort option out of bounds.");
2851 if (server_mode(options) &&
2852 (!strcmpstart(uname, "Windows 95") ||
2853 !strcmpstart(uname, "Windows 98") ||
2854 !strcmpstart(uname, "Windows Me"))) {
2855 log(LOG_WARN, LD_CONFIG, "Tor is running as a server, but you are "
2856 "running %s; this probably won't work. See "
2857 "http://wiki.noreply.org/noreply/TheOnionRouter/TorFAQ#ServerOS "
2858 "for details.", uname);
2861 if (options->ORPort == 0 && options->ORListenAddress != NULL)
2862 REJECT("ORPort must be defined if ORListenAddress is defined.");
2864 if (options->DirPort == 0 && options->DirListenAddress != NULL)
2865 REJECT("DirPort must be defined if DirListenAddress is defined.");
2867 if (options->DNSPort == 0 && options->DNSListenAddress != NULL)
2868 REJECT("DNSPort must be defined if DNSListenAddress is defined.");
2870 if (options->ControlPort == 0 && options->ControlListenAddress != NULL)
2871 REJECT("ControlPort must be defined if ControlListenAddress is defined.");
2873 if (options->TransPort == 0 && options->TransListenAddress != NULL)
2874 REJECT("TransPort must be defined if TransListenAddress is defined.");
2876 if (options->NatdPort == 0 && options->NatdListenAddress != NULL)
2877 REJECT("NatdPort must be defined if NatdListenAddress is defined.");
2879 /* Don't gripe about SocksPort 0 with SocksListenAddress set; a standard
2880 * configuration does this. */
2882 for (i = 0; i < 3; ++i) {
2883 int is_socks = i==0;
2884 int is_trans = i==1;
2885 config_line_t *line, *opt, *old;
2886 const char *tp;
2887 if (is_socks) {
2888 opt = options->SocksListenAddress;
2889 old = old_options ? old_options->SocksListenAddress : NULL;
2890 tp = "SOCKS proxy";
2891 } else if (is_trans) {
2892 opt = options->TransListenAddress;
2893 old = old_options ? old_options->TransListenAddress : NULL;
2894 tp = "transparent proxy";
2895 } else {
2896 opt = options->NatdListenAddress;
2897 old = old_options ? old_options->NatdListenAddress : NULL;
2898 tp = "natd proxy";
2901 for (line = opt; line; line = line->next) {
2902 char *address = NULL;
2903 uint16_t port;
2904 uint32_t addr;
2905 if (parse_addr_port(LOG_WARN, line->value, &address, &addr, &port)<0)
2906 continue; /* We'll warn about this later. */
2907 if (!is_internal_IP(addr, 1) &&
2908 (!old_options || !config_lines_eq(old, opt))) {
2909 log_warn(LD_CONFIG,
2910 "You specified a public address '%s' for a %s. Other "
2911 "people on the Internet might find your computer and use it as "
2912 "an open %s. Please don't allow this unless you have "
2913 "a good reason.", address, tp, tp);
2915 tor_free(address);
2919 if (validate_data_directory(options)<0)
2920 REJECT("Invalid DataDirectory");
2922 if (options->Nickname == NULL) {
2923 if (server_mode(options)) {
2924 if (!(options->Nickname = get_default_nickname())) {
2925 log_notice(LD_CONFIG, "Couldn't pick a nickname based on "
2926 "our hostname; using %s instead.", UNNAMED_ROUTER_NICKNAME);
2927 options->Nickname = tor_strdup(UNNAMED_ROUTER_NICKNAME);
2928 } else {
2929 log_notice(LD_CONFIG, "Choosing default nickname '%s'",
2930 options->Nickname);
2933 } else {
2934 if (!is_legal_nickname(options->Nickname)) {
2935 r = tor_snprintf(buf, sizeof(buf),
2936 "Nickname '%s' is wrong length or contains illegal characters.",
2937 options->Nickname);
2938 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2939 return -1;
2943 if (server_mode(options) && !options->ContactInfo)
2944 log(LOG_NOTICE, LD_CONFIG, "Your ContactInfo config option is not set. "
2945 "Please consider setting it, so we can contact you if your server is "
2946 "misconfigured or something else goes wrong.");
2948 /* Special case on first boot if no Log options are given. */
2949 if (!options->Logs && !options->RunAsDaemon && !from_setconf)
2950 config_line_append(&options->Logs, "Log", "notice stdout");
2952 if (options_init_logs(options, 1)<0) /* Validate the log(s) */
2953 REJECT("Failed to validate Log options. See logs for details.");
2955 if (options->NoPublish) {
2956 log(LOG_WARN, LD_CONFIG,
2957 "NoPublish is obsolete. Use PublishServerDescriptor instead.");
2958 SMARTLIST_FOREACH(options->PublishServerDescriptor, char *, s,
2959 tor_free(s));
2960 smartlist_clear(options->PublishServerDescriptor);
2963 if (authdir_mode(options)) {
2964 /* confirm that our address isn't broken, so we can complain now */
2965 uint32_t tmp;
2966 if (resolve_my_address(LOG_WARN, options, &tmp, NULL) < 0)
2967 REJECT("Failed to resolve/guess local address. See logs for details.");
2970 #ifndef MS_WINDOWS
2971 if (options->RunAsDaemon && torrc_fname && path_is_relative(torrc_fname))
2972 REJECT("Can't use a relative path to torrc when RunAsDaemon is set.");
2973 #endif
2975 if (options->SocksPort < 0 || options->SocksPort > 65535)
2976 REJECT("SocksPort option out of bounds.");
2978 if (options->DNSPort < 0 || options->DNSPort > 65535)
2979 REJECT("DNSPort option out of bounds.");
2981 if (options->TransPort < 0 || options->TransPort > 65535)
2982 REJECT("TransPort option out of bounds.");
2984 if (options->NatdPort < 0 || options->NatdPort > 65535)
2985 REJECT("NatdPort option out of bounds.");
2987 if (options->SocksPort == 0 && options->TransPort == 0 &&
2988 options->NatdPort == 0 && options->ORPort == 0 &&
2989 options->DNSPort == 0 && !options->RendConfigLines)
2990 log(LOG_WARN, LD_CONFIG,
2991 "SocksPort, TransPort, NatdPort, DNSPort, and ORPort are all "
2992 "undefined, and there aren't any hidden services configured. "
2993 "Tor will still run, but probably won't do anything.");
2995 if (options->ControlPort < 0 || options->ControlPort > 65535)
2996 REJECT("ControlPort option out of bounds.");
2998 if (options->DirPort < 0 || options->DirPort > 65535)
2999 REJECT("DirPort option out of bounds.");
3001 #ifndef USE_TRANSPARENT
3002 if (options->TransPort || options->TransListenAddress)
3003 REJECT("TransPort and TransListenAddress are disabled in this build.");
3004 #endif
3006 if (options->ExcludeExitNodes || options->ExcludeNodes) {
3007 options->_ExcludeExitNodesUnion = routerset_new();
3008 routerset_union(options->_ExcludeExitNodesUnion,options->ExcludeExitNodes);
3009 routerset_union(options->_ExcludeExitNodesUnion,options->ExcludeNodes);
3012 if (options->StrictExitNodes &&
3013 (!options->ExitNodes) &&
3014 (!old_options ||
3015 (old_options->StrictExitNodes != options->StrictExitNodes) ||
3016 (!routerset_equal(old_options->ExitNodes,options->ExitNodes))))
3017 COMPLAIN("StrictExitNodes set, but no ExitNodes listed.");
3019 if (options->StrictEntryNodes &&
3020 (!options->EntryNodes) &&
3021 (!old_options ||
3022 (old_options->StrictEntryNodes != options->StrictEntryNodes) ||
3023 (!routerset_equal(old_options->EntryNodes,options->EntryNodes))))
3024 COMPLAIN("StrictEntryNodes set, but no EntryNodes listed.");
3026 if (options->EntryNodes && !routerset_is_list(options->EntryNodes)) {
3027 /** XXXX021 fix this; see entry_guards_prepend_from_config(). */
3028 REJECT("IPs or countries are not yet supported in EntryNodes.");
3031 if (options->AuthoritativeDir) {
3032 if (!options->ContactInfo)
3033 REJECT("Authoritative directory servers must set ContactInfo");
3034 if (options->V1AuthoritativeDir && !options->RecommendedVersions)
3035 REJECT("V1 auth dir servers must set RecommendedVersions.");
3036 if (!options->RecommendedClientVersions)
3037 options->RecommendedClientVersions =
3038 config_lines_dup(options->RecommendedVersions);
3039 if (!options->RecommendedServerVersions)
3040 options->RecommendedServerVersions =
3041 config_lines_dup(options->RecommendedVersions);
3042 if (options->VersioningAuthoritativeDir &&
3043 (!options->RecommendedClientVersions ||
3044 !options->RecommendedServerVersions))
3045 REJECT("Versioning auth dir servers must set Recommended*Versions.");
3046 if (options->UseEntryGuards) {
3047 log_info(LD_CONFIG, "Authoritative directory servers can't set "
3048 "UseEntryGuards. Disabling.");
3049 options->UseEntryGuards = 0;
3051 if (!options->DownloadExtraInfo && authdir_mode_any_main(options)) {
3052 log_info(LD_CONFIG, "Authoritative directories always try to download "
3053 "extra-info documents. Setting DownloadExtraInfo.");
3054 options->DownloadExtraInfo = 1;
3056 if (!(options->BridgeAuthoritativeDir || options->HSAuthoritativeDir ||
3057 options->V1AuthoritativeDir || options->V2AuthoritativeDir ||
3058 options->V3AuthoritativeDir))
3059 REJECT("AuthoritativeDir is set, but none of "
3060 "(Bridge/HS/V1/V2/V3)AuthoritativeDir is set.");
3063 if (options->AuthoritativeDir && !options->DirPort)
3064 REJECT("Running as authoritative directory, but no DirPort set.");
3066 if (options->AuthoritativeDir && !options->ORPort)
3067 REJECT("Running as authoritative directory, but no ORPort set.");
3069 if (options->AuthoritativeDir && options->ClientOnly)
3070 REJECT("Running as authoritative directory, but ClientOnly also set.");
3072 if (options->HSAuthorityRecordStats && !options->HSAuthoritativeDir)
3073 REJECT("HSAuthorityRecordStats is set but we're not running as "
3074 "a hidden service authority.");
3076 if (options->ConnLimit <= 0) {
3077 r = tor_snprintf(buf, sizeof(buf),
3078 "ConnLimit must be greater than 0, but was set to %d",
3079 options->ConnLimit);
3080 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3081 return -1;
3084 if (validate_ports_csv(options->FirewallPorts, "FirewallPorts", msg) < 0)
3085 return -1;
3087 if (validate_ports_csv(options->LongLivedPorts, "LongLivedPorts", msg) < 0)
3088 return -1;
3090 if (validate_ports_csv(options->RejectPlaintextPorts,
3091 "RejectPlaintextPorts", msg) < 0)
3092 return -1;
3094 if (validate_ports_csv(options->WarnPlaintextPorts,
3095 "WarnPlaintextPorts", msg) < 0)
3096 return -1;
3098 if (options->FascistFirewall && !options->ReachableAddresses) {
3099 if (options->FirewallPorts && smartlist_len(options->FirewallPorts)) {
3100 /* We already have firewall ports set, so migrate them to
3101 * ReachableAddresses, which will set ReachableORAddresses and
3102 * ReachableDirAddresses if they aren't set explicitly. */
3103 smartlist_t *instead = smartlist_create();
3104 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3105 new_line->key = tor_strdup("ReachableAddresses");
3106 /* If we're configured with the old format, we need to prepend some
3107 * open ports. */
3108 SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
3110 int p = atoi(portno);
3111 char *s;
3112 if (p<0) continue;
3113 s = tor_malloc(16);
3114 tor_snprintf(s, 16, "*:%d", p);
3115 smartlist_add(instead, s);
3117 new_line->value = smartlist_join_strings(instead,",",0,NULL);
3118 /* These have been deprecated since 0.1.1.5-alpha-cvs */
3119 log(LOG_NOTICE, LD_CONFIG,
3120 "Converting FascistFirewall and FirewallPorts "
3121 "config options to new format: \"ReachableAddresses %s\"",
3122 new_line->value);
3123 options->ReachableAddresses = new_line;
3124 SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
3125 smartlist_free(instead);
3126 } else {
3127 /* We do not have FirewallPorts set, so add 80 to
3128 * ReachableDirAddresses, and 443 to ReachableORAddresses. */
3129 if (!options->ReachableDirAddresses) {
3130 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3131 new_line->key = tor_strdup("ReachableDirAddresses");
3132 new_line->value = tor_strdup("*:80");
3133 options->ReachableDirAddresses = new_line;
3134 log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
3135 "to new format: \"ReachableDirAddresses *:80\"");
3137 if (!options->ReachableORAddresses) {
3138 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3139 new_line->key = tor_strdup("ReachableORAddresses");
3140 new_line->value = tor_strdup("*:443");
3141 options->ReachableORAddresses = new_line;
3142 log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
3143 "to new format: \"ReachableORAddresses *:443\"");
3148 for (i=0; i<3; i++) {
3149 config_line_t **linep =
3150 (i==0) ? &options->ReachableAddresses :
3151 (i==1) ? &options->ReachableORAddresses :
3152 &options->ReachableDirAddresses;
3153 if (!*linep)
3154 continue;
3155 /* We need to end with a reject *:*, not an implicit accept *:* */
3156 for (;;) {
3157 if (!strcmp((*linep)->value, "reject *:*")) /* already there */
3158 break;
3159 linep = &((*linep)->next);
3160 if (!*linep) {
3161 *linep = tor_malloc_zero(sizeof(config_line_t));
3162 (*linep)->key = tor_strdup(
3163 (i==0) ? "ReachableAddresses" :
3164 (i==1) ? "ReachableORAddresses" :
3165 "ReachableDirAddresses");
3166 (*linep)->value = tor_strdup("reject *:*");
3167 break;
3172 if ((options->ReachableAddresses ||
3173 options->ReachableORAddresses ||
3174 options->ReachableDirAddresses) &&
3175 server_mode(options))
3176 REJECT("Servers must be able to freely connect to the rest "
3177 "of the Internet, so they must not set Reachable*Addresses "
3178 "or FascistFirewall.");
3180 if (options->UseBridges &&
3181 server_mode(options))
3182 REJECT("Servers must be able to freely connect to the rest "
3183 "of the Internet, so they must not set UseBridges.");
3185 options->_AllowInvalid = 0;
3186 if (options->AllowInvalidNodes) {
3187 SMARTLIST_FOREACH(options->AllowInvalidNodes, const char *, cp, {
3188 if (!strcasecmp(cp, "entry"))
3189 options->_AllowInvalid |= ALLOW_INVALID_ENTRY;
3190 else if (!strcasecmp(cp, "exit"))
3191 options->_AllowInvalid |= ALLOW_INVALID_EXIT;
3192 else if (!strcasecmp(cp, "middle"))
3193 options->_AllowInvalid |= ALLOW_INVALID_MIDDLE;
3194 else if (!strcasecmp(cp, "introduction"))
3195 options->_AllowInvalid |= ALLOW_INVALID_INTRODUCTION;
3196 else if (!strcasecmp(cp, "rendezvous"))
3197 options->_AllowInvalid |= ALLOW_INVALID_RENDEZVOUS;
3198 else {
3199 r = tor_snprintf(buf, sizeof(buf),
3200 "Unrecognized value '%s' in AllowInvalidNodes", cp);
3201 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3202 return -1;
3207 if (compute_publishserverdescriptor(options) < 0) {
3208 r = tor_snprintf(buf, sizeof(buf),
3209 "Unrecognized value in PublishServerDescriptor");
3210 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3211 return -1;
3214 if (options->MinUptimeHidServDirectoryV2 < 0) {
3215 log_warn(LD_CONFIG, "MinUptimeHidServDirectoryV2 option must be at "
3216 "least 0 seconds. Changing to 0.");
3217 options->MinUptimeHidServDirectoryV2 = 0;
3220 if (options->RendPostPeriod < MIN_REND_POST_PERIOD) {
3221 log(LOG_WARN,LD_CONFIG,"RendPostPeriod option must be at least %d seconds."
3222 " Clipping.", MIN_REND_POST_PERIOD);
3223 options->RendPostPeriod = MIN_REND_POST_PERIOD;
3226 if (options->RendPostPeriod > MAX_DIR_PERIOD) {
3227 log(LOG_WARN, LD_CONFIG, "RendPostPeriod is too large; clipping to %ds.",
3228 MAX_DIR_PERIOD);
3229 options->RendPostPeriod = MAX_DIR_PERIOD;
3232 if (options->KeepalivePeriod < 1)
3233 REJECT("KeepalivePeriod option must be positive.");
3235 if (ensure_bandwidth_cap(&options->BandwidthRate,
3236 "BandwidthRate", msg) < 0)
3237 return -1;
3238 if (ensure_bandwidth_cap(&options->BandwidthBurst,
3239 "BandwidthBurst", msg) < 0)
3240 return -1;
3241 if (ensure_bandwidth_cap(&options->MaxAdvertisedBandwidth,
3242 "MaxAdvertisedBandwidth", msg) < 0)
3243 return -1;
3244 if (ensure_bandwidth_cap(&options->RelayBandwidthRate,
3245 "RelayBandwidthRate", msg) < 0)
3246 return -1;
3247 if (ensure_bandwidth_cap(&options->RelayBandwidthBurst,
3248 "RelayBandwidthBurst", msg) < 0)
3249 return -1;
3251 if (server_mode(options)) {
3252 if (options->BandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH*2) {
3253 r = tor_snprintf(buf, sizeof(buf),
3254 "BandwidthRate is set to %d bytes/second. "
3255 "For servers, it must be at least %d.",
3256 (int)options->BandwidthRate,
3257 ROUTER_REQUIRED_MIN_BANDWIDTH*2);
3258 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3259 return -1;
3260 } else if (options->MaxAdvertisedBandwidth <
3261 ROUTER_REQUIRED_MIN_BANDWIDTH) {
3262 r = tor_snprintf(buf, sizeof(buf),
3263 "MaxAdvertisedBandwidth is set to %d bytes/second. "
3264 "For servers, it must be at least %d.",
3265 (int)options->MaxAdvertisedBandwidth,
3266 ROUTER_REQUIRED_MIN_BANDWIDTH);
3267 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3268 return -1;
3270 if (options->RelayBandwidthRate &&
3271 options->RelayBandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
3272 r = tor_snprintf(buf, sizeof(buf),
3273 "RelayBandwidthRate is set to %d bytes/second. "
3274 "For servers, it must be at least %d.",
3275 (int)options->RelayBandwidthRate,
3276 ROUTER_REQUIRED_MIN_BANDWIDTH);
3277 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3278 return -1;
3282 if (options->RelayBandwidthRate && !options->RelayBandwidthBurst)
3283 options->RelayBandwidthBurst = options->RelayBandwidthRate;
3285 if (options->RelayBandwidthRate > options->RelayBandwidthBurst)
3286 REJECT("RelayBandwidthBurst must be at least equal "
3287 "to RelayBandwidthRate.");
3289 if (options->BandwidthRate > options->BandwidthBurst)
3290 REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
3292 /* if they set relaybandwidth* really high but left bandwidth*
3293 * at the default, raise the defaults. */
3294 if (options->RelayBandwidthRate > options->BandwidthRate)
3295 options->BandwidthRate = options->RelayBandwidthRate;
3296 if (options->RelayBandwidthBurst > options->BandwidthBurst)
3297 options->BandwidthBurst = options->RelayBandwidthBurst;
3299 if (accounting_parse_options(options, 1)<0)
3300 REJECT("Failed to parse accounting options. See logs for details.");
3302 if (options->HttpProxy) { /* parse it now */
3303 if (parse_addr_port(LOG_WARN, options->HttpProxy, NULL,
3304 &options->HttpProxyAddr, &options->HttpProxyPort) < 0)
3305 REJECT("HttpProxy failed to parse or resolve. Please fix.");
3306 if (options->HttpProxyPort == 0) { /* give it a default */
3307 options->HttpProxyPort = 80;
3311 if (options->HttpProxyAuthenticator) {
3312 if (strlen(options->HttpProxyAuthenticator) >= 48)
3313 REJECT("HttpProxyAuthenticator is too long (>= 48 chars).");
3316 if (options->HttpsProxy) { /* parse it now */
3317 if (parse_addr_port(LOG_WARN, options->HttpsProxy, NULL,
3318 &options->HttpsProxyAddr, &options->HttpsProxyPort) <0)
3319 REJECT("HttpsProxy failed to parse or resolve. Please fix.");
3320 if (options->HttpsProxyPort == 0) { /* give it a default */
3321 options->HttpsProxyPort = 443;
3325 if (options->HttpsProxyAuthenticator) {
3326 if (strlen(options->HttpsProxyAuthenticator) >= 48)
3327 REJECT("HttpsProxyAuthenticator is too long (>= 48 chars).");
3330 if (options->HashedControlPassword) {
3331 smartlist_t *sl = decode_hashed_passwords(options->HashedControlPassword);
3332 if (!sl) {
3333 REJECT("Bad HashedControlPassword: wrong length or bad encoding");
3334 } else {
3335 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3336 smartlist_free(sl);
3340 if (options->HashedControlSessionPassword) {
3341 smartlist_t *sl = decode_hashed_passwords(
3342 options->HashedControlSessionPassword);
3343 if (!sl) {
3344 REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
3345 } else {
3346 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3347 smartlist_free(sl);
3351 if (options->ControlListenAddress) {
3352 int all_are_local = 1;
3353 config_line_t *ln;
3354 for (ln = options->ControlListenAddress; ln; ln = ln->next) {
3355 if (strcmpstart(ln->value, "127."))
3356 all_are_local = 0;
3358 if (!all_are_local) {
3359 if (!options->HashedControlPassword &&
3360 !options->HashedControlSessionPassword &&
3361 !options->CookieAuthentication) {
3362 log_warn(LD_CONFIG, "You have a ControlListenAddress set to accept "
3363 "connections from a non-local address. This means that "
3364 "any program on the internet can reconfigure your Tor. "
3365 "That's so bad that I'm closing your ControlPort for you.");
3366 options->ControlPort = 0;
3367 } else {
3368 log_warn(LD_CONFIG, "You have a ControlListenAddress set to accept "
3369 "connections from a non-local address. This means that "
3370 "programs not running on your computer can reconfigure your "
3371 "Tor. That's pretty bad!");
3376 if (options->ControlPort && !options->HashedControlPassword &&
3377 !options->HashedControlSessionPassword &&
3378 !options->CookieAuthentication) {
3379 log_warn(LD_CONFIG, "ControlPort is open, but no authentication method "
3380 "has been configured. This means that any program on your "
3381 "computer can reconfigure your Tor. That's bad! You should "
3382 "upgrade your Tor controller as soon as possible.");
3385 if (options->UseEntryGuards && ! options->NumEntryGuards)
3386 REJECT("Cannot enable UseEntryGuards with NumEntryGuards set to 0");
3388 if (check_nickname_list(options->MyFamily, "MyFamily", msg))
3389 return -1;
3390 for (cl = options->NodeFamilies; cl; cl = cl->next) {
3391 if (check_nickname_list(cl->value, "NodeFamily", msg))
3392 return -1;
3395 if (validate_addr_policies(options, msg) < 0)
3396 return -1;
3398 for (cl = options->RedirectExit; cl; cl = cl->next) {
3399 if (parse_redirect_line(NULL, cl, msg)<0)
3400 return -1;
3403 if (validate_dir_authorities(options, old_options) < 0)
3404 REJECT("Directory authority line did not parse. See logs for details.");
3406 if (options->UseBridges && !options->Bridges)
3407 REJECT("If you set UseBridges, you must specify at least one bridge.");
3408 if (options->UseBridges && !options->TunnelDirConns)
3409 REJECT("If you set UseBridges, you must set TunnelDirConns.");
3410 if (options->Bridges) {
3411 for (cl = options->Bridges; cl; cl = cl->next) {
3412 if (parse_bridge_line(cl->value, 1)<0)
3413 REJECT("Bridge line did not parse. See logs for details.");
3417 if (options->ConstrainedSockets) {
3418 /* If the user wants to constrain socket buffer use, make sure the desired
3419 * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
3420 if (options->ConstrainedSockSize < MIN_CONSTRAINED_TCP_BUFFER ||
3421 options->ConstrainedSockSize > MAX_CONSTRAINED_TCP_BUFFER ||
3422 options->ConstrainedSockSize % 1024) {
3423 r = tor_snprintf(buf, sizeof(buf),
3424 "ConstrainedSockSize is invalid. Must be a value between %d and %d "
3425 "in 1024 byte increments.",
3426 MIN_CONSTRAINED_TCP_BUFFER, MAX_CONSTRAINED_TCP_BUFFER);
3427 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3428 return -1;
3430 if (options->DirPort) {
3431 /* Providing cached directory entries while system TCP buffers are scarce
3432 * will exacerbate the socket errors. Suggest that this be disabled. */
3433 COMPLAIN("You have requested constrained socket buffers while also "
3434 "serving directory entries via DirPort. It is strongly "
3435 "suggested that you disable serving directory requests when "
3436 "system TCP buffer resources are scarce.");
3440 if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
3441 options->V3AuthVotingInterval/2) {
3442 REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
3443 "V3AuthVotingInterval");
3445 if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS)
3446 REJECT("V3AuthVoteDelay is way too low.");
3447 if (options->V3AuthDistDelay < MIN_DIST_SECONDS)
3448 REJECT("V3AuthDistDelay is way too low.");
3450 if (options->V3AuthNIntervalsValid < 2)
3451 REJECT("V3AuthNIntervalsValid must be at least 2.");
3453 if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL) {
3454 REJECT("V3AuthVotingInterval is insanely low.");
3455 } else if (options->V3AuthVotingInterval > 24*60*60) {
3456 REJECT("V3AuthVotingInterval is insanely high.");
3457 } else if (((24*60*60) % options->V3AuthVotingInterval) != 0) {
3458 COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
3461 if (rend_config_services(options, 1) < 0)
3462 REJECT("Failed to configure rendezvous options. See logs for details.");
3464 /* Parse client-side authorization for hidden services. */
3465 if (rend_parse_service_authorization(options, 1) < 0)
3466 REJECT("Failed to configure client authorization for hidden services. "
3467 "See logs for details.");
3469 if (parse_virtual_addr_network(options->VirtualAddrNetwork, 1, NULL)<0)
3470 return -1;
3472 if (options->PreferTunneledDirConns && !options->TunnelDirConns)
3473 REJECT("Must set TunnelDirConns if PreferTunneledDirConns is set.");
3475 if (options->AutomapHostsSuffixes) {
3476 SMARTLIST_FOREACH(options->AutomapHostsSuffixes, char *, suf,
3478 size_t len = strlen(suf);
3479 if (len && suf[len-1] == '.')
3480 suf[len-1] = '\0';
3484 if (options->TestingTorNetwork && !options->DirServers) {
3485 REJECT("TestingTorNetwork may only be configured in combination with "
3486 "a non-default set of DirServers.");
3489 /*XXXX021 checking for defaults manually like this is a bit fragile.*/
3491 /* Keep changes to hard-coded values synchronous to man page and default
3492 * values table. */
3493 if (options->TestingV3AuthInitialVotingInterval != 30*60 &&
3494 !options->TestingTorNetwork) {
3495 REJECT("TestingV3AuthInitialVotingInterval may only be changed in testing "
3496 "Tor networks!");
3497 } else if (options->TestingV3AuthInitialVotingInterval < MIN_VOTE_INTERVAL) {
3498 REJECT("TestingV3AuthInitialVotingInterval is insanely low.");
3499 } else if (((30*60) % options->TestingV3AuthInitialVotingInterval) != 0) {
3500 REJECT("TestingV3AuthInitialVotingInterval does not divide evenly into "
3501 "30 minutes.");
3504 if (options->TestingV3AuthInitialVoteDelay != 5*60 &&
3505 !options->TestingTorNetwork) {
3506 REJECT("TestingV3AuthInitialVoteDelay may only be changed in testing "
3507 "Tor networks!");
3508 } else if (options->TestingV3AuthInitialVoteDelay < MIN_VOTE_SECONDS) {
3509 REJECT("TestingV3AuthInitialVoteDelay is way too low.");
3512 if (options->TestingV3AuthInitialDistDelay != 5*60 &&
3513 !options->TestingTorNetwork) {
3514 REJECT("TestingV3AuthInitialDistDelay may only be changed in testing "
3515 "Tor networks!");
3516 } else if (options->TestingV3AuthInitialDistDelay < MIN_DIST_SECONDS) {
3517 REJECT("TestingV3AuthInitialDistDelay is way too low.");
3520 if (options->TestingV3AuthInitialVoteDelay +
3521 options->TestingV3AuthInitialDistDelay >=
3522 options->TestingV3AuthInitialVotingInterval/2) {
3523 REJECT("TestingV3AuthInitialVoteDelay plus TestingV3AuthInitialDistDelay "
3524 "must be less than half TestingV3AuthInitialVotingInterval");
3527 if (options->TestingAuthDirTimeToLearnReachability != 30*60 &&
3528 !options->TestingTorNetwork) {
3529 REJECT("TestingAuthDirTimeToLearnReachability may only be changed in "
3530 "testing Tor networks!");
3531 } else if (options->TestingAuthDirTimeToLearnReachability < 0) {
3532 REJECT("TestingAuthDirTimeToLearnReachability must be non-negative.");
3533 } else if (options->TestingAuthDirTimeToLearnReachability > 2*60*60) {
3534 COMPLAIN("TestingAuthDirTimeToLearnReachability is insanely high.");
3537 if (options->TestingEstimatedDescriptorPropagationTime != 10*60 &&
3538 !options->TestingTorNetwork) {
3539 REJECT("TestingEstimatedDescriptorPropagationTime may only be changed in "
3540 "testing Tor networks!");
3541 } else if (options->TestingEstimatedDescriptorPropagationTime < 0) {
3542 REJECT("TestingEstimatedDescriptorPropagationTime must be non-negative.");
3543 } else if (options->TestingEstimatedDescriptorPropagationTime > 60*60) {
3544 COMPLAIN("TestingEstimatedDescriptorPropagationTime is insanely high.");
3547 if (options->TestingTorNetwork) {
3548 log_warn(LD_CONFIG, "TestingTorNetwork is set. This will make your node "
3549 "almost unusable in the public Tor network, and is "
3550 "therefore only advised if you are building a "
3551 "testing Tor network!");
3554 return 0;
3555 #undef REJECT
3556 #undef COMPLAIN
3559 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
3560 * equal strings. */
3561 static int
3562 opt_streq(const char *s1, const char *s2)
3564 if (!s1 && !s2)
3565 return 1;
3566 else if (s1 && s2 && !strcmp(s1,s2))
3567 return 1;
3568 else
3569 return 0;
3572 /** Check if any of the previous options have changed but aren't allowed to. */
3573 static int
3574 options_transition_allowed(or_options_t *old, or_options_t *new_val,
3575 char **msg)
3577 if (!old)
3578 return 0;
3580 if (!opt_streq(old->PidFile, new_val->PidFile)) {
3581 *msg = tor_strdup("PidFile is not allowed to change.");
3582 return -1;
3585 if (old->RunAsDaemon != new_val->RunAsDaemon) {
3586 *msg = tor_strdup("While Tor is running, changing RunAsDaemon "
3587 "is not allowed.");
3588 return -1;
3591 if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
3592 char buf[1024];
3593 int r = tor_snprintf(buf, sizeof(buf),
3594 "While Tor is running, changing DataDirectory "
3595 "(\"%s\"->\"%s\") is not allowed.",
3596 old->DataDirectory, new_val->DataDirectory);
3597 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3598 return -1;
3601 if (!opt_streq(old->User, new_val->User)) {
3602 *msg = tor_strdup("While Tor is running, changing User is not allowed.");
3603 return -1;
3606 if (!opt_streq(old->Group, new_val->Group)) {
3607 *msg = tor_strdup("While Tor is running, changing Group is not allowed.");
3608 return -1;
3611 if (old->HardwareAccel != new_val->HardwareAccel) {
3612 *msg = tor_strdup("While Tor is running, changing HardwareAccel is "
3613 "not allowed.");
3614 return -1;
3617 if (old->TestingTorNetwork != new_val->TestingTorNetwork) {
3618 *msg = tor_strdup("While Tor is running, changing TestingTorNetwork "
3619 "is not allowed.");
3620 return -1;
3623 return 0;
3626 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3627 * will require us to rotate the cpu and dns workers; else return 0. */
3628 static int
3629 options_transition_affects_workers(or_options_t *old_options,
3630 or_options_t *new_options)
3632 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
3633 old_options->NumCpus != new_options->NumCpus ||
3634 old_options->ORPort != new_options->ORPort ||
3635 old_options->ServerDNSSearchDomains !=
3636 new_options->ServerDNSSearchDomains ||
3637 old_options->SafeLogging != new_options->SafeLogging ||
3638 old_options->ClientOnly != new_options->ClientOnly ||
3639 !config_lines_eq(old_options->Logs, new_options->Logs))
3640 return 1;
3642 /* Check whether log options match. */
3644 /* Nothing that changed matters. */
3645 return 0;
3648 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3649 * will require us to generate a new descriptor; else return 0. */
3650 static int
3651 options_transition_affects_descriptor(or_options_t *old_options,
3652 or_options_t *new_options)
3654 /* XXX021 We can be smarter here. If your DirPort isn't being
3655 * published and you just turned it off, no need to republish. If
3656 * you changed your bandwidthrate but maxadvertisedbandwidth still
3657 * trumps, no need to republish. Etc. */
3658 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
3659 !opt_streq(old_options->Nickname,new_options->Nickname) ||
3660 !opt_streq(old_options->Address,new_options->Address) ||
3661 !config_lines_eq(old_options->ExitPolicy,new_options->ExitPolicy) ||
3662 old_options->ExitPolicyRejectPrivate !=
3663 new_options->ExitPolicyRejectPrivate ||
3664 old_options->ORPort != new_options->ORPort ||
3665 old_options->DirPort != new_options->DirPort ||
3666 old_options->ClientOnly != new_options->ClientOnly ||
3667 old_options->NoPublish != new_options->NoPublish ||
3668 old_options->_PublishServerDescriptor !=
3669 new_options->_PublishServerDescriptor ||
3670 old_options->BandwidthRate != new_options->BandwidthRate ||
3671 old_options->BandwidthBurst != new_options->BandwidthBurst ||
3672 old_options->MaxAdvertisedBandwidth !=
3673 new_options->MaxAdvertisedBandwidth ||
3674 !opt_streq(old_options->ContactInfo, new_options->ContactInfo) ||
3675 !opt_streq(old_options->MyFamily, new_options->MyFamily) ||
3676 !opt_streq(old_options->AccountingStart, new_options->AccountingStart) ||
3677 old_options->AccountingMax != new_options->AccountingMax)
3678 return 1;
3680 return 0;
3683 #ifdef MS_WINDOWS
3684 /** Return the directory on windows where we expect to find our application
3685 * data. */
3686 static char *
3687 get_windows_conf_root(void)
3689 static int is_set = 0;
3690 static char path[MAX_PATH+1];
3692 LPITEMIDLIST idl;
3693 IMalloc *m;
3694 HRESULT result;
3696 if (is_set)
3697 return path;
3699 /* Find X:\documents and settings\username\application data\ .
3700 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
3702 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, CSIDL_APPDATA,
3703 &idl))) {
3704 GetCurrentDirectory(MAX_PATH, path);
3705 is_set = 1;
3706 log_warn(LD_CONFIG,
3707 "I couldn't find your application data folder: are you "
3708 "running an ancient version of Windows 95? Defaulting to \"%s\"",
3709 path);
3710 return path;
3712 /* Convert the path from an "ID List" (whatever that is!) to a path. */
3713 result = SHGetPathFromIDList(idl, path);
3714 /* Now we need to free the */
3715 SHGetMalloc(&m);
3716 if (m) {
3717 m->lpVtbl->Free(m, idl);
3718 m->lpVtbl->Release(m);
3720 if (!SUCCEEDED(result)) {
3721 return NULL;
3723 strlcat(path,"\\tor",MAX_PATH);
3724 is_set = 1;
3725 return path;
3727 #endif
3729 /** Return the default location for our torrc file. */
3730 static const char *
3731 get_default_conf_file(void)
3733 #ifdef MS_WINDOWS
3734 static char path[MAX_PATH+1];
3735 strlcpy(path, get_windows_conf_root(), MAX_PATH);
3736 strlcat(path,"\\torrc",MAX_PATH);
3737 return path;
3738 #else
3739 return (CONFDIR "/torrc");
3740 #endif
3743 /** Verify whether lst is a string containing valid-looking comma-separated
3744 * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
3746 static int
3747 check_nickname_list(const char *lst, const char *name, char **msg)
3749 int r = 0;
3750 smartlist_t *sl;
3752 if (!lst)
3753 return 0;
3754 sl = smartlist_create();
3756 smartlist_split_string(sl, lst, ",",
3757 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK|SPLIT_STRIP_SPACE, 0);
3759 SMARTLIST_FOREACH(sl, const char *, s,
3761 if (!is_legal_nickname_or_hexdigest(s)) {
3762 char buf[1024];
3763 int tmp = tor_snprintf(buf, sizeof(buf),
3764 "Invalid nickname '%s' in %s line", s, name);
3765 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
3766 r = -1;
3767 break;
3770 SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
3771 smartlist_free(sl);
3772 return r;
3775 /** Learn config file name from command line arguments, or use the default */
3776 static char *
3777 find_torrc_filename(int argc, char **argv,
3778 int *using_default_torrc, int *ignore_missing_torrc)
3780 char *fname=NULL;
3781 int i;
3783 for (i = 1; i < argc; ++i) {
3784 if (i < argc-1 && !strcmp(argv[i],"-f")) {
3785 if (fname) {
3786 log(LOG_WARN, LD_CONFIG, "Duplicate -f options on command line.");
3787 tor_free(fname);
3789 #ifdef MS_WINDOWS
3790 /* XXX one day we might want to extend expand_filename to work
3791 * under Windows as well. */
3792 fname = tor_strdup(argv[i+1]);
3793 #else
3794 fname = expand_filename(argv[i+1]);
3795 #endif
3796 *using_default_torrc = 0;
3797 ++i;
3798 } else if (!strcmp(argv[i],"--ignore-missing-torrc")) {
3799 *ignore_missing_torrc = 1;
3803 if (*using_default_torrc) {
3804 /* didn't find one, try CONFDIR */
3805 const char *dflt = get_default_conf_file();
3806 if (dflt && file_status(dflt) == FN_FILE) {
3807 fname = tor_strdup(dflt);
3808 } else {
3809 #ifndef MS_WINDOWS
3810 char *fn;
3811 fn = expand_filename("~/.torrc");
3812 if (fn && file_status(fn) == FN_FILE) {
3813 fname = fn;
3814 } else {
3815 tor_free(fn);
3816 fname = tor_strdup(dflt);
3818 #else
3819 fname = tor_strdup(dflt);
3820 #endif
3823 return fname;
3826 /** Load torrc from disk, setting torrc_fname if successful */
3827 static char *
3828 load_torrc_from_disk(int argc, char **argv)
3830 char *fname=NULL;
3831 char *cf = NULL;
3832 int using_default_torrc = 1;
3833 int ignore_missing_torrc = 0;
3835 fname = find_torrc_filename(argc, argv,
3836 &using_default_torrc, &ignore_missing_torrc);
3837 tor_assert(fname);
3838 log(LOG_DEBUG, LD_CONFIG, "Opening config file \"%s\"", fname);
3840 tor_free(torrc_fname);
3841 torrc_fname = fname;
3843 /* Open config file */
3844 if (file_status(fname) != FN_FILE ||
3845 !(cf = read_file_to_str(fname,0,NULL))) {
3846 if (using_default_torrc == 1 || ignore_missing_torrc ) {
3847 log(LOG_NOTICE, LD_CONFIG, "Configuration file \"%s\" not present, "
3848 "using reasonable defaults.", fname);
3849 tor_free(fname); /* sets fname to NULL */
3850 torrc_fname = NULL;
3851 cf = tor_strdup("");
3852 } else {
3853 log(LOG_WARN, LD_CONFIG,
3854 "Unable to open configuration file \"%s\".", fname);
3855 goto err;
3859 return cf;
3860 err:
3861 tor_free(fname);
3862 torrc_fname = NULL;
3863 return NULL;
3866 /** Read a configuration file into <b>options</b>, finding the configuration
3867 * file location based on the command line. After loading the file
3868 * call options_init_from_string() to load the config.
3869 * Return 0 if success, -1 if failure. */
3871 options_init_from_torrc(int argc, char **argv)
3873 char *cf=NULL;
3874 int i, retval, command;
3875 static char **backup_argv;
3876 static int backup_argc;
3877 char *command_arg = NULL;
3878 char *errmsg=NULL;
3880 if (argv) { /* first time we're called. save commandline args */
3881 backup_argv = argv;
3882 backup_argc = argc;
3883 } else { /* we're reloading. need to clean up old options first. */
3884 argv = backup_argv;
3885 argc = backup_argc;
3887 if (argc > 1 && (!strcmp(argv[1], "-h") || !strcmp(argv[1],"--help"))) {
3888 print_usage();
3889 exit(0);
3891 if (argc > 1 && !strcmp(argv[1], "--list-torrc-options")) {
3892 /* For documenting validating whether we've documented everything. */
3893 list_torrc_options();
3894 exit(0);
3897 if (argc > 1 && (!strcmp(argv[1],"--version"))) {
3898 printf("Tor version %s.\n",get_version());
3899 if (argc > 2 && (!strcmp(argv[2],"--version"))) {
3900 print_svn_version();
3902 exit(0);
3905 /* Go through command-line variables */
3906 if (!global_cmdline_options) {
3907 /* Or we could redo the list every time we pass this place.
3908 * It does not really matter */
3909 if (config_get_commandlines(argc, argv, &global_cmdline_options) < 0) {
3910 goto err;
3914 command = CMD_RUN_TOR;
3915 for (i = 1; i < argc; ++i) {
3916 if (!strcmp(argv[i],"--list-fingerprint")) {
3917 command = CMD_LIST_FINGERPRINT;
3918 } else if (!strcmp(argv[i],"--hash-password")) {
3919 command = CMD_HASH_PASSWORD;
3920 command_arg = tor_strdup( (i < argc-1) ? argv[i+1] : "");
3921 ++i;
3922 } else if (!strcmp(argv[i],"--verify-config")) {
3923 command = CMD_VERIFY_CONFIG;
3927 if (command == CMD_HASH_PASSWORD) {
3928 cf = tor_strdup("");
3929 } else {
3930 cf = load_torrc_from_disk(argc, argv);
3931 if (!cf)
3932 goto err;
3935 retval = options_init_from_string(cf, command, command_arg, &errmsg);
3936 tor_free(cf);
3937 if (retval < 0)
3938 goto err;
3940 return 0;
3942 err:
3943 if (errmsg) {
3944 log(LOG_WARN,LD_CONFIG,"%s", errmsg);
3945 tor_free(errmsg);
3947 return -1;
3950 /** Load the options from the configuration in <b>cf</b>, validate
3951 * them for consistency and take actions based on them.
3953 * Return 0 if success, negative on error:
3954 * * -1 for general errors.
3955 * * -2 for failure to parse/validate,
3956 * * -3 for transition not allowed
3957 * * -4 for error while setting the new options
3959 setopt_err_t
3960 options_init_from_string(const char *cf,
3961 int command, const char *command_arg,
3962 char **msg)
3964 or_options_t *oldoptions, *newoptions;
3965 config_line_t *cl;
3966 int retval;
3967 setopt_err_t err = SETOPT_ERR_MISC;
3968 tor_assert(msg);
3970 oldoptions = global_options; /* get_options unfortunately asserts if
3971 this is the first time we run*/
3973 newoptions = tor_malloc_zero(sizeof(or_options_t));
3974 newoptions->_magic = OR_OPTIONS_MAGIC;
3975 options_init(newoptions);
3976 newoptions->command = command;
3977 newoptions->command_arg = command_arg;
3979 /* get config lines, assign them */
3980 retval = config_get_lines(cf, &cl);
3981 if (retval < 0) {
3982 err = SETOPT_ERR_PARSE;
3983 goto err;
3985 retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
3986 config_free_lines(cl);
3987 if (retval < 0) {
3988 err = SETOPT_ERR_PARSE;
3989 goto err;
3992 /* Go through command-line variables too */
3993 retval = config_assign(&options_format, newoptions,
3994 global_cmdline_options, 0, 0, msg);
3995 if (retval < 0) {
3996 err = SETOPT_ERR_PARSE;
3997 goto err;
4000 /* If this is a testing network configuration, change defaults
4001 * for a list of dependent config options, re-initialize newoptions
4002 * with the new defaults, and assign all options to it second time. */
4003 if (newoptions->TestingTorNetwork) {
4004 /* XXXX021 this is a bit of a kludge. perhaps there's a better way to do
4005 * this? We could, for example, make the parsing algorithm do two passes
4006 * over the configuration. If it finds any "suite" options like
4007 * TestingTorNetwork, it could change the defaults before its second pass.
4008 * Not urgent so long as this seems to work, but at any sign of trouble,
4009 * let's clean it up. -NM */
4011 /* Change defaults. */
4012 int i;
4013 for (i = 0; testing_tor_network_defaults[i].name; ++i) {
4014 config_var_t *new_var = &testing_tor_network_defaults[i];
4015 config_var_t *old_var =
4016 config_find_option(&options_format, new_var->name);
4017 tor_assert(new_var);
4018 tor_assert(old_var);
4019 old_var->initvalue = new_var->initvalue;
4022 /* Clear newoptions and re-initialize them with new defaults. */
4023 config_free(&options_format, newoptions);
4024 newoptions = tor_malloc_zero(sizeof(or_options_t));
4025 newoptions->_magic = OR_OPTIONS_MAGIC;
4026 options_init(newoptions);
4027 newoptions->command = command;
4028 newoptions->command_arg = command_arg;
4030 /* Assign all options a second time. */
4031 retval = config_get_lines(cf, &cl);
4032 if (retval < 0) {
4033 err = SETOPT_ERR_PARSE;
4034 goto err;
4036 retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
4037 config_free_lines(cl);
4038 if (retval < 0) {
4039 err = SETOPT_ERR_PARSE;
4040 goto err;
4042 retval = config_assign(&options_format, newoptions,
4043 global_cmdline_options, 0, 0, msg);
4044 if (retval < 0) {
4045 err = SETOPT_ERR_PARSE;
4046 goto err;
4050 /* Validate newoptions */
4051 if (options_validate(oldoptions, newoptions, 0, msg) < 0) {
4052 err = SETOPT_ERR_PARSE; /*XXX021 make this separate.*/
4053 goto err;
4056 if (options_transition_allowed(oldoptions, newoptions, msg) < 0) {
4057 err = SETOPT_ERR_TRANSITION;
4058 goto err;
4061 if (set_options(newoptions, msg)) {
4062 err = SETOPT_ERR_SETTING;
4063 goto err; /* frees and replaces old options */
4066 return SETOPT_OK;
4068 err:
4069 config_free(&options_format, newoptions);
4070 if (*msg) {
4071 int len = strlen(*msg)+256;
4072 char *newmsg = tor_malloc(len);
4074 tor_snprintf(newmsg, len, "Failed to parse/validate config: %s", *msg);
4075 tor_free(*msg);
4076 *msg = newmsg;
4078 return err;
4081 /** Return the location for our configuration file.
4083 const char *
4084 get_torrc_fname(void)
4086 if (torrc_fname)
4087 return torrc_fname;
4088 else
4089 return get_default_conf_file();
4092 /** Adjust the address map mased on the MapAddress elements in the
4093 * configuration <b>options</b>
4095 static void
4096 config_register_addressmaps(or_options_t *options)
4098 smartlist_t *elts;
4099 config_line_t *opt;
4100 char *from, *to;
4102 addressmap_clear_configured();
4103 elts = smartlist_create();
4104 for (opt = options->AddressMap; opt; opt = opt->next) {
4105 smartlist_split_string(elts, opt->value, NULL,
4106 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
4107 if (smartlist_len(elts) >= 2) {
4108 from = smartlist_get(elts,0);
4109 to = smartlist_get(elts,1);
4110 if (address_is_invalid_destination(to, 1)) {
4111 log_warn(LD_CONFIG,
4112 "Skipping invalid argument '%s' to MapAddress", to);
4113 } else {
4114 addressmap_register(from, tor_strdup(to), 0, ADDRMAPSRC_TORRC);
4115 if (smartlist_len(elts)>2) {
4116 log_warn(LD_CONFIG,"Ignoring extra arguments to MapAddress.");
4119 } else {
4120 log_warn(LD_CONFIG,"MapAddress '%s' has too few arguments. Ignoring.",
4121 opt->value);
4123 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
4124 smartlist_clear(elts);
4126 smartlist_free(elts);
4130 * Initialize the logs based on the configuration file.
4132 static int
4133 options_init_logs(or_options_t *options, int validate_only)
4135 config_line_t *opt;
4136 int ok;
4137 smartlist_t *elts;
4138 int daemon =
4139 #ifdef MS_WINDOWS
4141 #else
4142 options->RunAsDaemon;
4143 #endif
4145 ok = 1;
4146 elts = smartlist_create();
4148 for (opt = options->Logs; opt; opt = opt->next) {
4149 log_severity_list_t *severity;
4150 const char *cfg = opt->value;
4151 severity = tor_malloc_zero(sizeof(log_severity_list_t));
4152 if (parse_log_severity_config(&cfg, severity) < 0) {
4153 log_warn(LD_CONFIG, "Couldn't parse log levels in Log option 'Log %s'",
4154 opt->value);
4155 ok = 0; goto cleanup;
4158 smartlist_split_string(elts, cfg, NULL,
4159 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
4161 if (smartlist_len(elts) == 0)
4162 smartlist_add(elts, tor_strdup("stdout"));
4164 if (smartlist_len(elts) == 1 &&
4165 (!strcasecmp(smartlist_get(elts,0), "stdout") ||
4166 !strcasecmp(smartlist_get(elts,0), "stderr"))) {
4167 int err = smartlist_len(elts) &&
4168 !strcasecmp(smartlist_get(elts,0), "stderr");
4169 if (!validate_only) {
4170 if (daemon) {
4171 log_warn(LD_CONFIG,
4172 "Can't log to %s with RunAsDaemon set; skipping stdout",
4173 err?"stderr":"stdout");
4174 } else {
4175 add_stream_log(severity, err?"<stderr>":"<stdout>",
4176 err?stderr:stdout);
4179 goto cleanup;
4181 if (smartlist_len(elts) == 1 &&
4182 !strcasecmp(smartlist_get(elts,0), "syslog")) {
4183 #ifdef HAVE_SYSLOG_H
4184 if (!validate_only) {
4185 add_syslog_log(severity);
4187 #else
4188 log_warn(LD_CONFIG, "Syslog is not supported on this system. Sorry.");
4189 #endif
4190 goto cleanup;
4193 if (smartlist_len(elts) == 2 &&
4194 !strcasecmp(smartlist_get(elts,0), "file")) {
4195 if (!validate_only) {
4196 if (add_file_log(severity, smartlist_get(elts, 1)) < 0) {
4197 log_warn(LD_CONFIG, "Couldn't open file for 'Log %s': %s",
4198 opt->value, strerror(errno));
4199 ok = 0;
4202 goto cleanup;
4205 log_warn(LD_CONFIG, "Bad syntax on file Log option 'Log %s'",
4206 opt->value);
4207 ok = 0; goto cleanup;
4209 cleanup:
4210 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
4211 smartlist_clear(elts);
4212 tor_free(severity);
4214 smartlist_free(elts);
4216 return ok?0:-1;
4219 /** Parse a single RedirectExit line's contents from <b>line</b>. If
4220 * they are valid, and <b>result</b> is not NULL, add an element to
4221 * <b>result</b> and return 0. Else if they are valid, return 0.
4222 * Else set *msg and return -1. */
4223 static int
4224 parse_redirect_line(smartlist_t *result, config_line_t *line, char **msg)
4226 smartlist_t *elements = NULL;
4227 exit_redirect_t *r;
4229 tor_assert(line);
4231 r = tor_malloc_zero(sizeof(exit_redirect_t));
4232 elements = smartlist_create();
4233 smartlist_split_string(elements, line->value, NULL,
4234 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
4235 if (smartlist_len(elements) != 2) {
4236 *msg = tor_strdup("Wrong number of elements in RedirectExit line");
4237 goto err;
4239 if (tor_addr_parse_mask_ports(smartlist_get(elements,0),&r->addr,
4240 &r->maskbits,&r->port_min,&r->port_max)) {
4241 *msg = tor_strdup("Error parsing source address in RedirectExit line");
4242 goto err;
4244 if (0==strcasecmp(smartlist_get(elements,1), "pass")) {
4245 r->is_redirect = 0;
4246 } else {
4247 if (tor_addr_port_parse(smartlist_get(elements,1),
4248 &r->addr_dest, &r->port_dest)) {
4249 *msg = tor_strdup("Error parsing dest address in RedirectExit line");
4250 goto err;
4252 r->is_redirect = 1;
4255 goto done;
4256 err:
4257 tor_free(r);
4258 done:
4259 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
4260 smartlist_free(elements);
4261 if (r) {
4262 if (result)
4263 smartlist_add(result, r);
4264 else
4265 tor_free(r);
4266 return 0;
4267 } else {
4268 tor_assert(*msg);
4269 return -1;
4273 /** Read the contents of a Bridge line from <b>line</b>. Return 0
4274 * if the line is well-formed, and -1 if it isn't. If
4275 * <b>validate_only</b> is 0, and the line is well-formed, then add
4276 * the bridge described in the line to our internal bridge list. */
4277 static int
4278 parse_bridge_line(const char *line, int validate_only)
4280 smartlist_t *items = NULL;
4281 int r;
4282 char *addrport=NULL, *fingerprint=NULL;
4283 tor_addr_t addr;
4284 uint16_t port = 0;
4285 char digest[DIGEST_LEN];
4287 items = smartlist_create();
4288 smartlist_split_string(items, line, NULL,
4289 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4290 if (smartlist_len(items) < 1) {
4291 log_warn(LD_CONFIG, "Too few arguments to Bridge line.");
4292 goto err;
4294 addrport = smartlist_get(items, 0);
4295 smartlist_del_keeporder(items, 0);
4296 if (tor_addr_port_parse(addrport, &addr, &port)<0) {
4297 log_warn(LD_CONFIG, "Error parsing Bridge address '%s'", addrport);
4298 goto err;
4300 if (!port) {
4301 log_warn(LD_CONFIG, "Missing port in Bridge address '%s'",addrport);
4302 goto err;
4305 if (smartlist_len(items)) {
4306 fingerprint = smartlist_join_strings(items, "", 0, NULL);
4307 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
4308 log_warn(LD_CONFIG, "Key digest for Bridge is wrong length.");
4309 goto err;
4311 if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
4312 log_warn(LD_CONFIG, "Unable to decode Bridge key digest.");
4313 goto err;
4317 if (!validate_only) {
4318 log_debug(LD_DIR, "Bridge at %s:%d (%s)", fmt_addr(&addr),
4319 (int)port,
4320 fingerprint ? fingerprint : "no key listed");
4321 bridge_add_from_config(&addr, port, fingerprint ? digest : NULL);
4324 r = 0;
4325 goto done;
4327 err:
4328 r = -1;
4330 done:
4331 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4332 smartlist_free(items);
4333 tor_free(addrport);
4334 tor_free(fingerprint);
4335 return r;
4338 /** Read the contents of a DirServer line from <b>line</b>. If
4339 * <b>validate_only</b> is 0, and the line is well-formed, and it
4340 * shares any bits with <b>required_type</b> or <b>required_type</b>
4341 * is 0, then add the dirserver described in the line (minus whatever
4342 * bits it's missing) as a valid authority. Return 0 on success,
4343 * or -1 if the line isn't well-formed or if we can't add it. */
4344 static int
4345 parse_dir_server_line(const char *line, authority_type_t required_type,
4346 int validate_only)
4348 smartlist_t *items = NULL;
4349 int r;
4350 char *addrport=NULL, *address=NULL, *nickname=NULL, *fingerprint=NULL;
4351 uint16_t dir_port = 0, or_port = 0;
4352 char digest[DIGEST_LEN];
4353 char v3_digest[DIGEST_LEN];
4354 authority_type_t type = V2_AUTHORITY;
4355 int is_not_hidserv_authority = 0, is_not_v2_authority = 0;
4357 items = smartlist_create();
4358 smartlist_split_string(items, line, NULL,
4359 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4360 if (smartlist_len(items) < 1) {
4361 log_warn(LD_CONFIG, "No arguments on DirServer line.");
4362 goto err;
4365 if (is_legal_nickname(smartlist_get(items, 0))) {
4366 nickname = smartlist_get(items, 0);
4367 smartlist_del_keeporder(items, 0);
4370 while (smartlist_len(items)) {
4371 char *flag = smartlist_get(items, 0);
4372 if (TOR_ISDIGIT(flag[0]))
4373 break;
4374 if (!strcasecmp(flag, "v1")) {
4375 type |= (V1_AUTHORITY | HIDSERV_AUTHORITY);
4376 } else if (!strcasecmp(flag, "hs")) {
4377 type |= HIDSERV_AUTHORITY;
4378 } else if (!strcasecmp(flag, "no-hs")) {
4379 is_not_hidserv_authority = 1;
4380 } else if (!strcasecmp(flag, "bridge")) {
4381 type |= BRIDGE_AUTHORITY;
4382 } else if (!strcasecmp(flag, "no-v2")) {
4383 is_not_v2_authority = 1;
4384 } else if (!strcasecmpstart(flag, "orport=")) {
4385 int ok;
4386 char *portstring = flag + strlen("orport=");
4387 or_port = (uint16_t) tor_parse_long(portstring, 10, 1, 65535, &ok, NULL);
4388 if (!ok)
4389 log_warn(LD_CONFIG, "Invalid orport '%s' on DirServer line.",
4390 portstring);
4391 } else if (!strcasecmpstart(flag, "v3ident=")) {
4392 char *idstr = flag + strlen("v3ident=");
4393 if (strlen(idstr) != HEX_DIGEST_LEN ||
4394 base16_decode(v3_digest, DIGEST_LEN, idstr, HEX_DIGEST_LEN)<0) {
4395 log_warn(LD_CONFIG, "Bad v3 identity digest '%s' on DirServer line",
4396 flag);
4397 } else {
4398 type |= V3_AUTHORITY;
4400 } else {
4401 log_warn(LD_CONFIG, "Unrecognized flag '%s' on DirServer line",
4402 flag);
4404 tor_free(flag);
4405 smartlist_del_keeporder(items, 0);
4407 if (is_not_hidserv_authority)
4408 type &= ~HIDSERV_AUTHORITY;
4409 if (is_not_v2_authority)
4410 type &= ~V2_AUTHORITY;
4412 if (smartlist_len(items) < 2) {
4413 log_warn(LD_CONFIG, "Too few arguments to DirServer line.");
4414 goto err;
4416 addrport = smartlist_get(items, 0);
4417 smartlist_del_keeporder(items, 0);
4418 if (parse_addr_port(LOG_WARN, addrport, &address, NULL, &dir_port)<0) {
4419 log_warn(LD_CONFIG, "Error parsing DirServer address '%s'", addrport);
4420 goto err;
4422 if (!dir_port) {
4423 log_warn(LD_CONFIG, "Missing port in DirServer address '%s'",addrport);
4424 goto err;
4427 fingerprint = smartlist_join_strings(items, "", 0, NULL);
4428 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
4429 log_warn(LD_CONFIG, "Key digest for DirServer is wrong length %d.",
4430 (int)strlen(fingerprint));
4431 goto err;
4433 if (!strcmp(fingerprint, "E623F7625FBE0C87820F11EC5F6D5377ED816294")) {
4434 /* a known bad fingerprint. refuse to use it. We can remove this
4435 * clause once Tor 0.1.2.17 is obsolete. */
4436 log_warn(LD_CONFIG, "Dangerous dirserver line. To correct, erase your "
4437 "torrc file (%s), or reinstall Tor and use the default torrc.",
4438 get_torrc_fname());
4439 goto err;
4441 if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
4442 log_warn(LD_CONFIG, "Unable to decode DirServer key digest.");
4443 goto err;
4446 if (!validate_only && (!required_type || required_type & type)) {
4447 if (required_type)
4448 type &= required_type; /* pare down what we think of them as an
4449 * authority for. */
4450 log_debug(LD_DIR, "Trusted %d dirserver at %s:%d (%s)", (int)type,
4451 address, (int)dir_port, (char*)smartlist_get(items,0));
4452 if (!add_trusted_dir_server(nickname, address, dir_port, or_port,
4453 digest, v3_digest, type))
4454 goto err;
4457 r = 0;
4458 goto done;
4460 err:
4461 r = -1;
4463 done:
4464 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4465 smartlist_free(items);
4466 tor_free(addrport);
4467 tor_free(address);
4468 tor_free(nickname);
4469 tor_free(fingerprint);
4470 return r;
4473 /** Adjust the value of options->DataDirectory, or fill it in if it's
4474 * absent. Return 0 on success, -1 on failure. */
4475 static int
4476 normalize_data_directory(or_options_t *options)
4478 #ifdef MS_WINDOWS
4479 char *p;
4480 if (options->DataDirectory)
4481 return 0; /* all set */
4482 p = tor_malloc(MAX_PATH);
4483 strlcpy(p,get_windows_conf_root(),MAX_PATH);
4484 options->DataDirectory = p;
4485 return 0;
4486 #else
4487 const char *d = options->DataDirectory;
4488 if (!d)
4489 d = "~/.tor";
4491 if (strncmp(d,"~/",2) == 0) {
4492 char *fn = expand_filename(d);
4493 if (!fn) {
4494 log_warn(LD_CONFIG,"Failed to expand filename \"%s\".", d);
4495 return -1;
4497 if (!options->DataDirectory && !strcmp(fn,"/.tor")) {
4498 /* If our homedir is /, we probably don't want to use it. */
4499 /* Default to LOCALSTATEDIR/tor which is probably closer to what we
4500 * want. */
4501 log_warn(LD_CONFIG,
4502 "Default DataDirectory is \"~/.tor\". This expands to "
4503 "\"%s\", which is probably not what you want. Using "
4504 "\"%s"PATH_SEPARATOR"tor\" instead", fn, LOCALSTATEDIR);
4505 tor_free(fn);
4506 fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor");
4508 tor_free(options->DataDirectory);
4509 options->DataDirectory = fn;
4511 return 0;
4512 #endif
4515 /** Check and normalize the value of options->DataDirectory; return 0 if it
4516 * sane, -1 otherwise. */
4517 static int
4518 validate_data_directory(or_options_t *options)
4520 if (normalize_data_directory(options) < 0)
4521 return -1;
4522 tor_assert(options->DataDirectory);
4523 if (strlen(options->DataDirectory) > (512-128)) {
4524 log_warn(LD_CONFIG, "DataDirectory is too long.");
4525 return -1;
4527 return 0;
4530 /** This string must remain the same forevermore. It is how we
4531 * recognize that the torrc file doesn't need to be backed up. */
4532 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
4533 "if you edit it, comments will not be preserved"
4534 /** This string can change; it tries to give the reader an idea
4535 * that editing this file by hand is not a good plan. */
4536 #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
4537 "to torrc.orig.1 or similar, and Tor will ignore it"
4539 /** Save a configuration file for the configuration in <b>options</b>
4540 * into the file <b>fname</b>. If the file already exists, and
4541 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
4542 * replace it. Return 0 on success, -1 on failure. */
4543 static int
4544 write_configuration_file(const char *fname, or_options_t *options)
4546 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
4547 int rename_old = 0, r;
4548 size_t len;
4550 tor_assert(fname);
4552 switch (file_status(fname)) {
4553 case FN_FILE:
4554 old_val = read_file_to_str(fname, 0, NULL);
4555 if (strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
4556 rename_old = 1;
4558 tor_free(old_val);
4559 break;
4560 case FN_NOENT:
4561 break;
4562 case FN_ERROR:
4563 case FN_DIR:
4564 default:
4565 log_warn(LD_CONFIG,
4566 "Config file \"%s\" is not a file? Failing.", fname);
4567 return -1;
4570 if (!(new_conf = options_dump(options, 1))) {
4571 log_warn(LD_BUG, "Couldn't get configuration string");
4572 goto err;
4575 len = strlen(new_conf)+256;
4576 new_val = tor_malloc(len);
4577 tor_snprintf(new_val, len, "%s\n%s\n\n%s",
4578 GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
4580 if (rename_old) {
4581 int i = 1;
4582 size_t fn_tmp_len = strlen(fname)+32;
4583 char *fn_tmp;
4584 tor_assert(fn_tmp_len > strlen(fname)); /*check for overflow*/
4585 fn_tmp = tor_malloc(fn_tmp_len);
4586 while (1) {
4587 if (tor_snprintf(fn_tmp, fn_tmp_len, "%s.orig.%d", fname, i)<0) {
4588 log_warn(LD_BUG, "tor_snprintf failed inexplicably");
4589 tor_free(fn_tmp);
4590 goto err;
4592 if (file_status(fn_tmp) == FN_NOENT)
4593 break;
4594 ++i;
4596 log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
4597 if (rename(fname, fn_tmp) < 0) {
4598 log_warn(LD_FS,
4599 "Couldn't rename configuration file \"%s\" to \"%s\": %s",
4600 fname, fn_tmp, strerror(errno));
4601 tor_free(fn_tmp);
4602 goto err;
4604 tor_free(fn_tmp);
4607 if (write_str_to_file(fname, new_val, 0) < 0)
4608 goto err;
4610 r = 0;
4611 goto done;
4612 err:
4613 r = -1;
4614 done:
4615 tor_free(new_val);
4616 tor_free(new_conf);
4617 return r;
4621 * Save the current configuration file value to disk. Return 0 on
4622 * success, -1 on failure.
4625 options_save_current(void)
4627 if (torrc_fname) {
4628 /* This fails if we can't write to our configuration file.
4630 * If we try falling back to datadirectory or something, we have a better
4631 * chance of saving the configuration, but a better chance of doing
4632 * something the user never expected. Let's just warn instead. */
4633 return write_configuration_file(torrc_fname, get_options());
4635 return write_configuration_file(get_default_conf_file(), get_options());
4638 /** Mapping from a unit name to a multiplier for converting that unit into a
4639 * base unit. */
4640 struct unit_table_t {
4641 const char *unit;
4642 uint64_t multiplier;
4645 static struct unit_table_t memory_units[] = {
4646 { "", 1 },
4647 { "b", 1<< 0 },
4648 { "byte", 1<< 0 },
4649 { "bytes", 1<< 0 },
4650 { "kb", 1<<10 },
4651 { "kbyte", 1<<10 },
4652 { "kbytes", 1<<10 },
4653 { "kilobyte", 1<<10 },
4654 { "kilobytes", 1<<10 },
4655 { "m", 1<<20 },
4656 { "mb", 1<<20 },
4657 { "mbyte", 1<<20 },
4658 { "mbytes", 1<<20 },
4659 { "megabyte", 1<<20 },
4660 { "megabytes", 1<<20 },
4661 { "gb", 1<<30 },
4662 { "gbyte", 1<<30 },
4663 { "gbytes", 1<<30 },
4664 { "gigabyte", 1<<30 },
4665 { "gigabytes", 1<<30 },
4666 { "tb", U64_LITERAL(1)<<40 },
4667 { "terabyte", U64_LITERAL(1)<<40 },
4668 { "terabytes", U64_LITERAL(1)<<40 },
4669 { NULL, 0 },
4672 static struct unit_table_t time_units[] = {
4673 { "", 1 },
4674 { "second", 1 },
4675 { "seconds", 1 },
4676 { "minute", 60 },
4677 { "minutes", 60 },
4678 { "hour", 60*60 },
4679 { "hours", 60*60 },
4680 { "day", 24*60*60 },
4681 { "days", 24*60*60 },
4682 { "week", 7*24*60*60 },
4683 { "weeks", 7*24*60*60 },
4684 { NULL, 0 },
4687 /** Parse a string <b>val</b> containing a number, zero or more
4688 * spaces, and an optional unit string. If the unit appears in the
4689 * table <b>u</b>, then multiply the number by the unit multiplier.
4690 * On success, set *<b>ok</b> to 1 and return this product.
4691 * Otherwise, set *<b>ok</b> to 0.
4693 static uint64_t
4694 config_parse_units(const char *val, struct unit_table_t *u, int *ok)
4696 uint64_t v;
4697 char *cp;
4699 tor_assert(ok);
4701 v = tor_parse_uint64(val, 10, 0, UINT64_MAX, ok, &cp);
4702 if (!*ok)
4703 return 0;
4704 if (!cp) {
4705 *ok = 1;
4706 return v;
4708 while (TOR_ISSPACE(*cp))
4709 ++cp;
4710 for ( ;u->unit;++u) {
4711 if (!strcasecmp(u->unit, cp)) {
4712 v *= u->multiplier;
4713 *ok = 1;
4714 return v;
4717 log_warn(LD_CONFIG, "Unknown unit '%s'.", cp);
4718 *ok = 0;
4719 return 0;
4722 /** Parse a string in the format "number unit", where unit is a unit of
4723 * information (byte, KB, M, etc). On success, set *<b>ok</b> to true
4724 * and return the number of bytes specified. Otherwise, set
4725 * *<b>ok</b> to false and return 0. */
4726 static uint64_t
4727 config_parse_memunit(const char *s, int *ok)
4729 return config_parse_units(s, memory_units, ok);
4732 /** Parse a string in the format "number unit", where unit is a unit of time.
4733 * On success, set *<b>ok</b> to true and return the number of seconds in
4734 * the provided interval. Otherwise, set *<b>ok</b> to 0 and return -1.
4736 static int
4737 config_parse_interval(const char *s, int *ok)
4739 uint64_t r;
4740 r = config_parse_units(s, time_units, ok);
4741 if (!ok)
4742 return -1;
4743 if (r > INT_MAX) {
4744 log_warn(LD_CONFIG, "Interval '%s' is too long", s);
4745 *ok = 0;
4746 return -1;
4748 return (int)r;
4752 * Initialize the libevent library.
4754 static void
4755 init_libevent(void)
4757 configure_libevent_logging();
4758 /* If the kernel complains that some method (say, epoll) doesn't
4759 * exist, we don't care about it, since libevent will cope.
4761 suppress_libevent_log_msg("Function not implemented");
4762 #ifdef __APPLE__
4763 if (decode_libevent_version() < LE_11B) {
4764 setenv("EVENT_NOKQUEUE","1",1);
4766 #endif
4767 event_init();
4768 suppress_libevent_log_msg(NULL);
4769 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
4770 /* Making this a NOTICE for now so we can link bugs to a libevent versions
4771 * or methods better. */
4772 log(LOG_NOTICE, LD_GENERAL,
4773 "Initialized libevent version %s using method %s. Good.",
4774 event_get_version(), event_get_method());
4775 check_libevent_version(event_get_method(), get_options()->ORPort != 0);
4776 #else
4777 log(LOG_NOTICE, LD_GENERAL,
4778 "Initialized old libevent (version 1.0b or earlier).");
4779 log(LOG_WARN, LD_GENERAL,
4780 "You have a *VERY* old version of libevent. It is likely to be buggy; "
4781 "please build Tor with a more recent version.");
4782 #endif
4785 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
4786 /** Table mapping return value of event_get_version() to le_version_t. */
4787 static const struct {
4788 const char *name; le_version_t version;
4789 } le_version_table[] = {
4790 /* earlier versions don't have get_version. */
4791 { "1.0c", LE_10C },
4792 { "1.0d", LE_10D },
4793 { "1.0e", LE_10E },
4794 { "1.1", LE_11 },
4795 { "1.1a", LE_11A },
4796 { "1.1b", LE_11B },
4797 { "1.2", LE_12 },
4798 { "1.2a", LE_12A },
4799 { "1.3", LE_13 },
4800 { "1.3a", LE_13A },
4801 { "1.3b", LE_13B },
4802 { "1.3c", LE_13C },
4803 { "1.3d", LE_13D },
4804 { NULL, LE_OTHER }
4807 /** Return the le_version_t for the current version of libevent. If the
4808 * version is very new, return LE_OTHER. If the version is so old that it
4809 * doesn't support event_get_version(), return LE_OLD. */
4810 static le_version_t
4811 decode_libevent_version(void)
4813 const char *v = event_get_version();
4814 int i;
4815 for (i=0; le_version_table[i].name; ++i) {
4816 if (!strcmp(le_version_table[i].name, v)) {
4817 return le_version_table[i].version;
4820 return LE_OTHER;
4824 * Compare the given libevent method and version to a list of versions
4825 * which are known not to work. Warn the user as appropriate.
4827 static void
4828 check_libevent_version(const char *m, int server)
4830 int buggy = 0, iffy = 0, slow = 0, thread_unsafe = 0;
4831 le_version_t version;
4832 const char *v = event_get_version();
4833 const char *badness = NULL;
4834 const char *sad_os = "";
4836 version = decode_libevent_version();
4838 /* XXX Would it be worthwhile disabling the methods that we know
4839 * are buggy, rather than just warning about them and then proceeding
4840 * to use them? If so, we should probably not wrap this whole thing
4841 * in HAVE_EVENT_GET_VERSION and HAVE_EVENT_GET_METHOD. -RD */
4842 /* XXXX The problem is that it's not trivial to get libevent to change it's
4843 * method once it's initialized, and it's not trivial to tell what method it
4844 * will use without initializing it. I guess we could preemptively disable
4845 * buggy libevent modes based on the version _before_ initializing it,
4846 * though, but then there's no good way (afaict) to warn "I would have used
4847 * kqueue, but instead I'm using select." -NM */
4848 if (!strcmp(m, "kqueue")) {
4849 if (version < LE_11B)
4850 buggy = 1;
4851 } else if (!strcmp(m, "epoll")) {
4852 if (version < LE_11)
4853 iffy = 1;
4854 } else if (!strcmp(m, "poll")) {
4855 if (version < LE_10E)
4856 buggy = 1;
4857 else if (version < LE_11)
4858 slow = 1;
4859 } else if (!strcmp(m, "select")) {
4860 if (version < LE_11)
4861 slow = 1;
4862 } else if (!strcmp(m, "win32")) {
4863 if (version < LE_11B)
4864 buggy = 1;
4867 /* Libevent versions before 1.3b do very badly on operating systems with
4868 * user-space threading implementations. */
4869 #if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__)
4870 if (server && version < LE_13B) {
4871 thread_unsafe = 1;
4872 sad_os = "BSD variants";
4874 #elif defined(__APPLE__) || defined(__darwin__)
4875 if (server && version < LE_13B) {
4876 thread_unsafe = 1;
4877 sad_os = "Mac OS X";
4879 #endif
4881 if (thread_unsafe) {
4882 log(LOG_WARN, LD_GENERAL,
4883 "Libevent version %s often crashes when running a Tor server with %s. "
4884 "Please use the latest version of libevent (1.3b or later)",v,sad_os);
4885 badness = "BROKEN";
4886 } else if (buggy) {
4887 log(LOG_WARN, LD_GENERAL,
4888 "There are serious bugs in using %s with libevent %s. "
4889 "Please use the latest version of libevent.", m, v);
4890 badness = "BROKEN";
4891 } else if (iffy) {
4892 log(LOG_WARN, LD_GENERAL,
4893 "There are minor bugs in using %s with libevent %s. "
4894 "You may want to use the latest version of libevent.", m, v);
4895 badness = "BUGGY";
4896 } else if (slow && server) {
4897 log(LOG_WARN, LD_GENERAL,
4898 "libevent %s can be very slow with %s. "
4899 "When running a server, please use the latest version of libevent.",
4900 v,m);
4901 badness = "SLOW";
4903 if (badness) {
4904 control_event_general_status(LOG_WARN,
4905 "BAD_LIBEVENT VERSION=%s METHOD=%s BADNESS=%s RECOVERED=NO",
4906 v, m, badness);
4910 #else
4911 static le_version_t
4912 decode_libevent_version(void)
4914 return LE_OLD;
4916 #endif
4918 /** Return the persistent state struct for this Tor. */
4919 or_state_t *
4920 get_or_state(void)
4922 tor_assert(global_state);
4923 return global_state;
4926 /** Return a newly allocated string holding a filename relative to the data
4927 * directory. If <b>sub1</b> is present, it is the first path component after
4928 * the data directory. If <b>sub2</b> is also present, it is the second path
4929 * component after the data directory. If <b>suffix</b> is present, it
4930 * is appended to the filename.
4932 * Examples:
4933 * get_datadir_fname2_suffix("a", NULL, NULL) -> $DATADIR/a
4934 * get_datadir_fname2_suffix("a", NULL, ".tmp") -> $DATADIR/a.tmp
4935 * get_datadir_fname2_suffix("a", "b", ".tmp") -> $DATADIR/a/b/.tmp
4936 * get_datadir_fname2_suffix("a", "b", NULL) -> $DATADIR/a/b
4938 * Note: Consider using the get_datadir_fname* macros in or.h.
4940 char *
4941 options_get_datadir_fname2_suffix(or_options_t *options,
4942 const char *sub1, const char *sub2,
4943 const char *suffix)
4945 char *fname = NULL;
4946 size_t len;
4947 tor_assert(options);
4948 tor_assert(options->DataDirectory);
4949 tor_assert(sub1 || !sub2); /* If sub2 is present, sub1 must be present. */
4950 len = strlen(options->DataDirectory);
4951 if (sub1) {
4952 len += strlen(sub1)+1;
4953 if (sub2)
4954 len += strlen(sub2)+1;
4956 if (suffix)
4957 len += strlen(suffix);
4958 len++;
4959 fname = tor_malloc(len);
4960 if (sub1) {
4961 if (sub2) {
4962 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s",
4963 options->DataDirectory, sub1, sub2);
4964 } else {
4965 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s",
4966 options->DataDirectory, sub1);
4968 } else {
4969 strlcpy(fname, options->DataDirectory, len);
4971 if (suffix)
4972 strlcat(fname, suffix, len);
4973 return fname;
4976 /** Return 0 if every setting in <b>state</b> is reasonable, and a
4977 * permissible transition from <b>old_state</b>. Else warn and return -1.
4978 * Should have no side effects, except for normalizing the contents of
4979 * <b>state</b>.
4981 /* XXX from_setconf is here because of bug 238 */
4982 static int
4983 or_state_validate(or_state_t *old_state, or_state_t *state,
4984 int from_setconf, char **msg)
4986 /* We don't use these; only options do. Still, we need to match that
4987 * signature. */
4988 (void) from_setconf;
4989 (void) old_state;
4991 if (entry_guards_parse_state(state, 0, msg)<0)
4992 return -1;
4994 return 0;
4997 /** Replace the current persistent state with <b>new_state</b> */
4998 static void
4999 or_state_set(or_state_t *new_state)
5001 char *err = NULL;
5002 tor_assert(new_state);
5003 if (global_state)
5004 config_free(&state_format, global_state);
5005 global_state = new_state;
5006 if (entry_guards_parse_state(global_state, 1, &err)<0) {
5007 log_warn(LD_GENERAL,"%s",err);
5008 tor_free(err);
5010 if (rep_hist_load_state(global_state, &err)<0) {
5011 log_warn(LD_GENERAL,"Unparseable bandwidth history state: %s",err);
5012 tor_free(err);
5016 /** Reload the persistent state from disk, generating a new state as needed.
5017 * Return 0 on success, less than 0 on failure.
5019 static int
5020 or_state_load(void)
5022 or_state_t *new_state = NULL;
5023 char *contents = NULL, *fname;
5024 char *errmsg = NULL;
5025 int r = -1, badstate = 0;
5027 fname = get_datadir_fname("state");
5028 switch (file_status(fname)) {
5029 case FN_FILE:
5030 if (!(contents = read_file_to_str(fname, 0, NULL))) {
5031 log_warn(LD_FS, "Unable to read state file \"%s\"", fname);
5032 goto done;
5034 break;
5035 case FN_NOENT:
5036 break;
5037 case FN_ERROR:
5038 case FN_DIR:
5039 default:
5040 log_warn(LD_GENERAL,"State file \"%s\" is not a file? Failing.", fname);
5041 goto done;
5043 new_state = tor_malloc_zero(sizeof(or_state_t));
5044 new_state->_magic = OR_STATE_MAGIC;
5045 config_init(&state_format, new_state);
5046 if (contents) {
5047 config_line_t *lines=NULL;
5048 int assign_retval;
5049 if (config_get_lines(contents, &lines)<0)
5050 goto done;
5051 assign_retval = config_assign(&state_format, new_state,
5052 lines, 0, 0, &errmsg);
5053 config_free_lines(lines);
5054 if (assign_retval<0)
5055 badstate = 1;
5056 if (errmsg) {
5057 log_warn(LD_GENERAL, "%s", errmsg);
5058 tor_free(errmsg);
5062 if (!badstate && or_state_validate(NULL, new_state, 1, &errmsg) < 0)
5063 badstate = 1;
5065 if (errmsg) {
5066 log_warn(LD_GENERAL, "%s", errmsg);
5067 tor_free(errmsg);
5070 if (badstate && !contents) {
5071 log_warn(LD_BUG, "Uh oh. We couldn't even validate our own default state."
5072 " This is a bug in Tor.");
5073 goto done;
5074 } else if (badstate && contents) {
5075 int i;
5076 file_status_t status;
5077 size_t len = strlen(fname)+16;
5078 char *fname2 = tor_malloc(len);
5079 for (i = 0; i < 100; ++i) {
5080 tor_snprintf(fname2, len, "%s.%d", fname, i);
5081 status = file_status(fname2);
5082 if (status == FN_NOENT)
5083 break;
5085 if (i == 100) {
5086 log_warn(LD_BUG, "Unable to parse state in \"%s\"; too many saved bad "
5087 "state files to move aside. Discarding the old state file.",
5088 fname);
5089 unlink(fname);
5090 } else {
5091 log_warn(LD_BUG, "Unable to parse state in \"%s\". Moving it aside "
5092 "to \"%s\". This could be a bug in Tor; please tell "
5093 "the developers.", fname, fname2);
5094 if (rename(fname, fname2) < 0) {
5095 log_warn(LD_BUG, "Weirdly, I couldn't even move the state aside. The "
5096 "OS gave an error of %s", strerror(errno));
5099 tor_free(fname2);
5100 tor_free(contents);
5101 config_free(&state_format, new_state);
5103 new_state = tor_malloc_zero(sizeof(or_state_t));
5104 new_state->_magic = OR_STATE_MAGIC;
5105 config_init(&state_format, new_state);
5106 } else if (contents) {
5107 log_info(LD_GENERAL, "Loaded state from \"%s\"", fname);
5108 } else {
5109 log_info(LD_GENERAL, "Initialized state");
5111 or_state_set(new_state);
5112 new_state = NULL;
5113 if (!contents) {
5114 global_state->next_write = 0;
5115 or_state_save(time(NULL));
5117 r = 0;
5119 done:
5120 tor_free(fname);
5121 tor_free(contents);
5122 if (new_state)
5123 config_free(&state_format, new_state);
5125 return r;
5128 /** Write the persistent state to disk. Return 0 for success, <0 on failure. */
5130 or_state_save(time_t now)
5132 char *state, *contents;
5133 char tbuf[ISO_TIME_LEN+1];
5134 size_t len;
5135 char *fname;
5137 tor_assert(global_state);
5139 if (global_state->next_write > now)
5140 return 0;
5142 /* Call everything else that might dirty the state even more, in order
5143 * to avoid redundant writes. */
5144 entry_guards_update_state(global_state);
5145 rep_hist_update_state(global_state);
5146 if (accounting_is_enabled(get_options()))
5147 accounting_run_housekeeping(now);
5149 global_state->LastWritten = time(NULL);
5150 tor_free(global_state->TorVersion);
5151 len = strlen(get_version())+8;
5152 global_state->TorVersion = tor_malloc(len);
5153 tor_snprintf(global_state->TorVersion, len, "Tor %s", get_version());
5155 state = config_dump(&state_format, global_state, 1, 0);
5156 len = strlen(state)+256;
5157 contents = tor_malloc(len);
5158 format_local_iso_time(tbuf, time(NULL));
5159 tor_snprintf(contents, len,
5160 "# Tor state file last generated on %s local time\n"
5161 "# Other times below are in GMT\n"
5162 "# You *do not* need to edit this file.\n\n%s",
5163 tbuf, state);
5164 tor_free(state);
5165 fname = get_datadir_fname("state");
5166 if (write_str_to_file(fname, contents, 0)<0) {
5167 log_warn(LD_FS, "Unable to write state to file \"%s\"", fname);
5168 tor_free(fname);
5169 tor_free(contents);
5170 return -1;
5172 log_info(LD_GENERAL, "Saved state to \"%s\"", fname);
5173 tor_free(fname);
5174 tor_free(contents);
5176 global_state->next_write = TIME_MAX;
5177 return 0;
5180 /** Given a file name check to see whether the file exists but has not been
5181 * modified for a very long time. If so, remove it. */
5182 void
5183 remove_file_if_very_old(const char *fname, time_t now)
5185 #define VERY_OLD_FILE_AGE (28*24*60*60)
5186 struct stat st;
5188 if (stat(fname, &st)==0 && st.st_mtime < now-VERY_OLD_FILE_AGE) {
5189 char buf[ISO_TIME_LEN+1];
5190 format_local_iso_time(buf, st.st_mtime);
5191 log_notice(LD_GENERAL, "Obsolete file %s hasn't been modified since %s. "
5192 "Removing it.", fname, buf);
5193 unlink(fname);
5197 /** Helper to implement GETINFO functions about configuration variables (not
5198 * their values). Given a "config/names" question, set *<b>answer</b> to a
5199 * new string describing the supported configuration variables and their
5200 * types. */
5202 getinfo_helper_config(control_connection_t *conn,
5203 const char *question, char **answer)
5205 (void) conn;
5206 if (!strcmp(question, "config/names")) {
5207 smartlist_t *sl = smartlist_create();
5208 int i;
5209 for (i = 0; _option_vars[i].name; ++i) {
5210 config_var_t *var = &_option_vars[i];
5211 const char *type, *desc;
5212 char *line;
5213 size_t len;
5214 desc = config_find_description(&options_format, var->name);
5215 switch (var->type) {
5216 case CONFIG_TYPE_STRING: type = "String"; break;
5217 case CONFIG_TYPE_FILENAME: type = "Filename"; break;
5218 case CONFIG_TYPE_UINT: type = "Integer"; break;
5219 case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
5220 case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
5221 case CONFIG_TYPE_DOUBLE: type = "Float"; break;
5222 case CONFIG_TYPE_BOOL: type = "Boolean"; break;
5223 case CONFIG_TYPE_ISOTIME: type = "Time"; break;
5224 case CONFIG_TYPE_ROUTERSET: type = "RouterList"; break;
5225 case CONFIG_TYPE_CSV: type = "CommaList"; break;
5226 case CONFIG_TYPE_LINELIST: type = "LineList"; break;
5227 case CONFIG_TYPE_LINELIST_S: type = "Dependant"; break;
5228 case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
5229 default:
5230 case CONFIG_TYPE_OBSOLETE:
5231 type = NULL; break;
5233 if (!type)
5234 continue;
5235 len = strlen(var->name)+strlen(type)+16;
5236 if (desc)
5237 len += strlen(desc);
5238 line = tor_malloc(len);
5239 if (desc)
5240 tor_snprintf(line, len, "%s %s %s\n",var->name,type,desc);
5241 else
5242 tor_snprintf(line, len, "%s %s\n",var->name,type);
5243 smartlist_add(sl, line);
5245 *answer = smartlist_join_strings(sl, "", 0, NULL);
5246 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
5247 smartlist_free(sl);
5249 return 0;
5252 #include "aes.h"
5253 #include "ht.h"
5254 #include "test.h"
5256 extern const char address_c_id[];
5257 extern const char aes_c_id[];
5258 extern const char compat_c_id[];
5259 extern const char container_c_id[];
5260 extern const char crypto_c_id[];
5261 extern const char log_c_id[];
5262 extern const char torgzip_c_id[];
5263 extern const char tortls_c_id[];
5264 extern const char util_c_id[];
5266 extern const char buffers_c_id[];
5267 extern const char circuitbuild_c_id[];
5268 extern const char circuitlist_c_id[];
5269 extern const char circuituse_c_id[];
5270 extern const char command_c_id[];
5271 // extern const char config_c_id[];
5272 extern const char connection_c_id[];
5273 extern const char connection_edge_c_id[];
5274 extern const char connection_or_c_id[];
5275 extern const char control_c_id[];
5276 extern const char cpuworker_c_id[];
5277 extern const char directory_c_id[];
5278 extern const char dirserv_c_id[];
5279 extern const char dns_c_id[];
5280 extern const char hibernate_c_id[];
5281 extern const char main_c_id[];
5282 #ifdef NT_SERVICE
5283 extern const char ntmain_c_id[];
5284 #endif
5285 extern const char onion_c_id[];
5286 extern const char policies_c_id[];
5287 extern const char relay_c_id[];
5288 extern const char rendclient_c_id[];
5289 extern const char rendcommon_c_id[];
5290 extern const char rendmid_c_id[];
5291 extern const char rendservice_c_id[];
5292 extern const char rephist_c_id[];
5293 extern const char router_c_id[];
5294 extern const char routerlist_c_id[];
5295 extern const char routerparse_c_id[];
5297 /** Dump the version of every file to the log. */
5298 static void
5299 print_svn_version(void)
5301 puts(ADDRESS_H_ID);
5302 puts(AES_H_ID);
5303 puts(COMPAT_H_ID);
5304 puts(CONTAINER_H_ID);
5305 puts(CRYPTO_H_ID);
5306 puts(HT_H_ID);
5307 puts(TEST_H_ID);
5308 puts(LOG_H_ID);
5309 puts(TORGZIP_H_ID);
5310 puts(TORINT_H_ID);
5311 puts(TORTLS_H_ID);
5312 puts(UTIL_H_ID);
5313 puts(address_c_id);
5314 puts(aes_c_id);
5315 puts(compat_c_id);
5316 puts(container_c_id);
5317 puts(crypto_c_id);
5318 puts(log_c_id);
5319 puts(torgzip_c_id);
5320 puts(tortls_c_id);
5321 puts(util_c_id);
5323 puts(OR_H_ID);
5324 puts(buffers_c_id);
5325 puts(circuitbuild_c_id);
5326 puts(circuitlist_c_id);
5327 puts(circuituse_c_id);
5328 puts(command_c_id);
5329 puts(config_c_id);
5330 puts(connection_c_id);
5331 puts(connection_edge_c_id);
5332 puts(connection_or_c_id);
5333 puts(control_c_id);
5334 puts(cpuworker_c_id);
5335 puts(directory_c_id);
5336 puts(dirserv_c_id);
5337 puts(dns_c_id);
5338 puts(hibernate_c_id);
5339 puts(main_c_id);
5340 #ifdef NT_SERVICE
5341 puts(ntmain_c_id);
5342 #endif
5343 puts(onion_c_id);
5344 puts(policies_c_id);
5345 puts(relay_c_id);
5346 puts(rendclient_c_id);
5347 puts(rendcommon_c_id);
5348 puts(rendmid_c_id);
5349 puts(rendservice_c_id);
5350 puts(rephist_c_id);
5351 puts(router_c_id);
5352 puts(routerlist_c_id);
5353 puts(routerparse_c_id);