Add a lockfile to the Tor data directory to avoid situations where two Tors start...
[tor.git] / src / or / config.c
blob7d9dc64b7d9d087bb8aff6104c406048b879a7a8
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(AlternateBridgeAuthority, LINELIST, NULL),
140 V(AlternateDirAuthority, LINELIST, NULL),
141 V(AlternateHSAuthority, LINELIST, NULL),
142 V(AssumeReachable, BOOL, "0"),
143 V(AuthDirBadDir, LINELIST, NULL),
144 V(AuthDirBadExit, LINELIST, NULL),
145 V(AuthDirInvalid, LINELIST, NULL),
146 V(AuthDirReject, LINELIST, NULL),
147 V(AuthDirRejectUnlisted, BOOL, "0"),
148 V(AuthDirListBadDirs, BOOL, "0"),
149 V(AuthDirListBadExits, BOOL, "0"),
150 V(AuthDirMaxServersPerAddr, UINT, "2"),
151 V(AuthDirMaxServersPerAuthAddr,UINT, "5"),
152 VAR("AuthoritativeDirectory", BOOL, AuthoritativeDir, "0"),
153 V(AutomapHostsOnResolve, BOOL, "0"),
154 V(AutomapHostsSuffixes, CSV, ".onion,.exit"),
155 V(AvoidDiskWrites, BOOL, "0"),
156 V(BandwidthBurst, MEMUNIT, "10 MB"),
157 V(BandwidthRate, MEMUNIT, "5 MB"),
158 V(BridgeAuthoritativeDir, BOOL, "0"),
159 VAR("Bridge", LINELIST, Bridges, NULL),
160 V(BridgePassword, STRING, NULL),
161 V(BridgeRecordUsageByCountry, BOOL, "1"),
162 V(BridgeRelay, BOOL, "0"),
163 V(CircuitBuildTimeout, INTERVAL, "1 minute"),
164 V(CircuitIdleTimeout, INTERVAL, "1 hour"),
165 V(ClientDNSRejectInternalAddresses, BOOL,"1"),
166 V(ClientOnly, BOOL, "0"),
167 V(ConnLimit, UINT, "1000"),
168 V(ConstrainedSockets, BOOL, "0"),
169 V(ConstrainedSockSize, MEMUNIT, "8192"),
170 V(ContactInfo, STRING, NULL),
171 V(ControlListenAddress, LINELIST, NULL),
172 V(ControlPort, UINT, "0"),
173 V(ControlSocket, LINELIST, NULL),
174 V(CookieAuthentication, BOOL, "0"),
175 V(CookieAuthFileGroupReadable, BOOL, "0"),
176 V(CookieAuthFile, STRING, NULL),
177 V(DataDirectory, FILENAME, NULL),
178 OBSOLETE("DebugLogFile"),
179 V(DirAllowPrivateAddresses, BOOL, NULL),
180 V(TestingAuthDirTimeToLearnReachability, INTERVAL, "30 minutes"),
181 V(DirListenAddress, LINELIST, NULL),
182 OBSOLETE("DirFetchPeriod"),
183 V(DirPolicy, LINELIST, NULL),
184 V(DirPort, UINT, "0"),
185 OBSOLETE("DirPostPeriod"),
186 #ifdef ENABLE_GEOIP_STATS
187 V(DirRecordUsageByCountry, BOOL, "0"),
188 V(DirRecordUsageGranularity, UINT, "4"),
189 V(DirRecordUsageRetainIPs, INTERVAL, "14 days"),
190 V(DirRecordUsageSaveInterval, INTERVAL, "6 hours"),
191 #endif
192 VAR("DirServer", LINELIST, DirServers, NULL),
193 V(DNSPort, UINT, "0"),
194 V(DNSListenAddress, LINELIST, NULL),
195 V(DownloadExtraInfo, BOOL, "0"),
196 V(EnforceDistinctSubnets, BOOL, "1"),
197 V(EntryNodes, STRING, NULL),
198 V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "10 minutes"),
199 V(ExcludeNodes, ROUTERSET, NULL),
200 V(ExcludeExitNodes, ROUTERSET, NULL),
201 V(ExitNodes, STRING, NULL),
202 V(ExitPolicy, LINELIST, NULL),
203 V(ExitPolicyRejectPrivate, BOOL, "1"),
204 V(FallbackNetworkstatusFile, FILENAME,
205 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "fallback-consensus"),
206 V(FascistFirewall, BOOL, "0"),
207 V(FirewallPorts, CSV, ""),
208 V(FastFirstHopPK, BOOL, "1"),
209 V(FetchDirInfoEarly, BOOL, "0"),
210 V(FetchServerDescriptors, BOOL, "1"),
211 V(FetchHidServDescriptors, BOOL, "1"),
212 V(FetchUselessDescriptors, BOOL, "0"),
213 #ifdef WIN32
214 V(GeoIPFile, FILENAME, "<default>"),
215 #else
216 V(GeoIPFile, FILENAME,
217 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip"),
218 #endif
219 V(Group, STRING, NULL),
220 V(HardwareAccel, BOOL, "0"),
221 V(HashedControlPassword, LINELIST, NULL),
222 V(HidServDirectoryV2, BOOL, "0"),
223 VAR("HiddenServiceDir", LINELIST_S, RendConfigLines, NULL),
224 OBSOLETE("HiddenServiceExcludeNodes"),
225 OBSOLETE("HiddenServiceNodes"),
226 VAR("HiddenServiceOptions",LINELIST_V, RendConfigLines, NULL),
227 VAR("HiddenServicePort", LINELIST_S, RendConfigLines, NULL),
228 VAR("HiddenServiceVersion",LINELIST_S, RendConfigLines, NULL),
229 VAR("HiddenServiceAuthorizeClient",LINELIST_S,RendConfigLines, NULL),
230 V(HidServAuth, LINELIST, NULL),
231 V(HSAuthoritativeDir, BOOL, "0"),
232 V(HSAuthorityRecordStats, BOOL, "0"),
233 V(HttpProxy, STRING, NULL),
234 V(HttpProxyAuthenticator, STRING, NULL),
235 V(HttpsProxy, STRING, NULL),
236 V(HttpsProxyAuthenticator, STRING, NULL),
237 OBSOLETE("IgnoreVersion"),
238 V(KeepalivePeriod, INTERVAL, "5 minutes"),
239 VAR("Log", LINELIST, Logs, NULL),
240 OBSOLETE("LinkPadding"),
241 OBSOLETE("LogLevel"),
242 OBSOLETE("LogFile"),
243 V(LongLivedPorts, CSV,
244 "21,22,706,1863,5050,5190,5222,5223,6667,6697,8300"),
245 VAR("MapAddress", LINELIST, AddressMap, NULL),
246 V(MaxAdvertisedBandwidth, MEMUNIT, "1 GB"),
247 V(MaxCircuitDirtiness, INTERVAL, "10 minutes"),
248 V(MaxOnionsPending, UINT, "100"),
249 OBSOLETE("MonthlyAccountingStart"),
250 V(MyFamily, STRING, NULL),
251 V(NewCircuitPeriod, INTERVAL, "30 seconds"),
252 VAR("NamingAuthoritativeDirectory",BOOL, NamingAuthoritativeDir, "0"),
253 V(NatdListenAddress, LINELIST, NULL),
254 V(NatdPort, UINT, "0"),
255 V(Nickname, STRING, NULL),
256 V(NoPublish, BOOL, "0"),
257 VAR("NodeFamily", LINELIST, NodeFamilies, NULL),
258 V(NumCpus, UINT, "1"),
259 V(NumEntryGuards, UINT, "3"),
260 V(ORListenAddress, LINELIST, NULL),
261 V(ORPort, UINT, "0"),
262 V(OutboundBindAddress, STRING, NULL),
263 OBSOLETE("PathlenCoinWeight"),
264 V(PidFile, STRING, NULL),
265 V(TestingTorNetwork, BOOL, "0"),
266 V(PreferTunneledDirConns, BOOL, "1"),
267 V(ProtocolWarnings, BOOL, "0"),
268 V(PublishServerDescriptor, CSV, "1"),
269 V(PublishHidServDescriptors, BOOL, "1"),
270 V(ReachableAddresses, LINELIST, NULL),
271 V(ReachableDirAddresses, LINELIST, NULL),
272 V(ReachableORAddresses, LINELIST, NULL),
273 V(RecommendedVersions, LINELIST, NULL),
274 V(RecommendedClientVersions, LINELIST, NULL),
275 V(RecommendedServerVersions, LINELIST, NULL),
276 V(RedirectExit, LINELIST, NULL),
277 V(RejectPlaintextPorts, CSV, ""),
278 V(RelayBandwidthBurst, MEMUNIT, "0"),
279 V(RelayBandwidthRate, MEMUNIT, "0"),
280 OBSOLETE("RendExcludeNodes"),
281 OBSOLETE("RendNodes"),
282 V(RendPostPeriod, INTERVAL, "1 hour"),
283 V(RephistTrackTime, INTERVAL, "24 hours"),
284 OBSOLETE("RouterFile"),
285 V(RunAsDaemon, BOOL, "0"),
286 V(RunTesting, BOOL, "0"),
287 V(SafeLogging, BOOL, "1"),
288 V(SafeSocks, BOOL, "0"),
289 V(ServerDNSAllowBrokenResolvConf, BOOL, "0"),
290 V(ServerDNSAllowNonRFC953Hostnames, BOOL,"0"),
291 V(ServerDNSDetectHijacking, BOOL, "1"),
292 V(ServerDNSResolvConfFile, STRING, NULL),
293 V(ServerDNSSearchDomains, BOOL, "0"),
294 V(ServerDNSTestAddresses, CSV,
295 "www.google.com,www.mit.edu,www.yahoo.com,www.slashdot.org"),
296 V(ShutdownWaitLength, INTERVAL, "30 seconds"),
297 V(SocksListenAddress, LINELIST, NULL),
298 V(SocksPolicy, LINELIST, NULL),
299 V(SocksPort, UINT, "9050"),
300 V(SocksTimeout, INTERVAL, "2 minutes"),
301 OBSOLETE("StatusFetchPeriod"),
302 V(StrictEntryNodes, BOOL, "0"),
303 V(StrictExitNodes, BOOL, "0"),
304 OBSOLETE("SysLog"),
305 V(TestSocks, BOOL, "0"),
306 OBSOLETE("TestVia"),
307 V(TrackHostExits, CSV, NULL),
308 V(TrackHostExitsExpire, INTERVAL, "30 minutes"),
309 OBSOLETE("TrafficShaping"),
310 V(TransListenAddress, LINELIST, NULL),
311 V(TransPort, UINT, "0"),
312 V(TunnelDirConns, BOOL, "1"),
313 V(UpdateBridgesFromAuthority, BOOL, "0"),
314 V(UseBridges, BOOL, "0"),
315 V(UseEntryGuards, BOOL, "1"),
316 V(User, STRING, NULL),
317 VAR("V1AuthoritativeDirectory",BOOL, V1AuthoritativeDir, "0"),
318 VAR("V2AuthoritativeDirectory",BOOL, V2AuthoritativeDir, "0"),
319 VAR("V3AuthoritativeDirectory",BOOL, V3AuthoritativeDir, "0"),
320 V(TestingV3AuthInitialVotingInterval, INTERVAL, "30 minutes"),
321 V(TestingV3AuthInitialVoteDelay, INTERVAL, "5 minutes"),
322 V(TestingV3AuthInitialDistDelay, INTERVAL, "5 minutes"),
323 V(V3AuthVotingInterval, INTERVAL, "1 hour"),
324 V(V3AuthVoteDelay, INTERVAL, "5 minutes"),
325 V(V3AuthDistDelay, INTERVAL, "5 minutes"),
326 V(V3AuthNIntervalsValid, UINT, "3"),
327 V(V3AuthUseLegacyKey, BOOL, "0"),
328 VAR("VersioningAuthoritativeDirectory",BOOL,VersioningAuthoritativeDir, "0"),
329 V(VirtualAddrNetwork, STRING, "127.192.0.0/10"),
330 V(WarnPlaintextPorts, CSV, "23,109,110,143"),
331 VAR("__AllDirActionsPrivate", BOOL, AllDirActionsPrivate, "0"),
332 VAR("__DisablePredictedCircuits",BOOL,DisablePredictedCircuits, "0"),
333 VAR("__LeaveStreamsUnattached",BOOL, LeaveStreamsUnattached, "0"),
334 VAR("__HashedControlSessionPassword", LINELIST, HashedControlSessionPassword,
335 NULL),
336 V(MinUptimeHidServDirectoryV2, INTERVAL, "24 hours"),
337 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
340 /* Keep defaults synchronous with man page and config value check. */
341 static config_var_t testing_tor_network_defaults[] = {
342 V(ServerDNSAllowBrokenResolvConf, BOOL, "1"),
343 V(DirAllowPrivateAddresses, BOOL, "1"),
344 V(EnforceDistinctSubnets, BOOL, "0"),
345 V(AssumeReachable, BOOL, "1"),
346 V(AuthDirMaxServersPerAddr, UINT, "0"),
347 V(AuthDirMaxServersPerAuthAddr,UINT, "0"),
348 V(ClientDNSRejectInternalAddresses, BOOL,"0"),
349 V(ExitPolicyRejectPrivate, BOOL, "0"),
350 V(V3AuthVotingInterval, INTERVAL, "5 minutes"),
351 V(V3AuthVoteDelay, INTERVAL, "20 seconds"),
352 V(V3AuthDistDelay, INTERVAL, "20 seconds"),
353 V(TestingV3AuthInitialVotingInterval, INTERVAL, "5 minutes"),
354 V(TestingV3AuthInitialVoteDelay, INTERVAL, "20 seconds"),
355 V(TestingV3AuthInitialDistDelay, INTERVAL, "20 seconds"),
356 V(TestingAuthDirTimeToLearnReachability, INTERVAL, "0 minutes"),
357 V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "0 minutes"),
358 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
360 #undef VAR
362 #define VAR(name,conftype,member,initvalue) \
363 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_state_t, member), \
364 initvalue }
365 static config_var_t _state_vars[] = {
366 V(AccountingBytesReadInInterval, MEMUNIT, NULL),
367 V(AccountingBytesWrittenInInterval, MEMUNIT, NULL),
368 V(AccountingExpectedUsage, MEMUNIT, NULL),
369 V(AccountingIntervalStart, ISOTIME, NULL),
370 V(AccountingSecondsActive, INTERVAL, NULL),
372 VAR("EntryGuard", LINELIST_S, EntryGuards, NULL),
373 VAR("EntryGuardDownSince", LINELIST_S, EntryGuards, NULL),
374 VAR("EntryGuardUnlistedSince", LINELIST_S, EntryGuards, NULL),
375 VAR("EntryGuardAddedBy", LINELIST_S, EntryGuards, NULL),
376 V(EntryGuards, LINELIST_V, NULL),
378 V(BWHistoryReadEnds, ISOTIME, NULL),
379 V(BWHistoryReadInterval, UINT, "900"),
380 V(BWHistoryReadValues, CSV, ""),
381 V(BWHistoryWriteEnds, ISOTIME, NULL),
382 V(BWHistoryWriteInterval, UINT, "900"),
383 V(BWHistoryWriteValues, CSV, ""),
385 V(TorVersion, STRING, NULL),
387 V(LastRotatedOnionKey, ISOTIME, NULL),
388 V(LastWritten, ISOTIME, NULL),
390 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
393 #undef VAR
394 #undef V
395 #undef OBSOLETE
397 /** Represents an English description of a configuration variable; used when
398 * generating configuration file comments. */
399 typedef struct config_var_description_t {
400 const char *name;
401 const char *description;
402 } config_var_description_t;
404 static config_var_description_t options_description[] = {
405 /* ==== general options */
406 { "AvoidDiskWrites", "If non-zero, try to write to disk less frequently than"
407 " we would otherwise." },
408 { "BandwidthRate", "A token bucket limits the average incoming bandwidth on "
409 "this node to the specified number of bytes per second." },
410 { "BandwidthBurst", "Limit the maximum token buffer size (also known as "
411 "burst) to the given number of bytes." },
412 { "ConnLimit", "Minimum number of simultaneous sockets we must have." },
413 { "ConstrainedSockets", "Shrink tx and rx buffers for sockets to avoid "
414 "system limits on vservers and related environments. See man page for "
415 "more information regarding this option." },
416 { "ConstrainedSockSize", "Limit socket buffers to this size when "
417 "ConstrainedSockets is enabled." },
418 /* ControlListenAddress */
419 { "ControlPort", "If set, Tor will accept connections from the same machine "
420 "(localhost only) on this port, and allow those connections to control "
421 "the Tor process using the Tor Control Protocol (described in "
422 "control-spec.txt).", },
423 { "CookieAuthentication", "If this option is set to 1, don't allow any "
424 "connections to the control port except when the connecting process "
425 "can read a file that Tor creates in its data directory." },
426 { "DataDirectory", "Store working data, state, keys, and caches here." },
427 { "DirServer", "Tor only trusts directories signed with one of these "
428 "servers' keys. Used to override the standard list of directory "
429 "authorities." },
430 /* { "FastFirstHopPK", "" }, */
431 /* FetchServerDescriptors, FetchHidServDescriptors,
432 * FetchUselessDescriptors */
433 { "Group", "On startup, setgid to this group." },
434 { "HardwareAccel", "If set, Tor tries to use hardware crypto accelerators "
435 "when it can." },
436 /* HashedControlPassword */
437 { "HTTPProxy", "Force Tor to make all HTTP directory requests through this "
438 "host:port (or host:80 if port is not set)." },
439 { "HTTPProxyAuthenticator", "A username:password pair to be used with "
440 "HTTPProxy." },
441 { "HTTPSProxy", "Force Tor to make all TLS (SSL) connectinos through this "
442 "host:port (or host:80 if port is not set)." },
443 { "HTTPSProxyAuthenticator", "A username:password pair to be used with "
444 "HTTPSProxy." },
445 { "KeepalivePeriod", "Send a padding cell every N seconds to keep firewalls "
446 "from closing our connections while Tor is not in use." },
447 { "Log", "Where to send logging messages. Format is "
448 "minSeverity[-maxSeverity] (stderr|stdout|syslog|file FILENAME)." },
449 { "OutboundBindAddress", "Make all outbound connections originate from the "
450 "provided IP address (only useful for multiple network interfaces)." },
451 { "PIDFile", "On startup, write our PID to this file. On clean shutdown, "
452 "remove the file." },
453 { "PreferTunneledDirConns", "If non-zero, avoid directory servers that "
454 "don't support tunneled connections." },
455 /* PreferTunneledDirConns */
456 /* ProtocolWarnings */
457 /* RephistTrackTime */
458 { "RunAsDaemon", "If set, Tor forks and daemonizes to the background when "
459 "started. Unix only." },
460 { "SafeLogging", "If set to 0, Tor logs potentially sensitive strings "
461 "rather than replacing them with the string [scrubbed]." },
462 { "TunnelDirConns", "If non-zero, when a directory server we contact "
463 "supports it, we will build a one-hop circuit and make an encrypted "
464 "connection via its ORPort." },
465 { "User", "On startup, setuid to this user." },
467 /* ==== client options */
468 { "AllowInvalidNodes", "Where on our circuits should Tor allow servers "
469 "that the directory authorities haven't called \"valid\"?" },
470 { "AllowNonRFC953Hostnames", "If set to 1, we don't automatically reject "
471 "hostnames for having invalid characters." },
472 /* CircuitBuildTimeout, CircuitIdleTimeout */
473 { "ClientOnly", "If set to 1, Tor will under no circumstances run as a "
474 "server, even if ORPort is enabled." },
475 { "EntryNodes", "A list of preferred entry nodes to use for the first hop "
476 "in circuits, when possible." },
477 /* { "EnforceDistinctSubnets" , "" }, */
478 { "ExitNodes", "A list of preferred nodes to use for the last hop in "
479 "circuits, when possible." },
480 { "ExcludeNodes", "A list of nodes never to use when building a circuit." },
481 { "FascistFirewall", "If set, Tor will only create outgoing connections to "
482 "servers running on the ports listed in FirewallPorts." },
483 { "FirewallPorts", "A list of ports that we can connect to. Only used "
484 "when FascistFirewall is set." },
485 { "LongLivedPorts", "A list of ports for services that tend to require "
486 "high-uptime connections." },
487 { "MapAddress", "Force Tor to treat all requests for one address as if "
488 "they were for another." },
489 { "NewCircuitPeriod", "Force Tor to consider whether to build a new circuit "
490 "every NUM seconds." },
491 { "MaxCircuitDirtiness", "Do not attach new streams to a circuit that has "
492 "been used more than this many seconds ago." },
493 /* NatdPort, NatdListenAddress */
494 { "NodeFamily", "A list of servers that constitute a 'family' and should "
495 "never be used in the same circuit." },
496 { "NumEntryGuards", "How many entry guards should we keep at a time?" },
497 /* PathlenCoinWeight */
498 { "ReachableAddresses", "Addresses we can connect to, as IP/bits:port-port. "
499 "By default, we assume all addresses are reachable." },
500 /* reachablediraddresses, reachableoraddresses. */
501 /* SafeSOCKS */
502 { "SOCKSPort", "The port where we listen for SOCKS connections from "
503 "applications." },
504 { "SOCKSListenAddress", "Bind to this address to listen to connections from "
505 "SOCKS-speaking applications." },
506 { "SOCKSPolicy", "Set an entry policy to limit which addresses can connect "
507 "to the SOCKSPort." },
508 /* SocksTimeout */
509 { "StrictExitNodes", "If set, Tor will fail to operate when none of the "
510 "configured ExitNodes can be used." },
511 { "StrictEntryNodes", "If set, Tor will fail to operate when none of the "
512 "configured EntryNodes can be used." },
513 /* TestSocks */
514 { "TrackHostsExit", "Hosts and domains which should, if possible, be "
515 "accessed from the same exit node each time we connect to them." },
516 { "TrackHostsExitExpire", "Time after which we forget which exit we were "
517 "using to connect to hosts in TrackHostsExit." },
518 /* "TransPort", "TransListenAddress */
519 { "UseEntryGuards", "Set to 0 if we want to pick from the whole set of "
520 "servers for the first position in each circuit, rather than picking a "
521 "set of 'Guards' to prevent profiling attacks." },
523 /* === server options */
524 { "Address", "The advertised (external) address we should use." },
525 /* Accounting* options. */
526 /* AssumeReachable */
527 { "ContactInfo", "Administrative contact information to advertise for this "
528 "server." },
529 { "ExitPolicy", "Address/port ranges for which to accept or reject outgoing "
530 "connections on behalf of Tor users." },
531 /* { "ExitPolicyRejectPrivate, "" }, */
532 { "MaxAdvertisedBandwidth", "If set, we will not advertise more than this "
533 "amount of bandwidth for our bandwidth rate, regardless of how much "
534 "bandwidth we actually detect." },
535 { "MaxOnionsPending", "Reject new attempts to extend circuits when we "
536 "already have this many pending." },
537 { "MyFamily", "Declare a list of other servers as belonging to the same "
538 "family as this one, so that clients will not use two from the same "
539 "family in the same circuit." },
540 { "Nickname", "Set the server nickname." },
541 { "NoPublish", "{DEPRECATED}" },
542 { "NumCPUs", "How many processes to use at once for public-key crypto." },
543 { "ORPort", "Advertise this port to listen for connections from Tor clients "
544 "and servers." },
545 { "ORListenAddress", "Bind to this address to listen for connections from "
546 "clients and servers, instead of the default 0.0.0.0:ORPort." },
547 { "PublishServerDescriptor", "Set to 0 to keep the server from "
548 "uploading info to the directory authorities." },
549 /*{ "RedirectExit", "When an outgoing connection tries to connect to a "
550 *"given address, redirect it to another address instead." },
552 /* ServerDNS: DetectHijacking, ResolvConfFile, SearchDomains */
553 { "ShutdownWaitLength", "Wait this long for clients to finish when "
554 "shutting down because of a SIGINT." },
556 /* === directory cache options */
557 { "DirPort", "Serve directory information from this port, and act as a "
558 "directory cache." },
559 { "DirListenAddress", "Bind to this address to listen for connections from "
560 "clients and servers, instead of the default 0.0.0.0:DirPort." },
561 { "DirPolicy", "Set a policy to limit who can connect to the directory "
562 "port." },
564 /* Authority options: AuthDirBadExit, AuthDirInvalid, AuthDirReject,
565 * AuthDirRejectUnlisted, AuthDirListBadExits, AuthoritativeDirectory,
566 * DirAllowPrivateAddresses, HSAuthoritativeDir,
567 * NamingAuthoritativeDirectory, RecommendedVersions,
568 * RecommendedClientVersions, RecommendedServerVersions, RendPostPeriod,
569 * RunTesting, V1AuthoritativeDirectory, VersioningAuthoritativeDirectory, */
571 /* Hidden service options: HiddenService: dir,excludenodes, nodes,
572 * options, port. PublishHidServDescriptor */
574 /* Nonpersistent options: __LeaveStreamsUnattached, __AllDirActionsPrivate */
575 { NULL, NULL },
578 static config_var_description_t state_description[] = {
579 { "AccountingBytesReadInInterval",
580 "How many bytes have we read in this accounting period?" },
581 { "AccountingBytesWrittenInInterval",
582 "How many bytes have we written in this accounting period?" },
583 { "AccountingExpectedUsage",
584 "How many bytes did we expect to use per minute? (0 for no estimate.)" },
585 { "AccountingIntervalStart", "When did this accounting period begin?" },
586 { "AccountingSecondsActive", "How long have we been awake in this period?" },
588 { "BWHistoryReadEnds", "When does the last-recorded read-interval end?" },
589 { "BWHistoryReadInterval", "How long is each read-interval (in seconds)?" },
590 { "BWHistoryReadValues", "Number of bytes read in each interval." },
591 { "BWHistoryWriteEnds", "When does the last-recorded write-interval end?" },
592 { "BWHistoryWriteInterval", "How long is each write-interval (in seconds)?"},
593 { "BWHistoryWriteValues", "Number of bytes written in each interval." },
595 { "EntryGuard", "One of the nodes we have chosen as a fixed entry" },
596 { "EntryGuardDownSince",
597 "The last entry guard has been unreachable since this time." },
598 { "EntryGuardUnlistedSince",
599 "The last entry guard has been unusable since this time." },
601 { "LastRotatedOnionKey",
602 "The last time at which we changed the medium-term private key used for "
603 "building circuits." },
604 { "LastWritten", "When was this state file last regenerated?" },
606 { "TorVersion", "Which version of Tor generated this state file?" },
607 { NULL, NULL },
610 /** Type of a callback to validate whether a given configuration is
611 * well-formed and consistent. See options_trial_assign() for documentation
612 * of arguments. */
613 typedef int (*validate_fn_t)(void*,void*,int,char**);
615 /** Information on the keys, value types, key-to-struct-member mappings,
616 * variable descriptions, validation functions, and abbreviations for a
617 * configuration or storage format. */
618 typedef struct {
619 size_t size; /**< Size of the struct that everything gets parsed into. */
620 uint32_t magic; /**< Required 'magic value' to make sure we have a struct
621 * of the right type. */
622 off_t magic_offset; /**< Offset of the magic value within the struct. */
623 config_abbrev_t *abbrevs; /**< List of abbreviations that we expand when
624 * parsing this format. */
625 config_var_t *vars; /**< List of variables we recognize, their default
626 * values, and where we stick them in the structure. */
627 validate_fn_t validate_fn; /**< Function to validate config. */
628 /** Documentation for configuration variables. */
629 config_var_description_t *descriptions;
630 /** If present, extra is a LINELIST variable for unrecognized
631 * lines. Otherwise, unrecognized lines are an error. */
632 config_var_t *extra;
633 } config_format_t;
635 /** Macro: assert that <b>cfg</b> has the right magic field for format
636 * <b>fmt</b>. */
637 #define CHECK(fmt, cfg) STMT_BEGIN \
638 tor_assert(fmt && cfg); \
639 tor_assert((fmt)->magic == \
640 *(uint32_t*)STRUCT_VAR_P(cfg,fmt->magic_offset)); \
641 STMT_END
643 #ifdef MS_WINDOWS
644 static char *get_windows_conf_root(void);
645 #endif
646 static void config_line_append(config_line_t **lst,
647 const char *key, const char *val);
648 static void option_clear(config_format_t *fmt, or_options_t *options,
649 config_var_t *var);
650 static void option_reset(config_format_t *fmt, or_options_t *options,
651 config_var_t *var, int use_defaults);
652 static void config_free(config_format_t *fmt, void *options);
653 static int config_lines_eq(config_line_t *a, config_line_t *b);
654 static int option_is_same(config_format_t *fmt,
655 or_options_t *o1, or_options_t *o2,
656 const char *name);
657 static or_options_t *options_dup(config_format_t *fmt, or_options_t *old);
658 static int options_validate(or_options_t *old_options, or_options_t *options,
659 int from_setconf, char **msg);
660 static int options_act_reversible(or_options_t *old_options, char **msg);
661 static int options_act(or_options_t *old_options);
662 static int options_transition_allowed(or_options_t *old, or_options_t *new,
663 char **msg);
664 static int options_transition_affects_workers(or_options_t *old_options,
665 or_options_t *new_options);
666 static int options_transition_affects_descriptor(or_options_t *old_options,
667 or_options_t *new_options);
668 static int check_nickname_list(const char *lst, const char *name, char **msg);
669 static void config_register_addressmaps(or_options_t *options);
671 static int parse_bridge_line(const char *line, int validate_only);
672 static int parse_dir_server_line(const char *line,
673 authority_type_t required_type,
674 int validate_only);
675 static int parse_redirect_line(smartlist_t *result,
676 config_line_t *line, char **msg);
677 static int validate_data_directory(or_options_t *options);
678 static int write_configuration_file(const char *fname, or_options_t *options);
679 static config_line_t *get_assigned_option(config_format_t *fmt,
680 or_options_t *options, const char *key,
681 int escape_val);
682 static void config_init(config_format_t *fmt, void *options);
683 static int or_state_validate(or_state_t *old_options, or_state_t *options,
684 int from_setconf, char **msg);
685 static int or_state_load(void);
686 static int options_init_logs(or_options_t *options, int validate_only);
688 static uint64_t config_parse_memunit(const char *s, int *ok);
689 static int config_parse_interval(const char *s, int *ok);
690 static void print_svn_version(void);
691 static void init_libevent(void);
692 static int opt_streq(const char *s1, const char *s2);
693 /** Versions of libevent. */
694 typedef enum {
695 /* Note: we compare these, so it's important that "old" precede everything,
696 * and that "other" come last. */
697 LE_OLD=0, LE_10C, LE_10D, LE_10E, LE_11, LE_11A, LE_11B, LE_12, LE_12A,
698 LE_13, LE_13A, LE_13B, LE_13C, LE_13D,
699 LE_OTHER
700 } le_version_t;
701 static le_version_t decode_libevent_version(void);
702 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
703 static void check_libevent_version(const char *m, int server);
704 #endif
706 /** Magic value for or_options_t. */
707 #define OR_OPTIONS_MAGIC 9090909
709 /** Configuration format for or_options_t. */
710 static config_format_t options_format = {
711 sizeof(or_options_t),
712 OR_OPTIONS_MAGIC,
713 STRUCT_OFFSET(or_options_t, _magic),
714 _option_abbrevs,
715 _option_vars,
716 (validate_fn_t)options_validate,
717 options_description,
718 NULL
721 /** Magic value for or_state_t. */
722 #define OR_STATE_MAGIC 0x57A73f57
724 /** "Extra" variable in the state that receives lines we can't parse. This
725 * lets us preserve options from versions of Tor newer than us. */
726 static config_var_t state_extra_var = {
727 "__extra", CONFIG_TYPE_LINELIST, STRUCT_OFFSET(or_state_t, ExtraLines), NULL
730 /** Configuration format for or_state_t. */
731 static config_format_t state_format = {
732 sizeof(or_state_t),
733 OR_STATE_MAGIC,
734 STRUCT_OFFSET(or_state_t, _magic),
735 _state_abbrevs,
736 _state_vars,
737 (validate_fn_t)or_state_validate,
738 state_description,
739 &state_extra_var,
743 * Functions to read and write the global options pointer.
746 /** Command-line and config-file options. */
747 static or_options_t *global_options = NULL;
748 /** Name of most recently read torrc file. */
749 static char *torrc_fname = NULL;
750 /** Persistent serialized state. */
751 static or_state_t *global_state = NULL;
752 /** Configuration Options set by command line. */
753 static config_line_t *global_cmdline_options = NULL;
755 /** Allocate an empty configuration object of a given format type. */
756 static void *
757 config_alloc(config_format_t *fmt)
759 void *opts = tor_malloc_zero(fmt->size);
760 *(uint32_t*)STRUCT_VAR_P(opts, fmt->magic_offset) = fmt->magic;
761 CHECK(fmt, opts);
762 return opts;
765 /** Return the currently configured options. */
766 or_options_t *
767 get_options(void)
769 tor_assert(global_options);
770 return global_options;
773 /** Change the current global options to contain <b>new_val</b> instead of
774 * their current value; take action based on the new value; free the old value
775 * as necessary. Returns 0 on success, -1 on failure.
778 set_options(or_options_t *new_val, char **msg)
780 or_options_t *old_options = global_options;
781 global_options = new_val;
782 /* Note that we pass the *old* options below, for comparison. It
783 * pulls the new options directly out of global_options. */
784 if (options_act_reversible(old_options, msg)<0) {
785 tor_assert(*msg);
786 global_options = old_options;
787 return -1;
789 if (options_act(old_options) < 0) { /* acting on the options failed. die. */
790 log_err(LD_BUG,
791 "Acting on config options left us in a broken state. Dying.");
792 exit(1);
794 if (old_options)
795 config_free(&options_format, old_options);
797 return 0;
800 extern const char tor_svn_revision[]; /* from tor_main.c */
802 static char *_version = NULL;
804 /** Return the current Tor version, possibly */
805 const char *
806 get_version(void)
808 if (_version == NULL) {
809 if (strlen(tor_svn_revision)) {
810 size_t len = strlen(VERSION)+strlen(tor_svn_revision)+8;
811 _version = tor_malloc(len);
812 tor_snprintf(_version, len, "%s (r%s)", VERSION, tor_svn_revision);
813 } else {
814 _version = tor_strdup(VERSION);
817 return _version;
820 /** Release all memory and resources held by global configuration structures.
822 void
823 config_free_all(void)
825 if (global_options) {
826 config_free(&options_format, global_options);
827 global_options = NULL;
829 if (global_state) {
830 config_free(&state_format, global_state);
831 global_state = NULL;
833 if (global_cmdline_options) {
834 config_free_lines(global_cmdline_options);
835 global_cmdline_options = NULL;
837 tor_free(torrc_fname);
838 tor_free(_version);
841 /** If options->SafeLogging is on, return a not very useful string,
842 * else return address.
844 const char *
845 safe_str(const char *address)
847 tor_assert(address);
848 if (get_options()->SafeLogging)
849 return "[scrubbed]";
850 else
851 return address;
854 /** Equivalent to escaped(safe_str(address)). See reentrancy note on
855 * escaped(): don't use this outside the main thread, or twice in the same
856 * log statement. */
857 const char *
858 escaped_safe_str(const char *address)
860 if (get_options()->SafeLogging)
861 return "[scrubbed]";
862 else
863 return escaped(address);
866 /** Add the default directory authorities directly into the trusted dir list,
867 * but only add them insofar as they share bits with <b>type</b>. */
868 static void
869 add_default_trusted_dir_authorities(authority_type_t type)
871 int i;
872 const char *dirservers[] = {
873 "moria1 v1 orport=9001 v3ident=E2A2AF570166665D738736D0DD58169CC61D8A8B "
874 "128.31.0.34:9031 FFCB 46DB 1339 DA84 674C 70D7 CB58 6434 C437 0441",
875 "moria2 v1 orport=9002 128.31.0.34:9032 "
876 "719B E45D E224 B607 C537 07D0 E214 3E2D 423E 74CF",
877 "tor26 v1 orport=443 v3ident=14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4 "
878 "86.59.21.38:80 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D",
879 "lefkada orport=443 "
880 "140.247.60.64:80 38D4 F5FC F7B1 0232 28B8 95EA 56ED E7D5 CCDC AF32",
881 "dizum orport=443 v3ident=E8A9C45EDE6D711294FADF8E7951F4DE6CA56B58 "
882 "194.109.206.212:80 7EA6 EAD6 FD83 083C 538F 4403 8BBF A077 587D D755",
883 "Tonga orport=443 bridge no-v2 82.94.251.206:80 "
884 "4A0C CD2D DC79 9508 3D73 F5D6 6710 0C8A 5831 F16D",
885 "ides orport=9090 no-v2 v3ident=27B6B5996C426270A5C95488AA5BCEB6BCC86956 "
886 "216.224.124.114:9030 F397 038A DC51 3361 35E7 B80B D99C A384 4360 292B",
887 "gabelmoo orport=443 no-v2 "
888 "v3ident=81349FC1F2DBA2C2C11B45CB9706637D480AB913 "
889 "88.198.7.215:80 6833 3D07 61BC F397 A587 A0C0 B963 E4A9 E99E C4D3",
890 "dannenberg orport=443 no-v2 "
891 "v3ident=585769C78764D58426B8B52B6651A5A71137189A "
892 "213.73.91.31:80 7BE6 83E6 5D48 1413 21C5 ED92 F075 C553 64AC 7123",
893 NULL
895 for (i=0; dirservers[i]; i++) {
896 if (parse_dir_server_line(dirservers[i], type, 0)<0) {
897 log_err(LD_BUG, "Couldn't parse internal dirserver line %s",
898 dirservers[i]);
903 /** Look at all the config options for using alternate directory
904 * authorities, and make sure none of them are broken. Also, warn the
905 * user if we changed any dangerous ones.
907 static int
908 validate_dir_authorities(or_options_t *options, or_options_t *old_options)
910 config_line_t *cl;
912 if (options->DirServers &&
913 (options->AlternateDirAuthority || options->AlternateBridgeAuthority ||
914 options->AlternateHSAuthority)) {
915 log_warn(LD_CONFIG,
916 "You cannot set both DirServers and Alternate*Authority.");
917 return -1;
920 /* do we want to complain to the user about being partitionable? */
921 if ((options->DirServers &&
922 (!old_options ||
923 !config_lines_eq(options->DirServers, old_options->DirServers))) ||
924 (options->AlternateDirAuthority &&
925 (!old_options ||
926 !config_lines_eq(options->AlternateDirAuthority,
927 old_options->AlternateDirAuthority)))) {
928 log_warn(LD_CONFIG,
929 "You have used DirServer or AlternateDirAuthority to "
930 "specify alternate directory authorities in "
931 "your configuration. This is potentially dangerous: it can "
932 "make you look different from all other Tor users, and hurt "
933 "your anonymity. Even if you've specified the same "
934 "authorities as Tor uses by default, the defaults could "
935 "change in the future. Be sure you know what you're doing.");
938 /* Now go through the four ways you can configure an alternate
939 * set of directory authorities, and make sure none are broken. */
940 for (cl = options->DirServers; cl; cl = cl->next)
941 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
942 return -1;
943 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
944 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
945 return -1;
946 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
947 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
948 return -1;
949 for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
950 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
951 return -1;
952 return 0;
955 /** Look at all the config options and assign new dir authorities
956 * as appropriate.
958 static int
959 consider_adding_dir_authorities(or_options_t *options,
960 or_options_t *old_options)
962 config_line_t *cl;
963 int need_to_update =
964 !smartlist_len(router_get_trusted_dir_servers()) || !old_options ||
965 !config_lines_eq(options->DirServers, old_options->DirServers) ||
966 !config_lines_eq(options->AlternateBridgeAuthority,
967 old_options->AlternateBridgeAuthority) ||
968 !config_lines_eq(options->AlternateDirAuthority,
969 old_options->AlternateDirAuthority) ||
970 !config_lines_eq(options->AlternateHSAuthority,
971 old_options->AlternateHSAuthority);
973 if (!need_to_update)
974 return 0; /* all done */
976 /* Start from a clean slate. */
977 clear_trusted_dir_servers();
979 if (!options->DirServers) {
980 /* then we may want some of the defaults */
981 authority_type_t type = NO_AUTHORITY;
982 if (!options->AlternateBridgeAuthority)
983 type |= BRIDGE_AUTHORITY;
984 if (!options->AlternateDirAuthority)
985 type |= V1_AUTHORITY | V2_AUTHORITY | V3_AUTHORITY;
986 if (!options->AlternateHSAuthority)
987 type |= HIDSERV_AUTHORITY;
988 add_default_trusted_dir_authorities(type);
991 for (cl = options->DirServers; cl; cl = cl->next)
992 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
993 return -1;
994 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
995 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
996 return -1;
997 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
998 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
999 return -1;
1000 for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
1001 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1002 return -1;
1003 return 0;
1006 /** Fetch the active option list, and take actions based on it. All of the
1007 * things we do should survive being done repeatedly. If present,
1008 * <b>old_options</b> contains the previous value of the options.
1010 * Return 0 if all goes well, return -1 if things went badly.
1012 static int
1013 options_act_reversible(or_options_t *old_options, char **msg)
1015 smartlist_t *new_listeners = smartlist_create();
1016 smartlist_t *replaced_listeners = smartlist_create();
1017 static int libevent_initialized = 0;
1018 or_options_t *options = get_options();
1019 int running_tor = options->command == CMD_RUN_TOR;
1020 int set_conn_limit = 0;
1021 int r = -1;
1022 int logs_marked = 0;
1024 /* Daemonize _first_, since we only want to open most of this stuff in
1025 * the subprocess. Libevent bases can't be reliably inherited across
1026 * processes. */
1027 if (running_tor && options->RunAsDaemon) {
1028 /* No need to roll back, since you can't change the value. */
1029 start_daemon();
1032 #ifndef HAVE_SYS_UN_H
1033 if (options->ControlSocket) {
1034 *msg = tor_strdup("Unix domain sockets (ControlSocket) not supported"
1035 " on this OS/with this build.");
1036 goto rollback;
1038 #endif
1040 if (running_tor) {
1041 /* We need to set the connection limit before we can open the listeners. */
1042 if (set_max_file_descriptors((unsigned)options->ConnLimit,
1043 &options->_ConnLimit) < 0) {
1044 *msg = tor_strdup("Problem with ConnLimit value. See logs for details.");
1045 goto rollback;
1047 set_conn_limit = 1;
1049 /* Set up libevent. (We need to do this before we can register the
1050 * listeners as listeners.) */
1051 if (running_tor && !libevent_initialized) {
1052 init_libevent();
1053 libevent_initialized = 1;
1056 /* Launch the listeners. (We do this before we setuid, so we can bind to
1057 * ports under 1024.) */
1058 if (retry_all_listeners(replaced_listeners, new_listeners) < 0) {
1059 *msg = tor_strdup("Failed to bind one of the listener ports.");
1060 goto rollback;
1064 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
1065 /* Open /dev/pf before dropping privileges. */
1066 if (options->TransPort) {
1067 if (get_pf_socket() < 0) {
1068 *msg = tor_strdup("Unable to open /dev/pf for transparent proxy.");
1069 goto rollback;
1072 #endif
1074 /* Setuid/setgid as appropriate */
1075 if (options->User || options->Group) {
1076 /* XXXX021 We should only do this the first time through, not on
1077 * every setconf. */
1078 if (switch_id(options->User, options->Group) != 0) {
1079 /* No need to roll back, since you can't change the value. */
1080 *msg = tor_strdup("Problem with User or Group value. "
1081 "See logs for details.");
1082 goto done;
1086 /* Ensure data directory is private; create if possible. */
1087 if (check_private_dir(options->DataDirectory,
1088 running_tor ? CPD_CREATE : CPD_CHECK)<0) {
1089 char buf[1024];
1090 int tmp = tor_snprintf(buf, sizeof(buf),
1091 "Couldn't access/create private data directory \"%s\"",
1092 options->DataDirectory);
1093 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1094 goto done;
1095 /* No need to roll back, since you can't change the value. */
1098 /* Bail out at this point if we're not going to be a client or server:
1099 * we don't run Tor itself. */
1100 if (!running_tor)
1101 goto commit;
1103 mark_logs_temp(); /* Close current logs once new logs are open. */
1104 logs_marked = 1;
1105 if (options_init_logs(options, 0)<0) { /* Configure the log(s) */
1106 *msg = tor_strdup("Failed to init Log options. See logs for details.");
1107 goto rollback;
1110 commit:
1111 r = 0;
1112 if (logs_marked) {
1113 log_severity_list_t *severity =
1114 tor_malloc_zero(sizeof(log_severity_list_t));
1115 close_temp_logs();
1116 add_callback_log(severity, control_event_logmsg);
1117 control_adjust_event_log_severity();
1118 tor_free(severity);
1120 SMARTLIST_FOREACH(replaced_listeners, connection_t *, conn,
1122 log_notice(LD_NET, "Closing old %s on %s:%d",
1123 conn_type_to_string(conn->type), conn->address, conn->port);
1124 connection_close_immediate(conn);
1125 connection_mark_for_close(conn);
1127 goto done;
1129 rollback:
1130 r = -1;
1131 tor_assert(*msg);
1133 if (logs_marked) {
1134 rollback_log_changes();
1135 control_adjust_event_log_severity();
1138 if (set_conn_limit && old_options)
1139 set_max_file_descriptors((unsigned)old_options->ConnLimit,
1140 &options->_ConnLimit);
1142 SMARTLIST_FOREACH(new_listeners, connection_t *, conn,
1144 log_notice(LD_NET, "Closing partially-constructed listener %s on %s:%d",
1145 conn_type_to_string(conn->type), conn->address, conn->port);
1146 connection_close_immediate(conn);
1147 connection_mark_for_close(conn);
1150 done:
1151 smartlist_free(new_listeners);
1152 smartlist_free(replaced_listeners);
1153 return r;
1156 /** Fetch the active option list, and take actions based on it. All of the
1157 * things we do should survive being done repeatedly. If present,
1158 * <b>old_options</b> contains the previous value of the options.
1160 * Return 0 if all goes well, return -1 if it's time to die.
1162 * Note: We haven't moved all the "act on new configuration" logic
1163 * here yet. Some is still in do_hup() and other places.
1165 static int
1166 options_act(or_options_t *old_options)
1168 config_line_t *cl;
1169 char *fn;
1170 size_t len;
1171 or_options_t *options = get_options();
1172 int running_tor = options->command == CMD_RUN_TOR;
1173 char *msg;
1175 if (running_tor && !have_lockfile()) {
1176 if (try_locking(options, 1) < 0)
1177 return -1;
1180 if (consider_adding_dir_authorities(options, old_options) < 0)
1181 return -1;
1183 if (options->Bridges) {
1184 clear_bridge_list();
1185 for (cl = options->Bridges; cl; cl = cl->next) {
1186 if (parse_bridge_line(cl->value, 0)<0) {
1187 log_warn(LD_BUG,
1188 "Previously validated Bridge line could not be added!");
1189 return -1;
1194 if (running_tor && rend_config_services(options, 0)<0) {
1195 log_warn(LD_BUG,
1196 "Previously validated hidden services line could not be added!");
1197 return -1;
1200 if (running_tor && rend_parse_service_authorization(options, 0) < 0) {
1201 log_warn(LD_BUG, "Previously validated client authorization for "
1202 "hidden services could not be added!");
1203 return -1;
1206 if (running_tor && directory_caches_v2_dir_info(options)) {
1207 len = strlen(options->DataDirectory)+32;
1208 fn = tor_malloc(len);
1209 tor_snprintf(fn, len, "%s"PATH_SEPARATOR"cached-status",
1210 options->DataDirectory);
1211 if (check_private_dir(fn, CPD_CREATE) != 0) {
1212 log_warn(LD_CONFIG,
1213 "Couldn't access/create private data directory \"%s\"", fn);
1214 tor_free(fn);
1215 return -1;
1217 tor_free(fn);
1220 /* Load state */
1221 if (! global_state && running_tor) {
1222 if (or_state_load())
1223 return -1;
1224 rep_hist_load_mtbf_data(time(NULL));
1227 /* Bail out at this point if we're not going to be a client or server:
1228 * we want to not fork, and to log stuff to stderr. */
1229 if (!running_tor)
1230 return 0;
1233 smartlist_t *sl = smartlist_create();
1234 char *errmsg = NULL;
1235 for (cl = options->RedirectExit; cl; cl = cl->next) {
1236 if (parse_redirect_line(sl, cl, &errmsg)<0) {
1237 log_warn(LD_CONFIG, "%s", errmsg);
1238 tor_free(errmsg);
1239 SMARTLIST_FOREACH(sl, exit_redirect_t *, er, tor_free(er));
1240 smartlist_free(sl);
1241 return -1;
1244 set_exit_redirects(sl);
1247 /* Finish backgrounding the process */
1248 if (running_tor && options->RunAsDaemon) {
1249 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
1250 finish_daemon(options->DataDirectory);
1253 /* Write our pid to the pid file. If we do not have write permissions we
1254 * will log a warning */
1255 if (running_tor && options->PidFile)
1256 write_pidfile(options->PidFile);
1258 /* Register addressmap directives */
1259 config_register_addressmaps(options);
1260 parse_virtual_addr_network(options->VirtualAddrNetwork, 0, &msg);
1262 /* Update address policies. */
1263 if (policies_parse_from_options(options) < 0) {
1264 /* This should be impossible, but let's be sure. */
1265 log_warn(LD_BUG,"Error parsing already-validated policy options.");
1266 return -1;
1269 if (init_cookie_authentication(options->CookieAuthentication) < 0) {
1270 log_warn(LD_CONFIG,"Error creating cookie authentication file.");
1271 return -1;
1274 /* reload keys as needed for rendezvous services. */
1275 if (rend_service_load_keys()<0) {
1276 log_warn(LD_GENERAL,"Error loading rendezvous service keys");
1277 return -1;
1280 /* Set up accounting */
1281 if (accounting_parse_options(options, 0)<0) {
1282 log_warn(LD_CONFIG,"Error in accounting options");
1283 return -1;
1285 if (accounting_is_enabled(options))
1286 configure_accounting(time(NULL));
1288 /* Check for transitions that need action. */
1289 if (old_options) {
1290 if (options->UseEntryGuards && !old_options->UseEntryGuards) {
1291 log_info(LD_CIRC,
1292 "Switching to entry guards; abandoning previous circuits");
1293 circuit_mark_all_unused_circs();
1294 circuit_expire_all_dirty_circs();
1297 if (options_transition_affects_workers(old_options, options)) {
1298 log_info(LD_GENERAL,
1299 "Worker-related options changed. Rotating workers.");
1300 if (server_mode(options) && !server_mode(old_options)) {
1301 if (init_keys() < 0) {
1302 log_warn(LD_BUG,"Error initializing keys; exiting");
1303 return -1;
1305 ip_address_changed(0);
1306 if (has_completed_circuit || !any_predicted_circuits(time(NULL)))
1307 inform_testing_reachability();
1309 cpuworkers_rotate();
1310 if (dns_reset())
1311 return -1;
1312 } else {
1313 if (dns_reset())
1314 return -1;
1317 if (options->V3AuthoritativeDir && !old_options->V3AuthoritativeDir)
1318 init_keys();
1321 /* Maybe load geoip file */
1322 if (options->GeoIPFile &&
1323 ((!old_options || !opt_streq(old_options->GeoIPFile, options->GeoIPFile))
1324 || !geoip_is_loaded())) {
1325 /* XXXX021 Don't use this "<default>" junk; make our filename options
1326 * understand prefixes somehow. -NM */
1327 char *actual_fname = tor_strdup(options->GeoIPFile);
1328 #ifdef WIN32
1329 if (!strcmp(actual_fname, "<default>")) {
1330 const char *conf_root = get_windows_conf_root();
1331 size_t len = strlen(conf_root)+16;
1332 tor_free(actual_fname);
1333 actual_fname = tor_malloc(len+1);
1334 tor_snprintf(actual_fname, len, "%s\\geoip", conf_root);
1336 #endif
1337 geoip_load_file(actual_fname, options);
1338 tor_free(actual_fname);
1340 /* Check if we need to parse and add the EntryNodes config option. */
1341 if (options->EntryNodes &&
1342 (!old_options ||
1343 !opt_streq(old_options->EntryNodes, options->EntryNodes)))
1344 entry_nodes_should_be_added();
1346 /* Since our options changed, we might need to regenerate and upload our
1347 * server descriptor.
1349 if (!old_options ||
1350 options_transition_affects_descriptor(old_options, options))
1351 mark_my_descriptor_dirty();
1353 /* We may need to reschedule some directory stuff if our status changed. */
1354 if (old_options) {
1355 if (authdir_mode_v3(options) && !authdir_mode_v3(old_options))
1356 dirvote_recalculate_timing(options, time(NULL));
1357 if (!bool_eq(directory_fetches_dir_info_early(options),
1358 directory_fetches_dir_info_early(old_options)) ||
1359 !bool_eq(directory_fetches_dir_info_later(options),
1360 directory_fetches_dir_info_later(old_options))) {
1361 /* Make sure update_router_have_min_dir_info gets called. */
1362 router_dir_info_changed();
1363 /* We might need to download a new consensus status later or sooner than
1364 * we had expected. */
1365 update_consensus_networkstatus_fetch_time(time(NULL));
1369 return 0;
1373 * Functions to parse config options
1376 /** If <b>option</b> is an official abbreviation for a longer option,
1377 * return the longer option. Otherwise return <b>option</b>.
1378 * If <b>command_line</b> is set, apply all abbreviations. Otherwise, only
1379 * apply abbreviations that work for the config file and the command line.
1380 * If <b>warn_obsolete</b> is set, warn about deprecated names. */
1381 static const char *
1382 expand_abbrev(config_format_t *fmt, const char *option, int command_line,
1383 int warn_obsolete)
1385 int i;
1386 if (! fmt->abbrevs)
1387 return option;
1388 for (i=0; fmt->abbrevs[i].abbreviated; ++i) {
1389 /* Abbreviations are casei. */
1390 if (!strcasecmp(option,fmt->abbrevs[i].abbreviated) &&
1391 (command_line || !fmt->abbrevs[i].commandline_only)) {
1392 if (warn_obsolete && fmt->abbrevs[i].warn) {
1393 log_warn(LD_CONFIG,
1394 "The configuration option '%s' is deprecated; "
1395 "use '%s' instead.",
1396 fmt->abbrevs[i].abbreviated,
1397 fmt->abbrevs[i].full);
1399 return fmt->abbrevs[i].full;
1402 return option;
1405 /** Helper: Read a list of configuration options from the command line.
1406 * If successful, put them in *<b>result</b> and return 0, and return
1407 * -1 and leave *<b>result</b> alone. */
1408 static int
1409 config_get_commandlines(int argc, char **argv, config_line_t **result)
1411 config_line_t *front = NULL;
1412 config_line_t **new = &front;
1413 char *s;
1414 int i = 1;
1416 while (i < argc) {
1417 if (!strcmp(argv[i],"-f") ||
1418 !strcmp(argv[i],"--hash-password")) {
1419 i += 2; /* command-line option with argument. ignore them. */
1420 continue;
1421 } else if (!strcmp(argv[i],"--list-fingerprint") ||
1422 !strcmp(argv[i],"--verify-config") ||
1423 !strcmp(argv[i],"--ignore-missing-torrc") ||
1424 !strcmp(argv[i],"--quiet") ||
1425 !strcmp(argv[i],"--hush")) {
1426 i += 1; /* command-line option. ignore it. */
1427 continue;
1428 } else if (!strcmp(argv[i],"--nt-service") ||
1429 !strcmp(argv[i],"-nt-service")) {
1430 i += 1;
1431 continue;
1434 if (i == argc-1) {
1435 log_warn(LD_CONFIG,"Command-line option '%s' with no value. Failing.",
1436 argv[i]);
1437 config_free_lines(front);
1438 return -1;
1441 *new = tor_malloc_zero(sizeof(config_line_t));
1442 s = argv[i];
1444 while (*s == '-')
1445 s++;
1447 (*new)->key = tor_strdup(expand_abbrev(&options_format, s, 1, 1));
1448 (*new)->value = tor_strdup(argv[i+1]);
1449 (*new)->next = NULL;
1450 log(LOG_DEBUG, LD_CONFIG, "Commandline: parsed keyword '%s', value '%s'",
1451 (*new)->key, (*new)->value);
1453 new = &((*new)->next);
1454 i += 2;
1456 *result = front;
1457 return 0;
1460 /** Helper: allocate a new configuration option mapping 'key' to 'val',
1461 * append it to *<b>lst</b>. */
1462 static void
1463 config_line_append(config_line_t **lst,
1464 const char *key,
1465 const char *val)
1467 config_line_t *newline;
1469 newline = tor_malloc(sizeof(config_line_t));
1470 newline->key = tor_strdup(key);
1471 newline->value = tor_strdup(val);
1472 newline->next = NULL;
1473 while (*lst)
1474 lst = &((*lst)->next);
1476 (*lst) = newline;
1479 /** Helper: parse the config string and strdup into key/value
1480 * strings. Set *result to the list, or NULL if parsing the string
1481 * failed. Return 0 on success, -1 on failure. Warn and ignore any
1482 * misformatted lines. */
1484 config_get_lines(const char *string, config_line_t **result)
1486 config_line_t *list = NULL, **next;
1487 char *k, *v;
1489 next = &list;
1490 do {
1491 string = parse_config_line_from_str(string, &k, &v);
1492 if (!string) {
1493 config_free_lines(list);
1494 return -1;
1496 if (k && v) {
1497 /* This list can get long, so we keep a pointer to the end of it
1498 * rather than using config_line_append over and over and getting
1499 * n^2 performance. */
1500 *next = tor_malloc(sizeof(config_line_t));
1501 (*next)->key = k;
1502 (*next)->value = v;
1503 (*next)->next = NULL;
1504 next = &((*next)->next);
1505 } else {
1506 tor_free(k);
1507 tor_free(v);
1509 } while (*string);
1511 *result = list;
1512 return 0;
1516 * Free all the configuration lines on the linked list <b>front</b>.
1518 void
1519 config_free_lines(config_line_t *front)
1521 config_line_t *tmp;
1523 while (front) {
1524 tmp = front;
1525 front = tmp->next;
1527 tor_free(tmp->key);
1528 tor_free(tmp->value);
1529 tor_free(tmp);
1533 /** Return the description for a given configuration variable, or NULL if no
1534 * description exists. */
1535 static const char *
1536 config_find_description(config_format_t *fmt, const char *name)
1538 int i;
1539 for (i=0; fmt->descriptions[i].name; ++i) {
1540 if (!strcasecmp(name, fmt->descriptions[i].name))
1541 return fmt->descriptions[i].description;
1543 return NULL;
1546 /** If <b>key</b> is a configuration option, return the corresponding
1547 * config_var_t. Otherwise, if <b>key</b> is a non-standard abbreviation,
1548 * warn, and return the corresponding config_var_t. Otherwise return NULL.
1550 static config_var_t *
1551 config_find_option(config_format_t *fmt, const char *key)
1553 int i;
1554 size_t keylen = strlen(key);
1555 if (!keylen)
1556 return NULL; /* if they say "--" on the commandline, it's not an option */
1557 /* First, check for an exact (case-insensitive) match */
1558 for (i=0; fmt->vars[i].name; ++i) {
1559 if (!strcasecmp(key, fmt->vars[i].name)) {
1560 return &fmt->vars[i];
1563 /* If none, check for an abbreviated match */
1564 for (i=0; fmt->vars[i].name; ++i) {
1565 if (!strncasecmp(key, fmt->vars[i].name, keylen)) {
1566 log_warn(LD_CONFIG, "The abbreviation '%s' is deprecated. "
1567 "Please use '%s' instead",
1568 key, fmt->vars[i].name);
1569 return &fmt->vars[i];
1572 /* Okay, unrecognized option */
1573 return NULL;
1577 * Functions to assign config options.
1580 /** <b>c</b>-\>key is known to be a real key. Update <b>options</b>
1581 * with <b>c</b>-\>value and return 0, or return -1 if bad value.
1583 * Called from config_assign_line() and option_reset().
1585 static int
1586 config_assign_value(config_format_t *fmt, or_options_t *options,
1587 config_line_t *c, char **msg)
1589 int i, r, ok;
1590 char buf[1024];
1591 config_var_t *var;
1592 void *lvalue;
1594 CHECK(fmt, options);
1596 var = config_find_option(fmt, c->key);
1597 tor_assert(var);
1599 lvalue = STRUCT_VAR_P(options, var->var_offset);
1601 switch (var->type) {
1603 case CONFIG_TYPE_UINT:
1604 i = (int)tor_parse_long(c->value, 10, 0, INT_MAX, &ok, NULL);
1605 if (!ok) {
1606 r = tor_snprintf(buf, sizeof(buf),
1607 "Int keyword '%s %s' is malformed or out of bounds.",
1608 c->key, c->value);
1609 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1610 return -1;
1612 *(int *)lvalue = i;
1613 break;
1615 case CONFIG_TYPE_INTERVAL: {
1616 i = config_parse_interval(c->value, &ok);
1617 if (!ok) {
1618 r = tor_snprintf(buf, sizeof(buf),
1619 "Interval '%s %s' is malformed or out of bounds.",
1620 c->key, c->value);
1621 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1622 return -1;
1624 *(int *)lvalue = i;
1625 break;
1628 case CONFIG_TYPE_MEMUNIT: {
1629 uint64_t u64 = config_parse_memunit(c->value, &ok);
1630 if (!ok) {
1631 r = tor_snprintf(buf, sizeof(buf),
1632 "Value '%s %s' is malformed or out of bounds.",
1633 c->key, c->value);
1634 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1635 return -1;
1637 *(uint64_t *)lvalue = u64;
1638 break;
1641 case CONFIG_TYPE_BOOL:
1642 i = (int)tor_parse_long(c->value, 10, 0, 1, &ok, NULL);
1643 if (!ok) {
1644 r = tor_snprintf(buf, sizeof(buf),
1645 "Boolean '%s %s' expects 0 or 1.",
1646 c->key, c->value);
1647 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1648 return -1;
1650 *(int *)lvalue = i;
1651 break;
1653 case CONFIG_TYPE_STRING:
1654 case CONFIG_TYPE_FILENAME:
1655 tor_free(*(char **)lvalue);
1656 *(char **)lvalue = tor_strdup(c->value);
1657 break;
1659 case CONFIG_TYPE_DOUBLE:
1660 *(double *)lvalue = atof(c->value);
1661 break;
1663 case CONFIG_TYPE_ISOTIME:
1664 if (parse_iso_time(c->value, (time_t *)lvalue)) {
1665 r = tor_snprintf(buf, sizeof(buf),
1666 "Invalid time '%s' for keyword '%s'", c->value, c->key);
1667 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1668 return -1;
1670 break;
1672 case CONFIG_TYPE_ROUTERSET:
1673 if (*(routerset_t**)lvalue) {
1674 routerset_free(*(routerset_t**)lvalue);
1676 *(routerset_t**)lvalue = routerset_new();
1677 if (routerset_parse(*(routerset_t**)lvalue, c->value, c->key)<0) {
1678 tor_snprintf(buf, sizeof(buf), "Invalid exit list '%s' for option '%s'",
1679 c->value, c->key);
1680 *msg = tor_strdup(buf);
1681 return -1;
1683 break;
1685 case CONFIG_TYPE_CSV:
1686 if (*(smartlist_t**)lvalue) {
1687 SMARTLIST_FOREACH(*(smartlist_t**)lvalue, char *, cp, tor_free(cp));
1688 smartlist_clear(*(smartlist_t**)lvalue);
1689 } else {
1690 *(smartlist_t**)lvalue = smartlist_create();
1693 smartlist_split_string(*(smartlist_t**)lvalue, c->value, ",",
1694 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1695 break;
1697 case CONFIG_TYPE_LINELIST:
1698 case CONFIG_TYPE_LINELIST_S:
1699 config_line_append((config_line_t**)lvalue, c->key, c->value);
1700 break;
1702 case CONFIG_TYPE_OBSOLETE:
1703 log_warn(LD_CONFIG, "Skipping obsolete configuration option '%s'", c->key);
1704 break;
1705 case CONFIG_TYPE_LINELIST_V:
1706 r = tor_snprintf(buf, sizeof(buf),
1707 "You may not provide a value for virtual option '%s'", c->key);
1708 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1709 return -1;
1710 default:
1711 tor_assert(0);
1712 break;
1714 return 0;
1717 /** If <b>c</b> is a syntactically valid configuration line, update
1718 * <b>options</b> with its value and return 0. Otherwise return -1 for bad
1719 * key, -2 for bad value.
1721 * If <b>clear_first</b> is set, clear the value first. Then if
1722 * <b>use_defaults</b> is set, set the value to the default.
1724 * Called from config_assign().
1726 static int
1727 config_assign_line(config_format_t *fmt, or_options_t *options,
1728 config_line_t *c, int use_defaults,
1729 int clear_first, char **msg)
1731 config_var_t *var;
1733 CHECK(fmt, options);
1735 var = config_find_option(fmt, c->key);
1736 if (!var) {
1737 if (fmt->extra) {
1738 void *lvalue = STRUCT_VAR_P(options, fmt->extra->var_offset);
1739 log_info(LD_CONFIG,
1740 "Found unrecognized option '%s'; saving it.", c->key);
1741 config_line_append((config_line_t**)lvalue, c->key, c->value);
1742 return 0;
1743 } else {
1744 char buf[1024];
1745 int tmp = tor_snprintf(buf, sizeof(buf),
1746 "Unknown option '%s'. Failing.", c->key);
1747 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1748 return -1;
1751 /* Put keyword into canonical case. */
1752 if (strcmp(var->name, c->key)) {
1753 tor_free(c->key);
1754 c->key = tor_strdup(var->name);
1757 if (!strlen(c->value)) {
1758 /* reset or clear it, then return */
1759 if (!clear_first) {
1760 if (var->type == CONFIG_TYPE_LINELIST ||
1761 var->type == CONFIG_TYPE_LINELIST_S) {
1762 /* We got an empty linelist from the torrc or commandline.
1763 As a special case, call this an error. Warn and ignore. */
1764 log_warn(LD_CONFIG,
1765 "Linelist option '%s' has no value. Skipping.", c->key);
1766 } else { /* not already cleared */
1767 option_reset(fmt, options, var, use_defaults);
1770 return 0;
1773 if (config_assign_value(fmt, options, c, msg) < 0)
1774 return -2;
1775 return 0;
1778 /** Restore the option named <b>key</b> in options to its default value.
1779 * Called from config_assign(). */
1780 static void
1781 config_reset_line(config_format_t *fmt, or_options_t *options,
1782 const char *key, int use_defaults)
1784 config_var_t *var;
1786 CHECK(fmt, options);
1788 var = config_find_option(fmt, key);
1789 if (!var)
1790 return; /* give error on next pass. */
1792 option_reset(fmt, options, var, use_defaults);
1795 /** Return true iff key is a valid configuration option. */
1797 option_is_recognized(const char *key)
1799 config_var_t *var = config_find_option(&options_format, key);
1800 return (var != NULL);
1803 /** Return the canonical name of a configuration option, or NULL
1804 * if no such option exists. */
1805 const char *
1806 option_get_canonical_name(const char *key)
1808 config_var_t *var = config_find_option(&options_format, key);
1809 return var ? var->name : NULL;
1812 /** Return a canonicalized list of the options assigned for key.
1814 config_line_t *
1815 option_get_assignment(or_options_t *options, const char *key)
1817 return get_assigned_option(&options_format, options, key, 1);
1820 /** Return true iff value needs to be quoted and escaped to be used in
1821 * a configuration file. */
1822 static int
1823 config_value_needs_escape(const char *value)
1825 if (*value == '\"')
1826 return 1;
1827 while (*value) {
1828 switch (*value)
1830 case '\r':
1831 case '\n':
1832 case '#':
1833 /* Note: quotes and backspaces need special handling when we are using
1834 * quotes, not otherwise, so they don't trigger escaping on their
1835 * own. */
1836 return 1;
1837 default:
1838 if (!TOR_ISPRINT(*value))
1839 return 1;
1841 ++value;
1843 return 0;
1846 /** Return a newly allocated deep copy of the lines in <b>inp</b>. */
1847 static config_line_t *
1848 config_lines_dup(const config_line_t *inp)
1850 config_line_t *result = NULL;
1851 config_line_t **next_out = &result;
1852 while (inp) {
1853 *next_out = tor_malloc(sizeof(config_line_t));
1854 (*next_out)->key = tor_strdup(inp->key);
1855 (*next_out)->value = tor_strdup(inp->value);
1856 inp = inp->next;
1857 next_out = &((*next_out)->next);
1859 (*next_out) = NULL;
1860 return result;
1863 /** Return newly allocated line or lines corresponding to <b>key</b> in the
1864 * configuration <b>options</b>. If <b>escape_val</b> is true and a
1865 * value needs to be quoted before it's put in a config file, quote and
1866 * escape that value. Return NULL if no such key exists. */
1867 static config_line_t *
1868 get_assigned_option(config_format_t *fmt, or_options_t *options,
1869 const char *key, int escape_val)
1870 /* XXXX argument is options, but fmt is provided. Inconsistent. */
1872 config_var_t *var;
1873 const void *value;
1874 char buf[32];
1875 config_line_t *result;
1876 tor_assert(options && key);
1878 CHECK(fmt, options);
1880 var = config_find_option(fmt, key);
1881 if (!var) {
1882 log_warn(LD_CONFIG, "Unknown option '%s'. Failing.", key);
1883 return NULL;
1885 value = STRUCT_VAR_P(options, var->var_offset);
1887 result = tor_malloc_zero(sizeof(config_line_t));
1888 result->key = tor_strdup(var->name);
1889 switch (var->type)
1891 case CONFIG_TYPE_STRING:
1892 case CONFIG_TYPE_FILENAME:
1893 if (*(char**)value) {
1894 result->value = tor_strdup(*(char**)value);
1895 } else {
1896 tor_free(result->key);
1897 tor_free(result);
1898 return NULL;
1900 break;
1901 case CONFIG_TYPE_ISOTIME:
1902 if (*(time_t*)value) {
1903 result->value = tor_malloc(ISO_TIME_LEN+1);
1904 format_iso_time(result->value, *(time_t*)value);
1905 } else {
1906 tor_free(result->key);
1907 tor_free(result);
1909 escape_val = 0; /* Can't need escape. */
1910 break;
1911 case CONFIG_TYPE_INTERVAL:
1912 case CONFIG_TYPE_UINT:
1913 /* This means every or_options_t uint or bool element
1914 * needs to be an int. Not, say, a uint16_t or char. */
1915 tor_snprintf(buf, sizeof(buf), "%d", *(int*)value);
1916 result->value = tor_strdup(buf);
1917 escape_val = 0; /* Can't need escape. */
1918 break;
1919 case CONFIG_TYPE_MEMUNIT:
1920 tor_snprintf(buf, sizeof(buf), U64_FORMAT,
1921 U64_PRINTF_ARG(*(uint64_t*)value));
1922 result->value = tor_strdup(buf);
1923 escape_val = 0; /* Can't need escape. */
1924 break;
1925 case CONFIG_TYPE_DOUBLE:
1926 tor_snprintf(buf, sizeof(buf), "%f", *(double*)value);
1927 result->value = tor_strdup(buf);
1928 escape_val = 0; /* Can't need escape. */
1929 break;
1930 case CONFIG_TYPE_BOOL:
1931 result->value = tor_strdup(*(int*)value ? "1" : "0");
1932 escape_val = 0; /* Can't need escape. */
1933 break;
1934 case CONFIG_TYPE_ROUTERSET:
1935 result->value = routerset_to_string(*(routerset_t**)value);
1936 break;
1937 case CONFIG_TYPE_CSV:
1938 if (*(smartlist_t**)value)
1939 result->value =
1940 smartlist_join_strings(*(smartlist_t**)value, ",", 0, NULL);
1941 else
1942 result->value = tor_strdup("");
1943 break;
1944 case CONFIG_TYPE_OBSOLETE:
1945 log_warn(LD_CONFIG,
1946 "You asked me for the value of an obsolete config option '%s'.",
1947 key);
1948 tor_free(result->key);
1949 tor_free(result);
1950 return NULL;
1951 case CONFIG_TYPE_LINELIST_S:
1952 log_warn(LD_CONFIG,
1953 "Can't return context-sensitive '%s' on its own", key);
1954 tor_free(result->key);
1955 tor_free(result);
1956 return NULL;
1957 case CONFIG_TYPE_LINELIST:
1958 case CONFIG_TYPE_LINELIST_V:
1959 tor_free(result->key);
1960 tor_free(result);
1961 result = config_lines_dup(*(const config_line_t**)value);
1962 break;
1963 default:
1964 tor_free(result->key);
1965 tor_free(result);
1966 log_warn(LD_BUG,"Unknown type %d for known key '%s'",
1967 var->type, key);
1968 return NULL;
1971 if (escape_val) {
1972 config_line_t *line;
1973 for (line = result; line; line = line->next) {
1974 if (line->value && config_value_needs_escape(line->value)) {
1975 char *newval = esc_for_log(line->value);
1976 tor_free(line->value);
1977 line->value = newval;
1982 return result;
1985 /** Iterate through the linked list of requested options <b>list</b>.
1986 * For each item, convert as appropriate and assign to <b>options</b>.
1987 * If an item is unrecognized, set *msg and return -1 immediately,
1988 * else return 0 for success.
1990 * If <b>clear_first</b>, interpret config options as replacing (not
1991 * extending) their previous values. If <b>clear_first</b> is set,
1992 * then <b>use_defaults</b> to decide if you set to defaults after
1993 * clearing, or make the value 0 or NULL.
1995 * Here are the use cases:
1996 * 1. A non-empty AllowInvalid line in your torrc. Appends to current
1997 * if linelist, replaces current if csv.
1998 * 2. An empty AllowInvalid line in your torrc. Should clear it.
1999 * 3. "RESETCONF AllowInvalid" sets it to default.
2000 * 4. "SETCONF AllowInvalid" makes it NULL.
2001 * 5. "SETCONF AllowInvalid=foo" clears it and sets it to "foo".
2003 * Use_defaults Clear_first
2004 * 0 0 "append"
2005 * 1 0 undefined, don't use
2006 * 0 1 "set to null first"
2007 * 1 1 "set to defaults first"
2008 * Return 0 on success, -1 on bad key, -2 on bad value.
2010 * As an additional special case, if a LINELIST config option has
2011 * no value and clear_first is 0, then warn and ignore it.
2015 There are three call cases for config_assign() currently.
2017 Case one: Torrc entry
2018 options_init_from_torrc() calls config_assign(0, 0)
2019 calls config_assign_line(0, 0).
2020 if value is empty, calls option_reset(0) and returns.
2021 calls config_assign_value(), appends.
2023 Case two: setconf
2024 options_trial_assign() calls config_assign(0, 1)
2025 calls config_reset_line(0)
2026 calls option_reset(0)
2027 calls option_clear().
2028 calls config_assign_line(0, 1).
2029 if value is empty, returns.
2030 calls config_assign_value(), appends.
2032 Case three: resetconf
2033 options_trial_assign() calls config_assign(1, 1)
2034 calls config_reset_line(1)
2035 calls option_reset(1)
2036 calls option_clear().
2037 calls config_assign_value(default)
2038 calls config_assign_line(1, 1).
2039 returns.
2041 static int
2042 config_assign(config_format_t *fmt, void *options, config_line_t *list,
2043 int use_defaults, int clear_first, char **msg)
2045 config_line_t *p;
2047 CHECK(fmt, options);
2049 /* pass 1: normalize keys */
2050 for (p = list; p; p = p->next) {
2051 const char *full = expand_abbrev(fmt, p->key, 0, 1);
2052 if (strcmp(full,p->key)) {
2053 tor_free(p->key);
2054 p->key = tor_strdup(full);
2058 /* pass 2: if we're reading from a resetting source, clear all
2059 * mentioned config options, and maybe set to their defaults. */
2060 if (clear_first) {
2061 for (p = list; p; p = p->next)
2062 config_reset_line(fmt, options, p->key, use_defaults);
2065 /* pass 3: assign. */
2066 while (list) {
2067 int r;
2068 if ((r=config_assign_line(fmt, options, list, use_defaults,
2069 clear_first, msg)))
2070 return r;
2071 list = list->next;
2073 return 0;
2076 /** Try assigning <b>list</b> to the global options. You do this by duping
2077 * options, assigning list to the new one, then validating it. If it's
2078 * ok, then throw out the old one and stick with the new one. Else,
2079 * revert to old and return failure. Return SETOPT_OK on success, or
2080 * a setopt_err_t on failure.
2082 * If not success, point *<b>msg</b> to a newly allocated string describing
2083 * what went wrong.
2085 setopt_err_t
2086 options_trial_assign(config_line_t *list, int use_defaults,
2087 int clear_first, char **msg)
2089 int r;
2090 or_options_t *trial_options = options_dup(&options_format, get_options());
2092 if ((r=config_assign(&options_format, trial_options,
2093 list, use_defaults, clear_first, msg)) < 0) {
2094 config_free(&options_format, trial_options);
2095 return r;
2098 if (options_validate(get_options(), trial_options, 1, msg) < 0) {
2099 config_free(&options_format, trial_options);
2100 return SETOPT_ERR_PARSE; /*XXX021 make this separate. */
2103 if (options_transition_allowed(get_options(), trial_options, msg) < 0) {
2104 config_free(&options_format, trial_options);
2105 return SETOPT_ERR_TRANSITION;
2108 if (set_options(trial_options, msg)<0) {
2109 config_free(&options_format, trial_options);
2110 return SETOPT_ERR_SETTING;
2113 /* we liked it. put it in place. */
2114 return SETOPT_OK;
2117 /** Reset config option <b>var</b> to 0, 0.0, NULL, or the equivalent.
2118 * Called from option_reset() and config_free(). */
2119 static void
2120 option_clear(config_format_t *fmt, or_options_t *options, config_var_t *var)
2122 void *lvalue = STRUCT_VAR_P(options, var->var_offset);
2123 (void)fmt; /* unused */
2124 switch (var->type) {
2125 case CONFIG_TYPE_STRING:
2126 case CONFIG_TYPE_FILENAME:
2127 tor_free(*(char**)lvalue);
2128 break;
2129 case CONFIG_TYPE_DOUBLE:
2130 *(double*)lvalue = 0.0;
2131 break;
2132 case CONFIG_TYPE_ISOTIME:
2133 *(time_t*)lvalue = 0;
2134 case CONFIG_TYPE_INTERVAL:
2135 case CONFIG_TYPE_UINT:
2136 case CONFIG_TYPE_BOOL:
2137 *(int*)lvalue = 0;
2138 break;
2139 case CONFIG_TYPE_MEMUNIT:
2140 *(uint64_t*)lvalue = 0;
2141 break;
2142 case CONFIG_TYPE_ROUTERSET:
2143 if (*(routerset_t**)lvalue) {
2144 routerset_free(*(routerset_t**)lvalue);
2145 *(routerset_t**)lvalue = NULL;
2147 case CONFIG_TYPE_CSV:
2148 if (*(smartlist_t**)lvalue) {
2149 SMARTLIST_FOREACH(*(smartlist_t **)lvalue, char *, cp, tor_free(cp));
2150 smartlist_free(*(smartlist_t **)lvalue);
2151 *(smartlist_t **)lvalue = NULL;
2153 break;
2154 case CONFIG_TYPE_LINELIST:
2155 case CONFIG_TYPE_LINELIST_S:
2156 config_free_lines(*(config_line_t **)lvalue);
2157 *(config_line_t **)lvalue = NULL;
2158 break;
2159 case CONFIG_TYPE_LINELIST_V:
2160 /* handled by linelist_s. */
2161 break;
2162 case CONFIG_TYPE_OBSOLETE:
2163 break;
2167 /** Clear the option indexed by <b>var</b> in <b>options</b>. Then if
2168 * <b>use_defaults</b>, set it to its default value.
2169 * Called by config_init() and option_reset_line() and option_assign_line(). */
2170 static void
2171 option_reset(config_format_t *fmt, or_options_t *options,
2172 config_var_t *var, int use_defaults)
2174 config_line_t *c;
2175 char *msg = NULL;
2176 CHECK(fmt, options);
2177 option_clear(fmt, options, var); /* clear it first */
2178 if (!use_defaults)
2179 return; /* all done */
2180 if (var->initvalue) {
2181 c = tor_malloc_zero(sizeof(config_line_t));
2182 c->key = tor_strdup(var->name);
2183 c->value = tor_strdup(var->initvalue);
2184 if (config_assign_value(fmt, options, c, &msg) < 0) {
2185 log_warn(LD_BUG, "Failed to assign default: %s", msg);
2186 tor_free(msg); /* if this happens it's a bug */
2188 config_free_lines(c);
2192 /** Print a usage message for tor. */
2193 static void
2194 print_usage(void)
2196 printf(
2197 "Copyright (c) 2001-2004, Roger Dingledine\n"
2198 "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
2199 "Copyright (c) 2007-2008, The Tor Project, Inc.\n\n"
2200 "tor -f <torrc> [args]\n"
2201 "See man page for options, or https://www.torproject.org/ for "
2202 "documentation.\n");
2205 /** Print all non-obsolete torrc options. */
2206 static void
2207 list_torrc_options(void)
2209 int i;
2210 smartlist_t *lines = smartlist_create();
2211 for (i = 0; _option_vars[i].name; ++i) {
2212 config_var_t *var = &_option_vars[i];
2213 const char *desc;
2214 if (var->type == CONFIG_TYPE_OBSOLETE ||
2215 var->type == CONFIG_TYPE_LINELIST_V)
2216 continue;
2217 desc = config_find_description(&options_format, var->name);
2218 printf("%s\n", var->name);
2219 if (desc) {
2220 wrap_string(lines, desc, 76, " ", " ");
2221 SMARTLIST_FOREACH(lines, char *, cp, {
2222 printf("%s", cp);
2223 tor_free(cp);
2225 smartlist_clear(lines);
2228 smartlist_free(lines);
2231 /** Last value actually set by resolve_my_address. */
2232 static uint32_t last_resolved_addr = 0;
2234 * Based on <b>options-\>Address</b>, guess our public IP address and put it
2235 * (in host order) into *<b>addr_out</b>. If <b>hostname_out</b> is provided,
2236 * set *<b>hostname_out</b> to a new string holding the hostname we used to
2237 * get the address. Return 0 if all is well, or -1 if we can't find a suitable
2238 * public IP address.
2241 resolve_my_address(int warn_severity, or_options_t *options,
2242 uint32_t *addr_out, char **hostname_out)
2244 struct in_addr in;
2245 struct hostent *rent;
2246 char hostname[256];
2247 int explicit_ip=1;
2248 int explicit_hostname=1;
2249 int from_interface=0;
2250 char tmpbuf[INET_NTOA_BUF_LEN];
2251 const char *address = options->Address;
2252 int notice_severity = warn_severity <= LOG_NOTICE ?
2253 LOG_NOTICE : warn_severity;
2255 tor_assert(addr_out);
2257 if (address && *address) {
2258 strlcpy(hostname, address, sizeof(hostname));
2259 } else { /* then we need to guess our address */
2260 explicit_ip = 0; /* it's implicit */
2261 explicit_hostname = 0; /* it's implicit */
2263 if (gethostname(hostname, sizeof(hostname)) < 0) {
2264 log_fn(warn_severity, LD_NET,"Error obtaining local hostname");
2265 return -1;
2267 log_debug(LD_CONFIG,"Guessed local host name as '%s'",hostname);
2270 /* now we know hostname. resolve it and keep only the IP address */
2272 if (tor_inet_aton(hostname, &in) == 0) {
2273 /* then we have to resolve it */
2274 explicit_ip = 0;
2275 rent = (struct hostent *)gethostbyname(hostname);
2276 if (!rent) {
2277 uint32_t interface_ip;
2279 if (explicit_hostname) {
2280 log_fn(warn_severity, LD_CONFIG,
2281 "Could not resolve local Address '%s'. Failing.", hostname);
2282 return -1;
2284 log_fn(notice_severity, LD_CONFIG,
2285 "Could not resolve guessed local hostname '%s'. "
2286 "Trying something else.", hostname);
2287 if (get_interface_address(warn_severity, &interface_ip)) {
2288 log_fn(warn_severity, LD_CONFIG,
2289 "Could not get local interface IP address. Failing.");
2290 return -1;
2292 from_interface = 1;
2293 in.s_addr = htonl(interface_ip);
2294 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2295 log_fn(notice_severity, LD_CONFIG, "Learned IP address '%s' for "
2296 "local interface. Using that.", tmpbuf);
2297 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2298 } else {
2299 tor_assert(rent->h_length == 4);
2300 memcpy(&in.s_addr, rent->h_addr, rent->h_length);
2302 if (!explicit_hostname &&
2303 is_internal_IP(ntohl(in.s_addr), 0)) {
2304 uint32_t interface_ip;
2306 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2307 log_fn(notice_severity, LD_CONFIG, "Guessed local hostname '%s' "
2308 "resolves to a private IP address (%s). Trying something "
2309 "else.", hostname, tmpbuf);
2311 if (get_interface_address(warn_severity, &interface_ip)) {
2312 log_fn(warn_severity, LD_CONFIG,
2313 "Could not get local interface IP address. Too bad.");
2314 } else if (is_internal_IP(interface_ip, 0)) {
2315 struct in_addr in2;
2316 in2.s_addr = htonl(interface_ip);
2317 tor_inet_ntoa(&in2,tmpbuf,sizeof(tmpbuf));
2318 log_fn(notice_severity, LD_CONFIG,
2319 "Interface IP address '%s' is a private address too. "
2320 "Ignoring.", tmpbuf);
2321 } else {
2322 from_interface = 1;
2323 in.s_addr = htonl(interface_ip);
2324 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2325 log_fn(notice_severity, LD_CONFIG,
2326 "Learned IP address '%s' for local interface."
2327 " Using that.", tmpbuf);
2328 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2334 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2335 if (is_internal_IP(ntohl(in.s_addr), 0) &&
2336 options->_PublishServerDescriptor) {
2337 /* make sure we're ok with publishing an internal IP */
2338 if (!options->DirServers && !options->AlternateDirAuthority) {
2339 /* if they are using the default dirservers, disallow internal IPs
2340 * always. */
2341 log_fn(warn_severity, LD_CONFIG,
2342 "Address '%s' resolves to private IP address '%s'. "
2343 "Tor servers that use the default DirServers must have public "
2344 "IP addresses.", hostname, tmpbuf);
2345 return -1;
2347 if (!explicit_ip) {
2348 /* even if they've set their own dirservers, require an explicit IP if
2349 * they're using an internal address. */
2350 log_fn(warn_severity, LD_CONFIG, "Address '%s' resolves to private "
2351 "IP address '%s'. Please set the Address config option to be "
2352 "the IP address you want to use.", hostname, tmpbuf);
2353 return -1;
2357 log_debug(LD_CONFIG, "Resolved Address to '%s'.", tmpbuf);
2358 *addr_out = ntohl(in.s_addr);
2359 if (last_resolved_addr && last_resolved_addr != *addr_out) {
2360 /* Leave this as a notice, regardless of the requested severity,
2361 * at least until dynamic IP address support becomes bulletproof. */
2362 log_notice(LD_NET,
2363 "Your IP address seems to have changed to %s. Updating.",
2364 tmpbuf);
2365 ip_address_changed(0);
2367 if (last_resolved_addr != *addr_out) {
2368 const char *method;
2369 const char *h = hostname;
2370 if (explicit_ip) {
2371 method = "CONFIGURED";
2372 h = NULL;
2373 } else if (explicit_hostname) {
2374 method = "RESOLVED";
2375 } else if (from_interface) {
2376 method = "INTERFACE";
2377 h = NULL;
2378 } else {
2379 method = "GETHOSTNAME";
2381 control_event_server_status(LOG_NOTICE,
2382 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s %s%s",
2383 tmpbuf, method, h?"HOSTNAME=":"", h);
2385 last_resolved_addr = *addr_out;
2386 if (hostname_out)
2387 *hostname_out = tor_strdup(hostname);
2388 return 0;
2391 /** Return true iff <b>addr</b> is judged to be on the same network as us, or
2392 * on a private network.
2395 is_local_addr(const tor_addr_t *addr)
2397 if (tor_addr_is_internal(addr, 0))
2398 return 1;
2399 /* Check whether ip is on the same /24 as we are. */
2400 if (get_options()->EnforceDistinctSubnets == 0)
2401 return 0;
2402 if (tor_addr_family(addr) == AF_INET) {
2403 /*XXXX021 IP6 what corresponds to an /24? */
2404 uint32_t ip = tor_addr_to_ipv4h(addr);
2406 /* It's possible that this next check will hit before the first time
2407 * resolve_my_address actually succeeds. (For clients, it is likely that
2408 * resolve_my_address will never be called at all). In those cases,
2409 * last_resolved_addr will be 0, and so checking to see whether ip is on
2410 * the same /24 as last_resolved_addr will be the same as checking whether
2411 * it was on net 0, which is already done by is_internal_IP.
2413 if ((last_resolved_addr & 0xffffff00ul) == (ip & 0xffffff00ul))
2414 return 1;
2416 return 0;
2419 /** Called when we don't have a nickname set. Try to guess a good nickname
2420 * based on the hostname, and return it in a newly allocated string. If we
2421 * can't, return NULL and let the caller warn if it wants to. */
2422 static char *
2423 get_default_nickname(void)
2425 static const char * const bad_default_nicknames[] = {
2426 "localhost",
2427 NULL,
2429 char localhostname[256];
2430 char *cp, *out, *outp;
2431 int i;
2433 if (gethostname(localhostname, sizeof(localhostname)) < 0)
2434 return NULL;
2436 /* Put it in lowercase; stop at the first dot. */
2437 if ((cp = strchr(localhostname, '.')))
2438 *cp = '\0';
2439 tor_strlower(localhostname);
2441 /* Strip invalid characters. */
2442 cp = localhostname;
2443 out = outp = tor_malloc(strlen(localhostname) + 1);
2444 while (*cp) {
2445 if (strchr(LEGAL_NICKNAME_CHARACTERS, *cp))
2446 *outp++ = *cp++;
2447 else
2448 cp++;
2450 *outp = '\0';
2452 /* Enforce length. */
2453 if (strlen(out) > MAX_NICKNAME_LEN)
2454 out[MAX_NICKNAME_LEN]='\0';
2456 /* Check for dumb names. */
2457 for (i = 0; bad_default_nicknames[i]; ++i) {
2458 if (!strcmp(out, bad_default_nicknames[i])) {
2459 tor_free(out);
2460 return NULL;
2464 return out;
2467 /** Release storage held by <b>options</b>. */
2468 static void
2469 config_free(config_format_t *fmt, void *options)
2471 int i;
2473 tor_assert(options);
2475 for (i=0; fmt->vars[i].name; ++i)
2476 option_clear(fmt, options, &(fmt->vars[i]));
2477 if (fmt->extra) {
2478 config_line_t **linep = STRUCT_VAR_P(options, fmt->extra->var_offset);
2479 config_free_lines(*linep);
2480 *linep = NULL;
2482 tor_free(options);
2485 /** Return true iff a and b contain identical keys and values in identical
2486 * order. */
2487 static int
2488 config_lines_eq(config_line_t *a, config_line_t *b)
2490 while (a && b) {
2491 if (strcasecmp(a->key, b->key) || strcmp(a->value, b->value))
2492 return 0;
2493 a = a->next;
2494 b = b->next;
2496 if (a || b)
2497 return 0;
2498 return 1;
2501 /** Return true iff the option <b>name</b> has the same value in <b>o1</b>
2502 * and <b>o2</b>. Must not be called for LINELIST_S or OBSOLETE options.
2504 static int
2505 option_is_same(config_format_t *fmt,
2506 or_options_t *o1, or_options_t *o2, const char *name)
2508 config_line_t *c1, *c2;
2509 int r = 1;
2510 CHECK(fmt, o1);
2511 CHECK(fmt, o2);
2513 c1 = get_assigned_option(fmt, o1, name, 0);
2514 c2 = get_assigned_option(fmt, o2, name, 0);
2515 r = config_lines_eq(c1, c2);
2516 config_free_lines(c1);
2517 config_free_lines(c2);
2518 return r;
2521 /** Copy storage held by <b>old</b> into a new or_options_t and return it. */
2522 static or_options_t *
2523 options_dup(config_format_t *fmt, or_options_t *old)
2525 or_options_t *newopts;
2526 int i;
2527 config_line_t *line;
2529 newopts = config_alloc(fmt);
2530 for (i=0; fmt->vars[i].name; ++i) {
2531 if (fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
2532 continue;
2533 if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE)
2534 continue;
2535 line = get_assigned_option(fmt, old, fmt->vars[i].name, 0);
2536 if (line) {
2537 char *msg = NULL;
2538 if (config_assign(fmt, newopts, line, 0, 0, &msg) < 0) {
2539 log_err(LD_BUG, "Config_get_assigned_option() generated "
2540 "something we couldn't config_assign(): %s", msg);
2541 tor_free(msg);
2542 tor_assert(0);
2545 config_free_lines(line);
2547 return newopts;
2550 /** Return a new empty or_options_t. Used for testing. */
2551 or_options_t *
2552 options_new(void)
2554 return config_alloc(&options_format);
2557 /** Set <b>options</b> to hold reasonable defaults for most options.
2558 * Each option defaults to zero. */
2559 void
2560 options_init(or_options_t *options)
2562 config_init(&options_format, options);
2565 /** Set all vars in the configuration object <b>options</b> to their default
2566 * values. */
2567 static void
2568 config_init(config_format_t *fmt, void *options)
2570 int i;
2571 config_var_t *var;
2572 CHECK(fmt, options);
2574 for (i=0; fmt->vars[i].name; ++i) {
2575 var = &fmt->vars[i];
2576 if (!var->initvalue)
2577 continue; /* defaults to NULL or 0 */
2578 option_reset(fmt, options, var, 1);
2582 /** Allocate and return a new string holding the written-out values of the vars
2583 * in 'options'. If 'minimal', do not write out any default-valued vars.
2584 * Else, if comment_defaults, write default values as comments.
2586 static char *
2587 config_dump(config_format_t *fmt, void *options, int minimal,
2588 int comment_defaults)
2590 smartlist_t *elements;
2591 or_options_t *defaults;
2592 config_line_t *line, *assigned;
2593 char *result;
2594 int i;
2595 const char *desc;
2596 char *msg = NULL;
2598 defaults = config_alloc(fmt);
2599 config_init(fmt, defaults);
2601 /* XXX use a 1 here so we don't add a new log line while dumping */
2602 if (fmt->validate_fn(NULL,defaults, 1, &msg) < 0) {
2603 log_err(LD_BUG, "Failed to validate default config.");
2604 tor_free(msg);
2605 tor_assert(0);
2608 elements = smartlist_create();
2609 for (i=0; fmt->vars[i].name; ++i) {
2610 int comment_option = 0;
2611 if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE ||
2612 fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
2613 continue;
2614 /* Don't save 'hidden' control variables. */
2615 if (!strcmpstart(fmt->vars[i].name, "__"))
2616 continue;
2617 if (minimal && option_is_same(fmt, options, defaults, fmt->vars[i].name))
2618 continue;
2619 else if (comment_defaults &&
2620 option_is_same(fmt, options, defaults, fmt->vars[i].name))
2621 comment_option = 1;
2623 desc = config_find_description(fmt, fmt->vars[i].name);
2624 line = assigned = get_assigned_option(fmt, options, fmt->vars[i].name, 1);
2626 if (line && desc) {
2627 /* Only dump the description if there's something to describe. */
2628 wrap_string(elements, desc, 78, "# ", "# ");
2631 for (; line; line = line->next) {
2632 size_t len = strlen(line->key) + strlen(line->value) + 5;
2633 char *tmp;
2634 tmp = tor_malloc(len);
2635 if (tor_snprintf(tmp, len, "%s%s %s\n",
2636 comment_option ? "# " : "",
2637 line->key, line->value)<0) {
2638 log_err(LD_BUG,"Internal error writing option value");
2639 tor_assert(0);
2641 smartlist_add(elements, tmp);
2643 config_free_lines(assigned);
2646 if (fmt->extra) {
2647 line = *(config_line_t**)STRUCT_VAR_P(options, fmt->extra->var_offset);
2648 for (; line; line = line->next) {
2649 size_t len = strlen(line->key) + strlen(line->value) + 3;
2650 char *tmp;
2651 tmp = tor_malloc(len);
2652 if (tor_snprintf(tmp, len, "%s %s\n", line->key, line->value)<0) {
2653 log_err(LD_BUG,"Internal error writing option value");
2654 tor_assert(0);
2656 smartlist_add(elements, tmp);
2660 result = smartlist_join_strings(elements, "", 0, NULL);
2661 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
2662 smartlist_free(elements);
2663 config_free(fmt, defaults);
2664 return result;
2667 /** Return a string containing a possible configuration file that would give
2668 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
2669 * include options that are the same as Tor's defaults.
2671 static char *
2672 options_dump(or_options_t *options, int minimal)
2674 return config_dump(&options_format, options, minimal, 0);
2677 /** Return 0 if every element of sl is a string holding a decimal
2678 * representation of a port number, or if sl is NULL.
2679 * Otherwise set *msg and return -1. */
2680 static int
2681 validate_ports_csv(smartlist_t *sl, const char *name, char **msg)
2683 int i;
2684 char buf[1024];
2685 tor_assert(name);
2687 if (!sl)
2688 return 0;
2690 SMARTLIST_FOREACH(sl, const char *, cp,
2692 i = atoi(cp);
2693 if (i < 1 || i > 65535) {
2694 int r = tor_snprintf(buf, sizeof(buf),
2695 "Port '%s' out of range in %s", cp, name);
2696 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2697 return -1;
2700 return 0;
2703 /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
2704 * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
2705 * Else return 0.
2707 static int
2708 ensure_bandwidth_cap(uint64_t *value, const char *desc, char **msg)
2710 int r;
2711 char buf[1024];
2712 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2713 /* This handles an understandable special case where somebody says "2gb"
2714 * whereas our actual maximum is 2gb-1 (INT_MAX) */
2715 --*value;
2717 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2718 r = tor_snprintf(buf, sizeof(buf), "%s ("U64_FORMAT") must be at most %d",
2719 desc, U64_PRINTF_ARG(*value),
2720 ROUTER_MAX_DECLARED_BANDWIDTH);
2721 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2722 return -1;
2724 return 0;
2727 /** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
2728 * and write it to <b>options</b>-\>_PublishServerDescriptor. Treat "1"
2729 * as "v2,v3" unless BridgeRelay is 1, in which case treat it as "bridge".
2730 * Treat "0" as "".
2731 * Return 0 on success or -1 if not a recognized authority type (in which
2732 * case the value of _PublishServerDescriptor is undefined). */
2733 static int
2734 compute_publishserverdescriptor(or_options_t *options)
2736 smartlist_t *list = options->PublishServerDescriptor;
2737 authority_type_t *auth = &options->_PublishServerDescriptor;
2738 *auth = NO_AUTHORITY;
2739 if (!list) /* empty list, answer is none */
2740 return 0;
2741 SMARTLIST_FOREACH(list, const char *, string, {
2742 if (!strcasecmp(string, "v1"))
2743 *auth |= V1_AUTHORITY;
2744 else if (!strcmp(string, "1"))
2745 if (options->BridgeRelay)
2746 *auth |= BRIDGE_AUTHORITY;
2747 else
2748 *auth |= V2_AUTHORITY | V3_AUTHORITY;
2749 else if (!strcasecmp(string, "v2"))
2750 *auth |= V2_AUTHORITY;
2751 else if (!strcasecmp(string, "v3"))
2752 *auth |= V3_AUTHORITY;
2753 else if (!strcasecmp(string, "bridge"))
2754 *auth |= BRIDGE_AUTHORITY;
2755 else if (!strcasecmp(string, "hidserv"))
2756 *auth |= HIDSERV_AUTHORITY;
2757 else if (!strcasecmp(string, "") || !strcmp(string, "0"))
2758 /* no authority */;
2759 else
2760 return -1;
2762 return 0;
2765 /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
2766 * services can overload the directory system. */
2767 #define MIN_REND_POST_PERIOD (10*60)
2769 /** Highest allowable value for RendPostPeriod. */
2770 #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
2772 /** Return 0 if every setting in <b>options</b> is reasonable, and a
2773 * permissible transition from <b>old_options</b>. Else return -1.
2774 * Should have no side effects, except for normalizing the contents of
2775 * <b>options</b>.
2777 * On error, tor_strdup an error explanation into *<b>msg</b>.
2779 * XXX
2780 * If <b>from_setconf</b>, we were called by the controller, and our
2781 * Log line should stay empty. If it's 0, then give us a default log
2782 * if there are no logs defined.
2784 static int
2785 options_validate(or_options_t *old_options, or_options_t *options,
2786 int from_setconf, char **msg)
2788 int i, r;
2789 config_line_t *cl;
2790 const char *uname = get_uname();
2791 char buf[1024];
2792 #define REJECT(arg) \
2793 STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
2794 #define COMPLAIN(arg) STMT_BEGIN log(LOG_WARN, LD_CONFIG, arg); STMT_END
2796 tor_assert(msg);
2797 *msg = NULL;
2799 if (options->ORPort < 0 || options->ORPort > 65535)
2800 REJECT("ORPort option out of bounds.");
2802 if (server_mode(options) &&
2803 (!strcmpstart(uname, "Windows 95") ||
2804 !strcmpstart(uname, "Windows 98") ||
2805 !strcmpstart(uname, "Windows Me"))) {
2806 log(LOG_WARN, LD_CONFIG, "Tor is running as a server, but you are "
2807 "running %s; this probably won't work. See "
2808 "http://wiki.noreply.org/noreply/TheOnionRouter/TorFAQ#ServerOS "
2809 "for details.", uname);
2812 if (options->ORPort == 0 && options->ORListenAddress != NULL)
2813 REJECT("ORPort must be defined if ORListenAddress is defined.");
2815 if (options->DirPort == 0 && options->DirListenAddress != NULL)
2816 REJECT("DirPort must be defined if DirListenAddress is defined.");
2818 if (options->DNSPort == 0 && options->DNSListenAddress != NULL)
2819 REJECT("DNSPort must be defined if DNSListenAddress is defined.");
2821 if (options->ControlPort == 0 && options->ControlListenAddress != NULL)
2822 REJECT("ControlPort must be defined if ControlListenAddress is defined.");
2824 if (options->TransPort == 0 && options->TransListenAddress != NULL)
2825 REJECT("TransPort must be defined if TransListenAddress is defined.");
2827 if (options->NatdPort == 0 && options->NatdListenAddress != NULL)
2828 REJECT("NatdPort must be defined if NatdListenAddress is defined.");
2830 /* Don't gripe about SocksPort 0 with SocksListenAddress set; a standard
2831 * configuration does this. */
2833 for (i = 0; i < 3; ++i) {
2834 int is_socks = i==0;
2835 int is_trans = i==1;
2836 config_line_t *line, *opt, *old;
2837 const char *tp;
2838 if (is_socks) {
2839 opt = options->SocksListenAddress;
2840 old = old_options ? old_options->SocksListenAddress : NULL;
2841 tp = "SOCKS proxy";
2842 } else if (is_trans) {
2843 opt = options->TransListenAddress;
2844 old = old_options ? old_options->TransListenAddress : NULL;
2845 tp = "transparent proxy";
2846 } else {
2847 opt = options->NatdListenAddress;
2848 old = old_options ? old_options->NatdListenAddress : NULL;
2849 tp = "natd proxy";
2852 for (line = opt; line; line = line->next) {
2853 char *address = NULL;
2854 uint16_t port;
2855 uint32_t addr;
2856 if (parse_addr_port(LOG_WARN, line->value, &address, &addr, &port)<0)
2857 continue; /* We'll warn about this later. */
2858 if (!is_internal_IP(addr, 1) &&
2859 (!old_options || !config_lines_eq(old, opt))) {
2860 log_warn(LD_CONFIG,
2861 "You specified a public address '%s' for a %s. Other "
2862 "people on the Internet might find your computer and use it as "
2863 "an open %s. Please don't allow this unless you have "
2864 "a good reason.", address, tp, tp);
2866 tor_free(address);
2870 if (validate_data_directory(options)<0)
2871 REJECT("Invalid DataDirectory");
2873 if (options->Nickname == NULL) {
2874 if (server_mode(options)) {
2875 if (!(options->Nickname = get_default_nickname())) {
2876 log_notice(LD_CONFIG, "Couldn't pick a nickname based on "
2877 "our hostname; using %s instead.", UNNAMED_ROUTER_NICKNAME);
2878 options->Nickname = tor_strdup(UNNAMED_ROUTER_NICKNAME);
2879 } else {
2880 log_notice(LD_CONFIG, "Choosing default nickname '%s'",
2881 options->Nickname);
2884 } else {
2885 if (!is_legal_nickname(options->Nickname)) {
2886 r = tor_snprintf(buf, sizeof(buf),
2887 "Nickname '%s' is wrong length or contains illegal characters.",
2888 options->Nickname);
2889 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2890 return -1;
2894 if (server_mode(options) && !options->ContactInfo)
2895 log(LOG_NOTICE, LD_CONFIG, "Your ContactInfo config option is not set. "
2896 "Please consider setting it, so we can contact you if your server is "
2897 "misconfigured or something else goes wrong.");
2899 /* Special case on first boot if no Log options are given. */
2900 if (!options->Logs && !options->RunAsDaemon && !from_setconf)
2901 config_line_append(&options->Logs, "Log", "notice stdout");
2903 if (options_init_logs(options, 1)<0) /* Validate the log(s) */
2904 REJECT("Failed to validate Log options. See logs for details.");
2906 if (options->NoPublish) {
2907 log(LOG_WARN, LD_CONFIG,
2908 "NoPublish is obsolete. Use PublishServerDescriptor instead.");
2909 SMARTLIST_FOREACH(options->PublishServerDescriptor, char *, s,
2910 tor_free(s));
2911 smartlist_clear(options->PublishServerDescriptor);
2914 if (authdir_mode(options)) {
2915 /* confirm that our address isn't broken, so we can complain now */
2916 uint32_t tmp;
2917 if (resolve_my_address(LOG_WARN, options, &tmp, NULL) < 0)
2918 REJECT("Failed to resolve/guess local address. See logs for details.");
2921 #ifndef MS_WINDOWS
2922 if (options->RunAsDaemon && torrc_fname && path_is_relative(torrc_fname))
2923 REJECT("Can't use a relative path to torrc when RunAsDaemon is set.");
2924 #endif
2926 if (options->SocksPort < 0 || options->SocksPort > 65535)
2927 REJECT("SocksPort option out of bounds.");
2929 if (options->DNSPort < 0 || options->DNSPort > 65535)
2930 REJECT("DNSPort option out of bounds.");
2932 if (options->TransPort < 0 || options->TransPort > 65535)
2933 REJECT("TransPort option out of bounds.");
2935 if (options->NatdPort < 0 || options->NatdPort > 65535)
2936 REJECT("NatdPort option out of bounds.");
2938 if (options->SocksPort == 0 && options->TransPort == 0 &&
2939 options->NatdPort == 0 && options->ORPort == 0 &&
2940 options->DNSPort == 0 && !options->RendConfigLines)
2941 log(LOG_WARN, LD_CONFIG,
2942 "SocksPort, TransPort, NatdPort, DNSPort, and ORPort are all "
2943 "undefined, and there aren't any hidden services configured. "
2944 "Tor will still run, but probably won't do anything.");
2946 if (options->ControlPort < 0 || options->ControlPort > 65535)
2947 REJECT("ControlPort option out of bounds.");
2949 if (options->DirPort < 0 || options->DirPort > 65535)
2950 REJECT("DirPort option out of bounds.");
2952 #ifndef USE_TRANSPARENT
2953 if (options->TransPort || options->TransListenAddress)
2954 REJECT("TransPort and TransListenAddress are disabled in this build.");
2955 #endif
2957 if (options->ExcludeExitNodes || options->ExcludeNodes) {
2958 options->_ExcludeExitNodesUnion = routerset_new();
2959 routerset_union(options->_ExcludeExitNodesUnion,options->ExcludeExitNodes);
2960 routerset_union(options->_ExcludeExitNodesUnion,options->ExcludeNodes);
2963 if (options->StrictExitNodes &&
2964 (!options->ExitNodes || !strlen(options->ExitNodes)) &&
2965 (!old_options ||
2966 (old_options->StrictExitNodes != options->StrictExitNodes) ||
2967 (!opt_streq(old_options->ExitNodes, options->ExitNodes))))
2968 COMPLAIN("StrictExitNodes set, but no ExitNodes listed.");
2970 if (options->StrictEntryNodes &&
2971 (!options->EntryNodes || !strlen(options->EntryNodes)) &&
2972 (!old_options ||
2973 (old_options->StrictEntryNodes != options->StrictEntryNodes) ||
2974 (!opt_streq(old_options->EntryNodes, options->EntryNodes))))
2975 COMPLAIN("StrictEntryNodes set, but no EntryNodes listed.");
2977 if (options->AuthoritativeDir) {
2978 if (!options->ContactInfo)
2979 REJECT("Authoritative directory servers must set ContactInfo");
2980 if (options->V1AuthoritativeDir && !options->RecommendedVersions)
2981 REJECT("V1 auth dir servers must set RecommendedVersions.");
2982 if (!options->RecommendedClientVersions)
2983 options->RecommendedClientVersions =
2984 config_lines_dup(options->RecommendedVersions);
2985 if (!options->RecommendedServerVersions)
2986 options->RecommendedServerVersions =
2987 config_lines_dup(options->RecommendedVersions);
2988 if (options->VersioningAuthoritativeDir &&
2989 (!options->RecommendedClientVersions ||
2990 !options->RecommendedServerVersions))
2991 REJECT("Versioning auth dir servers must set Recommended*Versions.");
2992 if (options->UseEntryGuards) {
2993 log_info(LD_CONFIG, "Authoritative directory servers can't set "
2994 "UseEntryGuards. Disabling.");
2995 options->UseEntryGuards = 0;
2997 if (!options->DownloadExtraInfo && authdir_mode_any_main(options)) {
2998 log_info(LD_CONFIG, "Authoritative directories always try to download "
2999 "extra-info documents. Setting DownloadExtraInfo.");
3000 options->DownloadExtraInfo = 1;
3002 if (!(options->BridgeAuthoritativeDir || options->HSAuthoritativeDir ||
3003 options->V1AuthoritativeDir || options->V2AuthoritativeDir ||
3004 options->V3AuthoritativeDir))
3005 REJECT("AuthoritativeDir is set, but none of "
3006 "(Bridge/HS/V1/V2/V3)AuthoritativeDir is set.");
3009 if (options->AuthoritativeDir && !options->DirPort)
3010 REJECT("Running as authoritative directory, but no DirPort set.");
3012 if (options->AuthoritativeDir && !options->ORPort)
3013 REJECT("Running as authoritative directory, but no ORPort set.");
3015 if (options->AuthoritativeDir && options->ClientOnly)
3016 REJECT("Running as authoritative directory, but ClientOnly also set.");
3018 if (options->HSAuthorityRecordStats && !options->HSAuthoritativeDir)
3019 REJECT("HSAuthorityRecordStats is set but we're not running as "
3020 "a hidden service authority.");
3022 if (options->HidServDirectoryV2 && !options->DirPort)
3023 REJECT("Running as hidden service directory, but no DirPort set.");
3025 if (options->ConnLimit <= 0) {
3026 r = tor_snprintf(buf, sizeof(buf),
3027 "ConnLimit must be greater than 0, but was set to %d",
3028 options->ConnLimit);
3029 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3030 return -1;
3033 if (validate_ports_csv(options->FirewallPorts, "FirewallPorts", msg) < 0)
3034 return -1;
3036 if (validate_ports_csv(options->LongLivedPorts, "LongLivedPorts", msg) < 0)
3037 return -1;
3039 if (validate_ports_csv(options->RejectPlaintextPorts,
3040 "RejectPlaintextPorts", msg) < 0)
3041 return -1;
3043 if (validate_ports_csv(options->WarnPlaintextPorts,
3044 "WarnPlaintextPorts", msg) < 0)
3045 return -1;
3047 if (options->FascistFirewall && !options->ReachableAddresses) {
3048 if (options->FirewallPorts && smartlist_len(options->FirewallPorts)) {
3049 /* We already have firewall ports set, so migrate them to
3050 * ReachableAddresses, which will set ReachableORAddresses and
3051 * ReachableDirAddresses if they aren't set explicitly. */
3052 smartlist_t *instead = smartlist_create();
3053 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3054 new_line->key = tor_strdup("ReachableAddresses");
3055 /* If we're configured with the old format, we need to prepend some
3056 * open ports. */
3057 SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
3059 int p = atoi(portno);
3060 char *s;
3061 if (p<0) continue;
3062 s = tor_malloc(16);
3063 tor_snprintf(s, 16, "*:%d", p);
3064 smartlist_add(instead, s);
3066 new_line->value = smartlist_join_strings(instead,",",0,NULL);
3067 /* These have been deprecated since 0.1.1.5-alpha-cvs */
3068 log(LOG_NOTICE, LD_CONFIG,
3069 "Converting FascistFirewall and FirewallPorts "
3070 "config options to new format: \"ReachableAddresses %s\"",
3071 new_line->value);
3072 options->ReachableAddresses = new_line;
3073 SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
3074 smartlist_free(instead);
3075 } else {
3076 /* We do not have FirewallPorts set, so add 80 to
3077 * ReachableDirAddresses, and 443 to ReachableORAddresses. */
3078 if (!options->ReachableDirAddresses) {
3079 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3080 new_line->key = tor_strdup("ReachableDirAddresses");
3081 new_line->value = tor_strdup("*:80");
3082 options->ReachableDirAddresses = new_line;
3083 log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
3084 "to new format: \"ReachableDirAddresses *:80\"");
3086 if (!options->ReachableORAddresses) {
3087 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3088 new_line->key = tor_strdup("ReachableORAddresses");
3089 new_line->value = tor_strdup("*:443");
3090 options->ReachableORAddresses = new_line;
3091 log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
3092 "to new format: \"ReachableORAddresses *:443\"");
3097 for (i=0; i<3; i++) {
3098 config_line_t **linep =
3099 (i==0) ? &options->ReachableAddresses :
3100 (i==1) ? &options->ReachableORAddresses :
3101 &options->ReachableDirAddresses;
3102 if (!*linep)
3103 continue;
3104 /* We need to end with a reject *:*, not an implicit accept *:* */
3105 for (;;) {
3106 if (!strcmp((*linep)->value, "reject *:*")) /* already there */
3107 break;
3108 linep = &((*linep)->next);
3109 if (!*linep) {
3110 *linep = tor_malloc_zero(sizeof(config_line_t));
3111 (*linep)->key = tor_strdup(
3112 (i==0) ? "ReachableAddresses" :
3113 (i==1) ? "ReachableORAddresses" :
3114 "ReachableDirAddresses");
3115 (*linep)->value = tor_strdup("reject *:*");
3116 break;
3121 if ((options->ReachableAddresses ||
3122 options->ReachableORAddresses ||
3123 options->ReachableDirAddresses) &&
3124 server_mode(options))
3125 REJECT("Servers must be able to freely connect to the rest "
3126 "of the Internet, so they must not set Reachable*Addresses "
3127 "or FascistFirewall.");
3129 if (options->UseBridges &&
3130 server_mode(options))
3131 REJECT("Servers must be able to freely connect to the rest "
3132 "of the Internet, so they must not set UseBridges.");
3134 options->_AllowInvalid = 0;
3135 if (options->AllowInvalidNodes) {
3136 SMARTLIST_FOREACH(options->AllowInvalidNodes, const char *, cp, {
3137 if (!strcasecmp(cp, "entry"))
3138 options->_AllowInvalid |= ALLOW_INVALID_ENTRY;
3139 else if (!strcasecmp(cp, "exit"))
3140 options->_AllowInvalid |= ALLOW_INVALID_EXIT;
3141 else if (!strcasecmp(cp, "middle"))
3142 options->_AllowInvalid |= ALLOW_INVALID_MIDDLE;
3143 else if (!strcasecmp(cp, "introduction"))
3144 options->_AllowInvalid |= ALLOW_INVALID_INTRODUCTION;
3145 else if (!strcasecmp(cp, "rendezvous"))
3146 options->_AllowInvalid |= ALLOW_INVALID_RENDEZVOUS;
3147 else {
3148 r = tor_snprintf(buf, sizeof(buf),
3149 "Unrecognized value '%s' in AllowInvalidNodes", cp);
3150 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3151 return -1;
3156 if (compute_publishserverdescriptor(options) < 0) {
3157 r = tor_snprintf(buf, sizeof(buf),
3158 "Unrecognized value in PublishServerDescriptor");
3159 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3160 return -1;
3163 if (options->MinUptimeHidServDirectoryV2 < 0) {
3164 log_warn(LD_CONFIG, "MinUptimeHidServDirectoryV2 option must be at "
3165 "least 0 seconds. Changing to 0.");
3166 options->MinUptimeHidServDirectoryV2 = 0;
3169 if (options->RendPostPeriod < MIN_REND_POST_PERIOD) {
3170 log(LOG_WARN,LD_CONFIG,"RendPostPeriod option must be at least %d seconds."
3171 " Clipping.", MIN_REND_POST_PERIOD);
3172 options->RendPostPeriod = MIN_REND_POST_PERIOD;
3175 if (options->RendPostPeriod > MAX_DIR_PERIOD) {
3176 log(LOG_WARN, LD_CONFIG, "RendPostPeriod is too large; clipping to %ds.",
3177 MAX_DIR_PERIOD);
3178 options->RendPostPeriod = MAX_DIR_PERIOD;
3181 if (options->KeepalivePeriod < 1)
3182 REJECT("KeepalivePeriod option must be positive.");
3184 if (ensure_bandwidth_cap(&options->BandwidthRate,
3185 "BandwidthRate", msg) < 0)
3186 return -1;
3187 if (ensure_bandwidth_cap(&options->BandwidthBurst,
3188 "BandwidthBurst", msg) < 0)
3189 return -1;
3190 if (ensure_bandwidth_cap(&options->MaxAdvertisedBandwidth,
3191 "MaxAdvertisedBandwidth", msg) < 0)
3192 return -1;
3193 if (ensure_bandwidth_cap(&options->RelayBandwidthRate,
3194 "RelayBandwidthRate", msg) < 0)
3195 return -1;
3196 if (ensure_bandwidth_cap(&options->RelayBandwidthBurst,
3197 "RelayBandwidthBurst", msg) < 0)
3198 return -1;
3200 if (server_mode(options)) {
3201 if (options->BandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH*2) {
3202 r = tor_snprintf(buf, sizeof(buf),
3203 "BandwidthRate is set to %d bytes/second. "
3204 "For servers, it must be at least %d.",
3205 (int)options->BandwidthRate,
3206 ROUTER_REQUIRED_MIN_BANDWIDTH*2);
3207 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3208 return -1;
3209 } else if (options->MaxAdvertisedBandwidth <
3210 ROUTER_REQUIRED_MIN_BANDWIDTH) {
3211 r = tor_snprintf(buf, sizeof(buf),
3212 "MaxAdvertisedBandwidth is set to %d bytes/second. "
3213 "For servers, it must be at least %d.",
3214 (int)options->MaxAdvertisedBandwidth,
3215 ROUTER_REQUIRED_MIN_BANDWIDTH);
3216 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3217 return -1;
3219 if (options->RelayBandwidthRate &&
3220 options->RelayBandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
3221 r = tor_snprintf(buf, sizeof(buf),
3222 "RelayBandwidthRate is set to %d bytes/second. "
3223 "For servers, it must be at least %d.",
3224 (int)options->RelayBandwidthRate,
3225 ROUTER_REQUIRED_MIN_BANDWIDTH);
3226 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3227 return -1;
3231 if (options->RelayBandwidthRate && !options->RelayBandwidthBurst)
3232 options->RelayBandwidthBurst = options->RelayBandwidthRate;
3234 if (options->RelayBandwidthRate > options->RelayBandwidthBurst)
3235 REJECT("RelayBandwidthBurst must be at least equal "
3236 "to RelayBandwidthRate.");
3238 if (options->BandwidthRate > options->BandwidthBurst)
3239 REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
3241 /* if they set relaybandwidth* really high but left bandwidth*
3242 * at the default, raise the defaults. */
3243 if (options->RelayBandwidthRate > options->BandwidthRate)
3244 options->BandwidthRate = options->RelayBandwidthRate;
3245 if (options->RelayBandwidthBurst > options->BandwidthBurst)
3246 options->BandwidthBurst = options->RelayBandwidthBurst;
3248 if (accounting_parse_options(options, 1)<0)
3249 REJECT("Failed to parse accounting options. See logs for details.");
3251 if (options->HttpProxy) { /* parse it now */
3252 if (parse_addr_port(LOG_WARN, options->HttpProxy, NULL,
3253 &options->HttpProxyAddr, &options->HttpProxyPort) < 0)
3254 REJECT("HttpProxy failed to parse or resolve. Please fix.");
3255 if (options->HttpProxyPort == 0) { /* give it a default */
3256 options->HttpProxyPort = 80;
3260 if (options->HttpProxyAuthenticator) {
3261 if (strlen(options->HttpProxyAuthenticator) >= 48)
3262 REJECT("HttpProxyAuthenticator is too long (>= 48 chars).");
3265 if (options->HttpsProxy) { /* parse it now */
3266 if (parse_addr_port(LOG_WARN, options->HttpsProxy, NULL,
3267 &options->HttpsProxyAddr, &options->HttpsProxyPort) <0)
3268 REJECT("HttpsProxy failed to parse or resolve. Please fix.");
3269 if (options->HttpsProxyPort == 0) { /* give it a default */
3270 options->HttpsProxyPort = 443;
3274 if (options->HttpsProxyAuthenticator) {
3275 if (strlen(options->HttpsProxyAuthenticator) >= 48)
3276 REJECT("HttpsProxyAuthenticator is too long (>= 48 chars).");
3279 if (options->HashedControlPassword) {
3280 smartlist_t *sl = decode_hashed_passwords(options->HashedControlPassword);
3281 if (!sl) {
3282 REJECT("Bad HashedControlPassword: wrong length or bad encoding");
3283 } else {
3284 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3285 smartlist_free(sl);
3289 if (options->HashedControlSessionPassword) {
3290 smartlist_t *sl = decode_hashed_passwords(
3291 options->HashedControlSessionPassword);
3292 if (!sl) {
3293 REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
3294 } else {
3295 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3296 smartlist_free(sl);
3300 if (options->ControlListenAddress) {
3301 int all_are_local = 1;
3302 config_line_t *ln;
3303 for (ln = options->ControlListenAddress; ln; ln = ln->next) {
3304 if (strcmpstart(ln->value, "127."))
3305 all_are_local = 0;
3307 if (!all_are_local) {
3308 if (!options->HashedControlPassword &&
3309 !options->HashedControlSessionPassword &&
3310 !options->CookieAuthentication) {
3311 log_warn(LD_CONFIG, "You have a ControlListenAddress set to accept "
3312 "connections from a non-local address. This means that "
3313 "any program on the internet can reconfigure your Tor. "
3314 "That's so bad that I'm closing your ControlPort for you.");
3315 options->ControlPort = 0;
3316 } else {
3317 log_warn(LD_CONFIG, "You have a ControlListenAddress set to accept "
3318 "connections from a non-local address. This means that "
3319 "programs not running on your computer can reconfigure your "
3320 "Tor. That's pretty bad!");
3325 if (options->ControlPort && !options->HashedControlPassword &&
3326 !options->HashedControlSessionPassword &&
3327 !options->CookieAuthentication) {
3328 log_warn(LD_CONFIG, "ControlPort is open, but no authentication method "
3329 "has been configured. This means that any program on your "
3330 "computer can reconfigure your Tor. That's bad! You should "
3331 "upgrade your Tor controller as soon as possible.");
3334 if (options->UseEntryGuards && ! options->NumEntryGuards)
3335 REJECT("Cannot enable UseEntryGuards with NumEntryGuards set to 0");
3337 if (check_nickname_list(options->ExitNodes, "ExitNodes", msg))
3338 return -1;
3339 if (check_nickname_list(options->EntryNodes, "EntryNodes", msg))
3340 return -1;
3341 if (check_nickname_list(options->MyFamily, "MyFamily", msg))
3342 return -1;
3343 for (cl = options->NodeFamilies; cl; cl = cl->next) {
3344 if (check_nickname_list(cl->value, "NodeFamily", msg))
3345 return -1;
3348 if (validate_addr_policies(options, msg) < 0)
3349 return -1;
3351 for (cl = options->RedirectExit; cl; cl = cl->next) {
3352 if (parse_redirect_line(NULL, cl, msg)<0)
3353 return -1;
3356 if (validate_dir_authorities(options, old_options) < 0)
3357 REJECT("Directory authority line did not parse. See logs for details.");
3359 if (options->UseBridges && !options->Bridges)
3360 REJECT("If you set UseBridges, you must specify at least one bridge.");
3361 if (options->UseBridges && !options->TunnelDirConns)
3362 REJECT("If you set UseBridges, you must set TunnelDirConns.");
3363 if (options->Bridges) {
3364 for (cl = options->Bridges; cl; cl = cl->next) {
3365 if (parse_bridge_line(cl->value, 1)<0)
3366 REJECT("Bridge line did not parse. See logs for details.");
3370 if (options->ConstrainedSockets) {
3371 /* If the user wants to constrain socket buffer use, make sure the desired
3372 * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
3373 if (options->ConstrainedSockSize < MIN_CONSTRAINED_TCP_BUFFER ||
3374 options->ConstrainedSockSize > MAX_CONSTRAINED_TCP_BUFFER ||
3375 options->ConstrainedSockSize % 1024) {
3376 r = tor_snprintf(buf, sizeof(buf),
3377 "ConstrainedSockSize is invalid. Must be a value between %d and %d "
3378 "in 1024 byte increments.",
3379 MIN_CONSTRAINED_TCP_BUFFER, MAX_CONSTRAINED_TCP_BUFFER);
3380 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3381 return -1;
3383 if (options->DirPort) {
3384 /* Providing cached directory entries while system TCP buffers are scarce
3385 * will exacerbate the socket errors. Suggest that this be disabled. */
3386 COMPLAIN("You have requested constrained socket buffers while also "
3387 "serving directory entries via DirPort. It is strongly "
3388 "suggested that you disable serving directory requests when "
3389 "system TCP buffer resources are scarce.");
3393 if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
3394 options->V3AuthVotingInterval/2) {
3395 REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
3396 "V3AuthVotingInterval");
3398 if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS)
3399 REJECT("V3AuthVoteDelay is way too low.");
3400 if (options->V3AuthDistDelay < MIN_DIST_SECONDS)
3401 REJECT("V3AuthDistDelay is way too low.");
3403 if (options->V3AuthNIntervalsValid < 2)
3404 REJECT("V3AuthNIntervalsValid must be at least 2.");
3406 if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL) {
3407 REJECT("V3AuthVotingInterval is insanely low.");
3408 } else if (options->V3AuthVotingInterval > 24*60*60) {
3409 REJECT("V3AuthVotingInterval is insanely high.");
3410 } else if (((24*60*60) % options->V3AuthVotingInterval) != 0) {
3411 COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
3414 if (rend_config_services(options, 1) < 0)
3415 REJECT("Failed to configure rendezvous options. See logs for details.");
3417 /* Parse client-side authorization for hidden services. */
3418 if (rend_parse_service_authorization(options, 1) < 0)
3419 REJECT("Failed to configure client authorization for hidden services. "
3420 "See logs for details.");
3422 if (parse_virtual_addr_network(options->VirtualAddrNetwork, 1, NULL)<0)
3423 return -1;
3425 if (options->PreferTunneledDirConns && !options->TunnelDirConns)
3426 REJECT("Must set TunnelDirConns if PreferTunneledDirConns is set.");
3428 if (options->AutomapHostsSuffixes) {
3429 SMARTLIST_FOREACH(options->AutomapHostsSuffixes, char *, suf,
3431 size_t len = strlen(suf);
3432 if (len && suf[len-1] == '.')
3433 suf[len-1] = '\0';
3437 if (options->TestingTorNetwork && !options->DirServers) {
3438 REJECT("TestingTorNetwork may only be configured in combination with "
3439 "a non-default set of DirServers.");
3442 /*XXXX021 checking for defaults manually like this is a bit fragile.*/
3444 /* Keep changes to hard-coded values synchronous to man page and default
3445 * values table. */
3446 if (options->TestingV3AuthInitialVotingInterval != 30*60 &&
3447 !options->TestingTorNetwork) {
3448 REJECT("TestingV3AuthInitialVotingInterval may only be changed in testing "
3449 "Tor networks!");
3450 } else if (options->TestingV3AuthInitialVotingInterval < MIN_VOTE_INTERVAL) {
3451 REJECT("TestingV3AuthInitialVotingInterval is insanely low.");
3452 } else if (((30*60) % options->TestingV3AuthInitialVotingInterval) != 0) {
3453 REJECT("TestingV3AuthInitialVotingInterval does not divide evenly into "
3454 "30 minutes.");
3457 if (options->TestingV3AuthInitialVoteDelay != 5*60 &&
3458 !options->TestingTorNetwork) {
3459 REJECT("TestingV3AuthInitialVoteDelay may only be changed in testing "
3460 "Tor networks!");
3461 } else if (options->TestingV3AuthInitialVoteDelay < MIN_VOTE_SECONDS) {
3462 REJECT("TestingV3AuthInitialVoteDelay is way too low.");
3465 if (options->TestingV3AuthInitialDistDelay != 5*60 &&
3466 !options->TestingTorNetwork) {
3467 REJECT("TestingV3AuthInitialDistDelay may only be changed in testing "
3468 "Tor networks!");
3469 } else if (options->TestingV3AuthInitialDistDelay < MIN_DIST_SECONDS) {
3470 REJECT("TestingV3AuthInitialDistDelay is way too low.");
3473 if (options->TestingV3AuthInitialVoteDelay +
3474 options->TestingV3AuthInitialDistDelay >=
3475 options->TestingV3AuthInitialVotingInterval/2) {
3476 REJECT("TestingV3AuthInitialVoteDelay plus TestingV3AuthInitialDistDelay "
3477 "must be less than half TestingV3AuthInitialVotingInterval");
3480 if (options->TestingAuthDirTimeToLearnReachability != 30*60 &&
3481 !options->TestingTorNetwork) {
3482 REJECT("TestingAuthDirTimeToLearnReachability may only be changed in "
3483 "testing Tor networks!");
3484 } else if (options->TestingAuthDirTimeToLearnReachability < 0) {
3485 REJECT("TestingAuthDirTimeToLearnReachability must be non-negative.");
3486 } else if (options->TestingAuthDirTimeToLearnReachability > 2*60*60) {
3487 COMPLAIN("TestingAuthDirTimeToLearnReachability is insanely high.");
3490 if (options->TestingEstimatedDescriptorPropagationTime != 10*60 &&
3491 !options->TestingTorNetwork) {
3492 REJECT("TestingEstimatedDescriptorPropagationTime may only be changed in "
3493 "testing Tor networks!");
3494 } else if (options->TestingEstimatedDescriptorPropagationTime < 0) {
3495 REJECT("TestingEstimatedDescriptorPropagationTime must be non-negative.");
3496 } else if (options->TestingEstimatedDescriptorPropagationTime > 60*60) {
3497 COMPLAIN("TestingEstimatedDescriptorPropagationTime is insanely high.");
3500 if (options->TestingTorNetwork) {
3501 log_warn(LD_CONFIG, "TestingTorNetwork is set. This will make your node "
3502 "almost unusable in the public Tor network, and is "
3503 "therefore only advised if you are building a "
3504 "testing Tor network!");
3507 return 0;
3508 #undef REJECT
3509 #undef COMPLAIN
3512 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
3513 * equal strings. */
3514 static int
3515 opt_streq(const char *s1, const char *s2)
3517 if (!s1 && !s2)
3518 return 1;
3519 else if (s1 && s2 && !strcmp(s1,s2))
3520 return 1;
3521 else
3522 return 0;
3525 /** Check if any of the previous options have changed but aren't allowed to. */
3526 static int
3527 options_transition_allowed(or_options_t *old, or_options_t *new_val,
3528 char **msg)
3530 if (!old)
3531 return 0;
3533 if (!opt_streq(old->PidFile, new_val->PidFile)) {
3534 *msg = tor_strdup("PidFile is not allowed to change.");
3535 return -1;
3538 if (old->RunAsDaemon != new_val->RunAsDaemon) {
3539 *msg = tor_strdup("While Tor is running, changing RunAsDaemon "
3540 "is not allowed.");
3541 return -1;
3544 if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
3545 char buf[1024];
3546 int r = tor_snprintf(buf, sizeof(buf),
3547 "While Tor is running, changing DataDirectory "
3548 "(\"%s\"->\"%s\") is not allowed.",
3549 old->DataDirectory, new_val->DataDirectory);
3550 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3551 return -1;
3554 if (!opt_streq(old->User, new_val->User)) {
3555 *msg = tor_strdup("While Tor is running, changing User is not allowed.");
3556 return -1;
3559 if (!opt_streq(old->Group, new_val->Group)) {
3560 *msg = tor_strdup("While Tor is running, changing Group is not allowed.");
3561 return -1;
3564 if (old->HardwareAccel != new_val->HardwareAccel) {
3565 *msg = tor_strdup("While Tor is running, changing HardwareAccel is "
3566 "not allowed.");
3567 return -1;
3570 if (old->TestingTorNetwork != new_val->TestingTorNetwork) {
3571 *msg = tor_strdup("While Tor is running, changing TestingTorNetwork "
3572 "is not allowed.");
3573 return -1;
3576 return 0;
3579 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3580 * will require us to rotate the cpu and dns workers; else return 0. */
3581 static int
3582 options_transition_affects_workers(or_options_t *old_options,
3583 or_options_t *new_options)
3585 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
3586 old_options->NumCpus != new_options->NumCpus ||
3587 old_options->ORPort != new_options->ORPort ||
3588 old_options->ServerDNSSearchDomains !=
3589 new_options->ServerDNSSearchDomains ||
3590 old_options->SafeLogging != new_options->SafeLogging ||
3591 old_options->ClientOnly != new_options->ClientOnly ||
3592 !config_lines_eq(old_options->Logs, new_options->Logs))
3593 return 1;
3595 /* Check whether log options match. */
3597 /* Nothing that changed matters. */
3598 return 0;
3601 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3602 * will require us to generate a new descriptor; else return 0. */
3603 static int
3604 options_transition_affects_descriptor(or_options_t *old_options,
3605 or_options_t *new_options)
3607 /* XXX021 We can be smarter here. If your DirPort isn't being
3608 * published and you just turned it off, no need to republish. If
3609 * you changed your bandwidthrate but maxadvertisedbandwidth still
3610 * trumps, no need to republish. Etc. */
3611 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
3612 !opt_streq(old_options->Nickname,new_options->Nickname) ||
3613 !opt_streq(old_options->Address,new_options->Address) ||
3614 !config_lines_eq(old_options->ExitPolicy,new_options->ExitPolicy) ||
3615 old_options->ExitPolicyRejectPrivate !=
3616 new_options->ExitPolicyRejectPrivate ||
3617 old_options->ORPort != new_options->ORPort ||
3618 old_options->DirPort != new_options->DirPort ||
3619 old_options->ClientOnly != new_options->ClientOnly ||
3620 old_options->NoPublish != new_options->NoPublish ||
3621 old_options->_PublishServerDescriptor !=
3622 new_options->_PublishServerDescriptor ||
3623 old_options->BandwidthRate != new_options->BandwidthRate ||
3624 old_options->BandwidthBurst != new_options->BandwidthBurst ||
3625 old_options->MaxAdvertisedBandwidth !=
3626 new_options->MaxAdvertisedBandwidth ||
3627 !opt_streq(old_options->ContactInfo, new_options->ContactInfo) ||
3628 !opt_streq(old_options->MyFamily, new_options->MyFamily) ||
3629 !opt_streq(old_options->AccountingStart, new_options->AccountingStart) ||
3630 old_options->AccountingMax != new_options->AccountingMax)
3631 return 1;
3633 return 0;
3636 #ifdef MS_WINDOWS
3637 /** Return the directory on windows where we expect to find our application
3638 * data. */
3639 static char *
3640 get_windows_conf_root(void)
3642 static int is_set = 0;
3643 static char path[MAX_PATH+1];
3645 LPITEMIDLIST idl;
3646 IMalloc *m;
3647 HRESULT result;
3649 if (is_set)
3650 return path;
3652 /* Find X:\documents and settings\username\application data\ .
3653 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
3655 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, CSIDL_APPDATA,
3656 &idl))) {
3657 GetCurrentDirectory(MAX_PATH, path);
3658 is_set = 1;
3659 log_warn(LD_CONFIG,
3660 "I couldn't find your application data folder: are you "
3661 "running an ancient version of Windows 95? Defaulting to \"%s\"",
3662 path);
3663 return path;
3665 /* Convert the path from an "ID List" (whatever that is!) to a path. */
3666 result = SHGetPathFromIDList(idl, path);
3667 /* Now we need to free the */
3668 SHGetMalloc(&m);
3669 if (m) {
3670 m->lpVtbl->Free(m, idl);
3671 m->lpVtbl->Release(m);
3673 if (!SUCCEEDED(result)) {
3674 return NULL;
3676 strlcat(path,"\\tor",MAX_PATH);
3677 is_set = 1;
3678 return path;
3680 #endif
3682 /** Return the default location for our torrc file. */
3683 static const char *
3684 get_default_conf_file(void)
3686 #ifdef MS_WINDOWS
3687 static char path[MAX_PATH+1];
3688 strlcpy(path, get_windows_conf_root(), MAX_PATH);
3689 strlcat(path,"\\torrc",MAX_PATH);
3690 return path;
3691 #else
3692 return (CONFDIR "/torrc");
3693 #endif
3696 /** Verify whether lst is a string containing valid-looking space-separated
3697 * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
3699 static int
3700 check_nickname_list(const char *lst, const char *name, char **msg)
3702 int r = 0;
3703 smartlist_t *sl;
3705 if (!lst)
3706 return 0;
3707 sl = smartlist_create();
3708 smartlist_split_string(sl, lst, ",", SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
3709 SMARTLIST_FOREACH(sl, const char *, s,
3711 if (!is_legal_nickname_or_hexdigest(s)) {
3712 char buf[1024];
3713 int tmp = tor_snprintf(buf, sizeof(buf),
3714 "Invalid nickname '%s' in %s line", s, name);
3715 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
3716 r = -1;
3717 break;
3720 SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
3721 smartlist_free(sl);
3722 return r;
3725 /** Learn config file name from command line arguments, or use the default */
3726 static char *
3727 find_torrc_filename(int argc, char **argv,
3728 int *using_default_torrc, int *ignore_missing_torrc)
3730 char *fname=NULL;
3731 int i;
3733 for (i = 1; i < argc; ++i) {
3734 if (i < argc-1 && !strcmp(argv[i],"-f")) {
3735 if (fname) {
3736 log(LOG_WARN, LD_CONFIG, "Duplicate -f options on command line.");
3737 tor_free(fname);
3739 #ifdef MS_WINDOWS
3740 /* XXX one day we might want to extend expand_filename to work
3741 * under Windows as well. */
3742 fname = tor_strdup(argv[i+1]);
3743 #else
3744 fname = expand_filename(argv[i+1]);
3745 #endif
3746 *using_default_torrc = 0;
3747 ++i;
3748 } else if (!strcmp(argv[i],"--ignore-missing-torrc")) {
3749 *ignore_missing_torrc = 1;
3753 if (*using_default_torrc) {
3754 /* didn't find one, try CONFDIR */
3755 const char *dflt = get_default_conf_file();
3756 if (dflt && file_status(dflt) == FN_FILE) {
3757 fname = tor_strdup(dflt);
3758 } else {
3759 #ifndef MS_WINDOWS
3760 char *fn;
3761 fn = expand_filename("~/.torrc");
3762 if (fn && file_status(fn) == FN_FILE) {
3763 fname = fn;
3764 } else {
3765 tor_free(fn);
3766 fname = tor_strdup(dflt);
3768 #else
3769 fname = tor_strdup(dflt);
3770 #endif
3773 return fname;
3776 /** Load torrc from disk, setting torrc_fname if successful */
3777 static char *
3778 load_torrc_from_disk(int argc, char **argv)
3780 char *fname=NULL;
3781 char *cf = NULL;
3782 int using_default_torrc = 1;
3783 int ignore_missing_torrc = 0;
3785 fname = find_torrc_filename(argc, argv,
3786 &using_default_torrc, &ignore_missing_torrc);
3787 tor_assert(fname);
3788 log(LOG_DEBUG, LD_CONFIG, "Opening config file \"%s\"", fname);
3790 tor_free(torrc_fname);
3791 torrc_fname = fname;
3793 /* Open config file */
3794 if (file_status(fname) != FN_FILE ||
3795 !(cf = read_file_to_str(fname,0,NULL))) {
3796 if (using_default_torrc == 1 || ignore_missing_torrc ) {
3797 log(LOG_NOTICE, LD_CONFIG, "Configuration file \"%s\" not present, "
3798 "using reasonable defaults.", fname);
3799 tor_free(fname); /* sets fname to NULL */
3800 torrc_fname = NULL;
3801 cf = tor_strdup("");
3802 } else {
3803 log(LOG_WARN, LD_CONFIG,
3804 "Unable to open configuration file \"%s\".", fname);
3805 goto err;
3809 return cf;
3810 err:
3811 tor_free(fname);
3812 torrc_fname = NULL;
3813 return NULL;
3816 /** Read a configuration file into <b>options</b>, finding the configuration
3817 * file location based on the command line. After loading the file
3818 * call options_init_from_string() to load the config.
3819 * Return 0 if success, -1 if failure. */
3821 options_init_from_torrc(int argc, char **argv)
3823 char *cf=NULL;
3824 int i, retval, command;
3825 static char **backup_argv;
3826 static int backup_argc;
3827 char *command_arg = NULL;
3828 char *errmsg=NULL;
3830 if (argv) { /* first time we're called. save commandline args */
3831 backup_argv = argv;
3832 backup_argc = argc;
3833 } else { /* we're reloading. need to clean up old options first. */
3834 argv = backup_argv;
3835 argc = backup_argc;
3837 if (argc > 1 && (!strcmp(argv[1], "-h") || !strcmp(argv[1],"--help"))) {
3838 print_usage();
3839 exit(0);
3841 if (argc > 1 && !strcmp(argv[1], "--list-torrc-options")) {
3842 /* For documenting validating whether we've documented everything. */
3843 list_torrc_options();
3844 exit(0);
3847 if (argc > 1 && (!strcmp(argv[1],"--version"))) {
3848 printf("Tor version %s.\n",get_version());
3849 if (argc > 2 && (!strcmp(argv[2],"--version"))) {
3850 print_svn_version();
3852 exit(0);
3855 /* Go through command-line variables */
3856 if (!global_cmdline_options) {
3857 /* Or we could redo the list every time we pass this place.
3858 * It does not really matter */
3859 if (config_get_commandlines(argc, argv, &global_cmdline_options) < 0) {
3860 goto err;
3864 command = CMD_RUN_TOR;
3865 for (i = 1; i < argc; ++i) {
3866 if (!strcmp(argv[i],"--list-fingerprint")) {
3867 command = CMD_LIST_FINGERPRINT;
3868 } else if (!strcmp(argv[i],"--hash-password")) {
3869 command = CMD_HASH_PASSWORD;
3870 command_arg = tor_strdup( (i < argc-1) ? argv[i+1] : "");
3871 ++i;
3872 } else if (!strcmp(argv[i],"--verify-config")) {
3873 command = CMD_VERIFY_CONFIG;
3877 if (command == CMD_HASH_PASSWORD) {
3878 cf = tor_strdup("");
3879 } else {
3880 cf = load_torrc_from_disk(argc, argv);
3881 if (!cf)
3882 goto err;
3885 retval = options_init_from_string(cf, command, command_arg, &errmsg);
3886 tor_free(cf);
3887 if (retval < 0)
3888 goto err;
3890 return 0;
3892 err:
3893 if (errmsg) {
3894 log(LOG_WARN,LD_CONFIG,"%s", errmsg);
3895 tor_free(errmsg);
3897 return -1;
3900 /** Load the options from the configuration in <b>cf</b>, validate
3901 * them for consistency and take actions based on them.
3903 * Return 0 if success, negative on error:
3904 * * -1 for general errors.
3905 * * -2 for failure to parse/validate,
3906 * * -3 for transition not allowed
3907 * * -4 for error while setting the new options
3909 setopt_err_t
3910 options_init_from_string(const char *cf,
3911 int command, const char *command_arg,
3912 char **msg)
3914 or_options_t *oldoptions, *newoptions;
3915 config_line_t *cl;
3916 int retval;
3917 setopt_err_t err = SETOPT_ERR_MISC;
3918 tor_assert(msg);
3920 oldoptions = global_options; /* get_options unfortunately asserts if
3921 this is the first time we run*/
3923 newoptions = tor_malloc_zero(sizeof(or_options_t));
3924 newoptions->_magic = OR_OPTIONS_MAGIC;
3925 options_init(newoptions);
3926 newoptions->command = command;
3927 newoptions->command_arg = command_arg;
3929 /* get config lines, assign them */
3930 retval = config_get_lines(cf, &cl);
3931 if (retval < 0) {
3932 err = SETOPT_ERR_PARSE;
3933 goto err;
3935 retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
3936 config_free_lines(cl);
3937 if (retval < 0) {
3938 err = SETOPT_ERR_PARSE;
3939 goto err;
3942 /* Go through command-line variables too */
3943 retval = config_assign(&options_format, newoptions,
3944 global_cmdline_options, 0, 0, msg);
3945 if (retval < 0) {
3946 err = SETOPT_ERR_PARSE;
3947 goto err;
3950 /* If this is a testing network configuration, change defaults
3951 * for a list of dependent config options, re-initialize newoptions
3952 * with the new defaults, and assign all options to it second time. */
3953 if (newoptions->TestingTorNetwork) {
3954 /* XXXX021 this is a bit of a kludge. perhaps there's a better way to do
3955 * this? We could, for example, make the parsing algorithm do two passes
3956 * over the configuration. If it finds any "suite" options like
3957 * TestingTorNetwork, it could change the defaults before its second pass.
3958 * Not urgent so long as this seems to work, but at any sign of trouble,
3959 * let's clean it up. -NM */
3961 /* Change defaults. */
3962 int i;
3963 for (i = 0; testing_tor_network_defaults[i].name; ++i) {
3964 config_var_t *new_var = &testing_tor_network_defaults[i];
3965 config_var_t *old_var =
3966 config_find_option(&options_format, new_var->name);
3967 tor_assert(new_var);
3968 tor_assert(old_var);
3969 old_var->initvalue = new_var->initvalue;
3972 /* Clear newoptions and re-initialize them with new defaults. */
3973 config_free(&options_format, newoptions);
3974 newoptions = tor_malloc_zero(sizeof(or_options_t));
3975 newoptions->_magic = OR_OPTIONS_MAGIC;
3976 options_init(newoptions);
3977 newoptions->command = command;
3978 newoptions->command_arg = command_arg;
3980 /* Assign all options a second time. */
3981 retval = config_get_lines(cf, &cl);
3982 if (retval < 0) {
3983 err = SETOPT_ERR_PARSE;
3984 goto err;
3986 retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
3987 config_free_lines(cl);
3988 if (retval < 0) {
3989 err = SETOPT_ERR_PARSE;
3990 goto err;
3992 retval = config_assign(&options_format, newoptions,
3993 global_cmdline_options, 0, 0, msg);
3994 if (retval < 0) {
3995 err = SETOPT_ERR_PARSE;
3996 goto err;
4000 /* Validate newoptions */
4001 if (options_validate(oldoptions, newoptions, 0, msg) < 0) {
4002 err = SETOPT_ERR_PARSE; /*XXX021 make this separate.*/
4003 goto err;
4006 if (options_transition_allowed(oldoptions, newoptions, msg) < 0) {
4007 err = SETOPT_ERR_TRANSITION;
4008 goto err;
4011 if (set_options(newoptions, msg)) {
4012 err = SETOPT_ERR_SETTING;
4013 goto err; /* frees and replaces old options */
4016 return SETOPT_OK;
4018 err:
4019 config_free(&options_format, newoptions);
4020 if (*msg) {
4021 int len = strlen(*msg)+256;
4022 char *newmsg = tor_malloc(len);
4024 tor_snprintf(newmsg, len, "Failed to parse/validate config: %s", *msg);
4025 tor_free(*msg);
4026 *msg = newmsg;
4028 return err;
4031 /** Return the location for our configuration file.
4033 const char *
4034 get_torrc_fname(void)
4036 if (torrc_fname)
4037 return torrc_fname;
4038 else
4039 return get_default_conf_file();
4042 /** Adjust the address map mased on the MapAddress elements in the
4043 * configuration <b>options</b>
4045 static void
4046 config_register_addressmaps(or_options_t *options)
4048 smartlist_t *elts;
4049 config_line_t *opt;
4050 char *from, *to;
4052 addressmap_clear_configured();
4053 elts = smartlist_create();
4054 for (opt = options->AddressMap; opt; opt = opt->next) {
4055 smartlist_split_string(elts, opt->value, NULL,
4056 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
4057 if (smartlist_len(elts) >= 2) {
4058 from = smartlist_get(elts,0);
4059 to = smartlist_get(elts,1);
4060 if (address_is_invalid_destination(to, 1)) {
4061 log_warn(LD_CONFIG,
4062 "Skipping invalid argument '%s' to MapAddress", to);
4063 } else {
4064 addressmap_register(from, tor_strdup(to), 0, ADDRMAPSRC_TORRC);
4065 if (smartlist_len(elts)>2) {
4066 log_warn(LD_CONFIG,"Ignoring extra arguments to MapAddress.");
4069 } else {
4070 log_warn(LD_CONFIG,"MapAddress '%s' has too few arguments. Ignoring.",
4071 opt->value);
4073 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
4074 smartlist_clear(elts);
4076 smartlist_free(elts);
4080 * Initialize the logs based on the configuration file.
4082 static int
4083 options_init_logs(or_options_t *options, int validate_only)
4085 config_line_t *opt;
4086 int ok;
4087 smartlist_t *elts;
4088 int daemon =
4089 #ifdef MS_WINDOWS
4091 #else
4092 options->RunAsDaemon;
4093 #endif
4095 ok = 1;
4096 elts = smartlist_create();
4098 for (opt = options->Logs; opt; opt = opt->next) {
4099 log_severity_list_t *severity;
4100 const char *cfg = opt->value;
4101 severity = tor_malloc_zero(sizeof(log_severity_list_t));
4102 if (parse_log_severity_config(&cfg, severity) < 0) {
4103 log_warn(LD_CONFIG, "Couldn't parse log levels in Log option 'Log %s'",
4104 opt->value);
4105 ok = 0; goto cleanup;
4108 smartlist_split_string(elts, cfg, NULL,
4109 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
4111 if (smartlist_len(elts) == 0)
4112 smartlist_add(elts, tor_strdup("stdout"));
4114 if (smartlist_len(elts) == 1 &&
4115 (!strcasecmp(smartlist_get(elts,0), "stdout") ||
4116 !strcasecmp(smartlist_get(elts,0), "stderr"))) {
4117 int err = smartlist_len(elts) &&
4118 !strcasecmp(smartlist_get(elts,0), "stderr");
4119 if (!validate_only) {
4120 if (daemon) {
4121 log_warn(LD_CONFIG,
4122 "Can't log to %s with RunAsDaemon set; skipping stdout",
4123 err?"stderr":"stdout");
4124 } else {
4125 add_stream_log(severity, err?"<stderr>":"<stdout>",
4126 err?stderr:stdout);
4129 goto cleanup;
4131 if (smartlist_len(elts) == 1 &&
4132 !strcasecmp(smartlist_get(elts,0), "syslog")) {
4133 #ifdef HAVE_SYSLOG_H
4134 if (!validate_only) {
4135 add_syslog_log(severity);
4137 #else
4138 log_warn(LD_CONFIG, "Syslog is not supported on this system. Sorry.");
4139 #endif
4140 goto cleanup;
4143 if (smartlist_len(elts) == 2 &&
4144 !strcasecmp(smartlist_get(elts,0), "file")) {
4145 if (!validate_only) {
4146 if (add_file_log(severity, smartlist_get(elts, 1)) < 0) {
4147 log_warn(LD_CONFIG, "Couldn't open file for 'Log %s': %s",
4148 opt->value, strerror(errno));
4149 ok = 0;
4152 goto cleanup;
4155 log_warn(LD_CONFIG, "Bad syntax on file Log option 'Log %s'",
4156 opt->value);
4157 ok = 0; goto cleanup;
4159 cleanup:
4160 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
4161 smartlist_clear(elts);
4162 tor_free(severity);
4164 smartlist_free(elts);
4166 return ok?0:-1;
4169 /** Parse a single RedirectExit line's contents from <b>line</b>. If
4170 * they are valid, and <b>result</b> is not NULL, add an element to
4171 * <b>result</b> and return 0. Else if they are valid, return 0.
4172 * Else set *msg and return -1. */
4173 static int
4174 parse_redirect_line(smartlist_t *result, config_line_t *line, char **msg)
4176 smartlist_t *elements = NULL;
4177 exit_redirect_t *r;
4179 tor_assert(line);
4181 r = tor_malloc_zero(sizeof(exit_redirect_t));
4182 elements = smartlist_create();
4183 smartlist_split_string(elements, line->value, NULL,
4184 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
4185 if (smartlist_len(elements) != 2) {
4186 *msg = tor_strdup("Wrong number of elements in RedirectExit line");
4187 goto err;
4189 if (tor_addr_parse_mask_ports(smartlist_get(elements,0),&r->addr,
4190 &r->maskbits,&r->port_min,&r->port_max)) {
4191 *msg = tor_strdup("Error parsing source address in RedirectExit line");
4192 goto err;
4194 if (0==strcasecmp(smartlist_get(elements,1), "pass")) {
4195 r->is_redirect = 0;
4196 } else {
4197 if (tor_addr_port_parse(smartlist_get(elements,1),
4198 &r->addr_dest, &r->port_dest)) {
4199 *msg = tor_strdup("Error parsing dest address in RedirectExit line");
4200 goto err;
4202 r->is_redirect = 1;
4205 goto done;
4206 err:
4207 tor_free(r);
4208 done:
4209 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
4210 smartlist_free(elements);
4211 if (r) {
4212 if (result)
4213 smartlist_add(result, r);
4214 else
4215 tor_free(r);
4216 return 0;
4217 } else {
4218 tor_assert(*msg);
4219 return -1;
4223 /** Read the contents of a Bridge line from <b>line</b>. Return 0
4224 * if the line is well-formed, and -1 if it isn't. If
4225 * <b>validate_only</b> is 0, and the line is well-formed, then add
4226 * the bridge described in the line to our internal bridge list. */
4227 static int
4228 parse_bridge_line(const char *line, int validate_only)
4230 smartlist_t *items = NULL;
4231 int r;
4232 char *addrport=NULL, *fingerprint=NULL;
4233 tor_addr_t addr;
4234 uint16_t port = 0;
4235 char digest[DIGEST_LEN];
4237 items = smartlist_create();
4238 smartlist_split_string(items, line, NULL,
4239 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4240 if (smartlist_len(items) < 1) {
4241 log_warn(LD_CONFIG, "Too few arguments to Bridge line.");
4242 goto err;
4244 addrport = smartlist_get(items, 0);
4245 smartlist_del_keeporder(items, 0);
4246 if (tor_addr_port_parse(addrport, &addr, &port)<0) {
4247 log_warn(LD_CONFIG, "Error parsing Bridge address '%s'", addrport);
4248 goto err;
4250 if (!port) {
4251 log_warn(LD_CONFIG, "Missing port in Bridge address '%s'",addrport);
4252 goto err;
4255 if (smartlist_len(items)) {
4256 fingerprint = smartlist_join_strings(items, "", 0, NULL);
4257 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
4258 log_warn(LD_CONFIG, "Key digest for Bridge is wrong length.");
4259 goto err;
4261 if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
4262 log_warn(LD_CONFIG, "Unable to decode Bridge key digest.");
4263 goto err;
4267 if (!validate_only) {
4268 log_debug(LD_DIR, "Bridge at %s:%d (%s)", fmt_addr(&addr),
4269 (int)port,
4270 fingerprint ? fingerprint : "no key listed");
4271 bridge_add_from_config(&addr, port, fingerprint ? digest : NULL);
4274 r = 0;
4275 goto done;
4277 err:
4278 r = -1;
4280 done:
4281 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4282 smartlist_free(items);
4283 tor_free(addrport);
4284 tor_free(fingerprint);
4285 return r;
4288 /** Read the contents of a DirServer line from <b>line</b>. If
4289 * <b>validate_only</b> is 0, and the line is well-formed, and it
4290 * shares any bits with <b>required_type</b> or <b>required_type</b>
4291 * is 0, then add the dirserver described in the line (minus whatever
4292 * bits it's missing) as a valid authority. Return 0 on success,
4293 * or -1 if the line isn't well-formed or if we can't add it. */
4294 static int
4295 parse_dir_server_line(const char *line, authority_type_t required_type,
4296 int validate_only)
4298 smartlist_t *items = NULL;
4299 int r;
4300 char *addrport=NULL, *address=NULL, *nickname=NULL, *fingerprint=NULL;
4301 uint16_t dir_port = 0, or_port = 0;
4302 char digest[DIGEST_LEN];
4303 char v3_digest[DIGEST_LEN];
4304 authority_type_t type = V2_AUTHORITY;
4305 int is_not_hidserv_authority = 0, is_not_v2_authority = 0;
4307 items = smartlist_create();
4308 smartlist_split_string(items, line, NULL,
4309 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4310 if (smartlist_len(items) < 1) {
4311 log_warn(LD_CONFIG, "No arguments on DirServer line.");
4312 goto err;
4315 if (is_legal_nickname(smartlist_get(items, 0))) {
4316 nickname = smartlist_get(items, 0);
4317 smartlist_del_keeporder(items, 0);
4320 while (smartlist_len(items)) {
4321 char *flag = smartlist_get(items, 0);
4322 if (TOR_ISDIGIT(flag[0]))
4323 break;
4324 if (!strcasecmp(flag, "v1")) {
4325 type |= (V1_AUTHORITY | HIDSERV_AUTHORITY);
4326 } else if (!strcasecmp(flag, "hs")) {
4327 type |= HIDSERV_AUTHORITY;
4328 } else if (!strcasecmp(flag, "no-hs")) {
4329 is_not_hidserv_authority = 1;
4330 } else if (!strcasecmp(flag, "bridge")) {
4331 type |= BRIDGE_AUTHORITY;
4332 } else if (!strcasecmp(flag, "no-v2")) {
4333 is_not_v2_authority = 1;
4334 } else if (!strcasecmpstart(flag, "orport=")) {
4335 int ok;
4336 char *portstring = flag + strlen("orport=");
4337 or_port = (uint16_t) tor_parse_long(portstring, 10, 1, 65535, &ok, NULL);
4338 if (!ok)
4339 log_warn(LD_CONFIG, "Invalid orport '%s' on DirServer line.",
4340 portstring);
4341 } else if (!strcasecmpstart(flag, "v3ident=")) {
4342 char *idstr = flag + strlen("v3ident=");
4343 if (strlen(idstr) != HEX_DIGEST_LEN ||
4344 base16_decode(v3_digest, DIGEST_LEN, idstr, HEX_DIGEST_LEN)<0) {
4345 log_warn(LD_CONFIG, "Bad v3 identity digest '%s' on DirServer line",
4346 flag);
4347 } else {
4348 type |= V3_AUTHORITY;
4350 } else {
4351 log_warn(LD_CONFIG, "Unrecognized flag '%s' on DirServer line",
4352 flag);
4354 tor_free(flag);
4355 smartlist_del_keeporder(items, 0);
4357 if (is_not_hidserv_authority)
4358 type &= ~HIDSERV_AUTHORITY;
4359 if (is_not_v2_authority)
4360 type &= ~V2_AUTHORITY;
4362 if (smartlist_len(items) < 2) {
4363 log_warn(LD_CONFIG, "Too few arguments to DirServer line.");
4364 goto err;
4366 addrport = smartlist_get(items, 0);
4367 smartlist_del_keeporder(items, 0);
4368 if (parse_addr_port(LOG_WARN, addrport, &address, NULL, &dir_port)<0) {
4369 log_warn(LD_CONFIG, "Error parsing DirServer address '%s'", addrport);
4370 goto err;
4372 if (!dir_port) {
4373 log_warn(LD_CONFIG, "Missing port in DirServer address '%s'",addrport);
4374 goto err;
4377 fingerprint = smartlist_join_strings(items, "", 0, NULL);
4378 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
4379 log_warn(LD_CONFIG, "Key digest for DirServer is wrong length %d.",
4380 (int)strlen(fingerprint));
4381 goto err;
4383 if (!strcmp(fingerprint, "E623F7625FBE0C87820F11EC5F6D5377ED816294")) {
4384 /* a known bad fingerprint. refuse to use it. We can remove this
4385 * clause once Tor 0.1.2.17 is obsolete. */
4386 log_warn(LD_CONFIG, "Dangerous dirserver line. To correct, erase your "
4387 "torrc file (%s), or reinstall Tor and use the default torrc.",
4388 get_torrc_fname());
4389 goto err;
4391 if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
4392 log_warn(LD_CONFIG, "Unable to decode DirServer key digest.");
4393 goto err;
4396 if (!validate_only && (!required_type || required_type & type)) {
4397 if (required_type)
4398 type &= required_type; /* pare down what we think of them as an
4399 * authority for. */
4400 log_debug(LD_DIR, "Trusted %d dirserver at %s:%d (%s)", (int)type,
4401 address, (int)dir_port, (char*)smartlist_get(items,0));
4402 if (!add_trusted_dir_server(nickname, address, dir_port, or_port,
4403 digest, v3_digest, type))
4404 goto err;
4407 r = 0;
4408 goto done;
4410 err:
4411 r = -1;
4413 done:
4414 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4415 smartlist_free(items);
4416 tor_free(addrport);
4417 tor_free(address);
4418 tor_free(nickname);
4419 tor_free(fingerprint);
4420 return r;
4423 /** Adjust the value of options->DataDirectory, or fill it in if it's
4424 * absent. Return 0 on success, -1 on failure. */
4425 static int
4426 normalize_data_directory(or_options_t *options)
4428 #ifdef MS_WINDOWS
4429 char *p;
4430 if (options->DataDirectory)
4431 return 0; /* all set */
4432 p = tor_malloc(MAX_PATH);
4433 strlcpy(p,get_windows_conf_root(),MAX_PATH);
4434 options->DataDirectory = p;
4435 return 0;
4436 #else
4437 const char *d = options->DataDirectory;
4438 if (!d)
4439 d = "~/.tor";
4441 if (strncmp(d,"~/",2) == 0) {
4442 char *fn = expand_filename(d);
4443 if (!fn) {
4444 log_warn(LD_CONFIG,"Failed to expand filename \"%s\".", d);
4445 return -1;
4447 if (!options->DataDirectory && !strcmp(fn,"/.tor")) {
4448 /* If our homedir is /, we probably don't want to use it. */
4449 /* Default to LOCALSTATEDIR/tor which is probably closer to what we
4450 * want. */
4451 log_warn(LD_CONFIG,
4452 "Default DataDirectory is \"~/.tor\". This expands to "
4453 "\"%s\", which is probably not what you want. Using "
4454 "\"%s"PATH_SEPARATOR"tor\" instead", fn, LOCALSTATEDIR);
4455 tor_free(fn);
4456 fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor");
4458 tor_free(options->DataDirectory);
4459 options->DataDirectory = fn;
4461 return 0;
4462 #endif
4465 /** Check and normalize the value of options->DataDirectory; return 0 if it
4466 * sane, -1 otherwise. */
4467 static int
4468 validate_data_directory(or_options_t *options)
4470 if (normalize_data_directory(options) < 0)
4471 return -1;
4472 tor_assert(options->DataDirectory);
4473 if (strlen(options->DataDirectory) > (512-128)) {
4474 log_warn(LD_CONFIG, "DataDirectory is too long.");
4475 return -1;
4477 return 0;
4480 /** This string must remain the same forevermore. It is how we
4481 * recognize that the torrc file doesn't need to be backed up. */
4482 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
4483 "if you edit it, comments will not be preserved"
4484 /** This string can change; it tries to give the reader an idea
4485 * that editing this file by hand is not a good plan. */
4486 #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
4487 "to torrc.orig.1 or similar, and Tor will ignore it"
4489 /** Save a configuration file for the configuration in <b>options</b>
4490 * into the file <b>fname</b>. If the file already exists, and
4491 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
4492 * replace it. Return 0 on success, -1 on failure. */
4493 static int
4494 write_configuration_file(const char *fname, or_options_t *options)
4496 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
4497 int rename_old = 0, r;
4498 size_t len;
4500 if (fname) {
4501 switch (file_status(fname)) {
4502 case FN_FILE:
4503 old_val = read_file_to_str(fname, 0, NULL);
4504 if (strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
4505 rename_old = 1;
4507 tor_free(old_val);
4508 break;
4509 case FN_NOENT:
4510 break;
4511 case FN_ERROR:
4512 case FN_DIR:
4513 default:
4514 log_warn(LD_CONFIG,
4515 "Config file \"%s\" is not a file? Failing.", fname);
4516 return -1;
4520 if (!(new_conf = options_dump(options, 1))) {
4521 log_warn(LD_BUG, "Couldn't get configuration string");
4522 goto err;
4525 len = strlen(new_conf)+256;
4526 new_val = tor_malloc(len);
4527 tor_snprintf(new_val, len, "%s\n%s\n\n%s",
4528 GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
4530 if (rename_old) {
4531 int i = 1;
4532 size_t fn_tmp_len = strlen(fname)+32;
4533 char *fn_tmp;
4534 tor_assert(fn_tmp_len > strlen(fname)); /*check for overflow*/
4535 fn_tmp = tor_malloc(fn_tmp_len);
4536 while (1) {
4537 if (tor_snprintf(fn_tmp, fn_tmp_len, "%s.orig.%d", fname, i)<0) {
4538 log_warn(LD_BUG, "tor_snprintf failed inexplicably");
4539 tor_free(fn_tmp);
4540 goto err;
4542 if (file_status(fn_tmp) == FN_NOENT)
4543 break;
4544 ++i;
4546 log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
4547 if (rename(fname, fn_tmp) < 0) {
4548 log_warn(LD_FS,
4549 "Couldn't rename configuration file \"%s\" to \"%s\": %s",
4550 fname, fn_tmp, strerror(errno));
4551 tor_free(fn_tmp);
4552 goto err;
4554 tor_free(fn_tmp);
4557 if (write_str_to_file(fname, new_val, 0) < 0)
4558 goto err;
4560 r = 0;
4561 goto done;
4562 err:
4563 r = -1;
4564 done:
4565 tor_free(new_val);
4566 tor_free(new_conf);
4567 return r;
4571 * Save the current configuration file value to disk. Return 0 on
4572 * success, -1 on failure.
4575 options_save_current(void)
4577 if (torrc_fname) {
4578 /* This fails if we can't write to our configuration file.
4580 * If we try falling back to datadirectory or something, we have a better
4581 * chance of saving the configuration, but a better chance of doing
4582 * something the user never expected. Let's just warn instead. */
4583 return write_configuration_file(torrc_fname, get_options());
4585 return write_configuration_file(get_default_conf_file(), get_options());
4588 /** Mapping from a unit name to a multiplier for converting that unit into a
4589 * base unit. */
4590 struct unit_table_t {
4591 const char *unit;
4592 uint64_t multiplier;
4595 static struct unit_table_t memory_units[] = {
4596 { "", 1 },
4597 { "b", 1<< 0 },
4598 { "byte", 1<< 0 },
4599 { "bytes", 1<< 0 },
4600 { "kb", 1<<10 },
4601 { "kbyte", 1<<10 },
4602 { "kbytes", 1<<10 },
4603 { "kilobyte", 1<<10 },
4604 { "kilobytes", 1<<10 },
4605 { "m", 1<<20 },
4606 { "mb", 1<<20 },
4607 { "mbyte", 1<<20 },
4608 { "mbytes", 1<<20 },
4609 { "megabyte", 1<<20 },
4610 { "megabytes", 1<<20 },
4611 { "gb", 1<<30 },
4612 { "gbyte", 1<<30 },
4613 { "gbytes", 1<<30 },
4614 { "gigabyte", 1<<30 },
4615 { "gigabytes", 1<<30 },
4616 { "tb", U64_LITERAL(1)<<40 },
4617 { "terabyte", U64_LITERAL(1)<<40 },
4618 { "terabytes", U64_LITERAL(1)<<40 },
4619 { NULL, 0 },
4622 static struct unit_table_t time_units[] = {
4623 { "", 1 },
4624 { "second", 1 },
4625 { "seconds", 1 },
4626 { "minute", 60 },
4627 { "minutes", 60 },
4628 { "hour", 60*60 },
4629 { "hours", 60*60 },
4630 { "day", 24*60*60 },
4631 { "days", 24*60*60 },
4632 { "week", 7*24*60*60 },
4633 { "weeks", 7*24*60*60 },
4634 { NULL, 0 },
4637 /** Parse a string <b>val</b> containing a number, zero or more
4638 * spaces, and an optional unit string. If the unit appears in the
4639 * table <b>u</b>, then multiply the number by the unit multiplier.
4640 * On success, set *<b>ok</b> to 1 and return this product.
4641 * Otherwise, set *<b>ok</b> to 0.
4643 static uint64_t
4644 config_parse_units(const char *val, struct unit_table_t *u, int *ok)
4646 uint64_t v;
4647 char *cp;
4649 tor_assert(ok);
4651 v = tor_parse_uint64(val, 10, 0, UINT64_MAX, ok, &cp);
4652 if (!*ok)
4653 return 0;
4654 if (!cp) {
4655 *ok = 1;
4656 return v;
4658 while (TOR_ISSPACE(*cp))
4659 ++cp;
4660 for ( ;u->unit;++u) {
4661 if (!strcasecmp(u->unit, cp)) {
4662 v *= u->multiplier;
4663 *ok = 1;
4664 return v;
4667 log_warn(LD_CONFIG, "Unknown unit '%s'.", cp);
4668 *ok = 0;
4669 return 0;
4672 /** Parse a string in the format "number unit", where unit is a unit of
4673 * information (byte, KB, M, etc). On success, set *<b>ok</b> to true
4674 * and return the number of bytes specified. Otherwise, set
4675 * *<b>ok</b> to false and return 0. */
4676 static uint64_t
4677 config_parse_memunit(const char *s, int *ok)
4679 return config_parse_units(s, memory_units, ok);
4682 /** Parse a string in the format "number unit", where unit is a unit of time.
4683 * On success, set *<b>ok</b> to true and return the number of seconds in
4684 * the provided interval. Otherwise, set *<b>ok</b> to 0 and return -1.
4686 static int
4687 config_parse_interval(const char *s, int *ok)
4689 uint64_t r;
4690 r = config_parse_units(s, time_units, ok);
4691 if (!ok)
4692 return -1;
4693 if (r > INT_MAX) {
4694 log_warn(LD_CONFIG, "Interval '%s' is too long", s);
4695 *ok = 0;
4696 return -1;
4698 return (int)r;
4702 * Initialize the libevent library.
4704 static void
4705 init_libevent(void)
4707 configure_libevent_logging();
4708 /* If the kernel complains that some method (say, epoll) doesn't
4709 * exist, we don't care about it, since libevent will cope.
4711 suppress_libevent_log_msg("Function not implemented");
4712 #ifdef __APPLE__
4713 if (decode_libevent_version() < LE_11B) {
4714 setenv("EVENT_NOKQUEUE","1",1);
4716 #endif
4717 event_init();
4718 suppress_libevent_log_msg(NULL);
4719 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
4720 /* Making this a NOTICE for now so we can link bugs to a libevent versions
4721 * or methods better. */
4722 log(LOG_NOTICE, LD_GENERAL,
4723 "Initialized libevent version %s using method %s. Good.",
4724 event_get_version(), event_get_method());
4725 check_libevent_version(event_get_method(), get_options()->ORPort != 0);
4726 #else
4727 log(LOG_NOTICE, LD_GENERAL,
4728 "Initialized old libevent (version 1.0b or earlier).");
4729 log(LOG_WARN, LD_GENERAL,
4730 "You have a *VERY* old version of libevent. It is likely to be buggy; "
4731 "please build Tor with a more recent version.");
4732 #endif
4735 #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
4736 /** Table mapping return value of event_get_version() to le_version_t. */
4737 static const struct {
4738 const char *name; le_version_t version;
4739 } le_version_table[] = {
4740 /* earlier versions don't have get_version. */
4741 { "1.0c", LE_10C },
4742 { "1.0d", LE_10D },
4743 { "1.0e", LE_10E },
4744 { "1.1", LE_11 },
4745 { "1.1a", LE_11A },
4746 { "1.1b", LE_11B },
4747 { "1.2", LE_12 },
4748 { "1.2a", LE_12A },
4749 { "1.3", LE_13 },
4750 { "1.3a", LE_13A },
4751 { "1.3b", LE_13B },
4752 { "1.3c", LE_13C },
4753 { "1.3d", LE_13D },
4754 { NULL, LE_OTHER }
4757 /** Return the le_version_t for the current version of libevent. If the
4758 * version is very new, return LE_OTHER. If the version is so old that it
4759 * doesn't support event_get_version(), return LE_OLD. */
4760 static le_version_t
4761 decode_libevent_version(void)
4763 const char *v = event_get_version();
4764 int i;
4765 for (i=0; le_version_table[i].name; ++i) {
4766 if (!strcmp(le_version_table[i].name, v)) {
4767 return le_version_table[i].version;
4770 return LE_OTHER;
4774 * Compare the given libevent method and version to a list of versions
4775 * which are known not to work. Warn the user as appropriate.
4777 static void
4778 check_libevent_version(const char *m, int server)
4780 int buggy = 0, iffy = 0, slow = 0, thread_unsafe = 0;
4781 le_version_t version;
4782 const char *v = event_get_version();
4783 const char *badness = NULL;
4784 const char *sad_os = "";
4786 version = decode_libevent_version();
4788 /* XXX Would it be worthwhile disabling the methods that we know
4789 * are buggy, rather than just warning about them and then proceeding
4790 * to use them? If so, we should probably not wrap this whole thing
4791 * in HAVE_EVENT_GET_VERSION and HAVE_EVENT_GET_METHOD. -RD */
4792 /* XXXX The problem is that it's not trivial to get libevent to change it's
4793 * method once it's initialized, and it's not trivial to tell what method it
4794 * will use without initializing it. I guess we could preemptively disable
4795 * buggy libevent modes based on the version _before_ initializing it,
4796 * though, but then there's no good way (afaict) to warn "I would have used
4797 * kqueue, but instead I'm using select." -NM */
4798 if (!strcmp(m, "kqueue")) {
4799 if (version < LE_11B)
4800 buggy = 1;
4801 } else if (!strcmp(m, "epoll")) {
4802 if (version < LE_11)
4803 iffy = 1;
4804 } else if (!strcmp(m, "poll")) {
4805 if (version < LE_10E)
4806 buggy = 1;
4807 else if (version < LE_11)
4808 slow = 1;
4809 } else if (!strcmp(m, "select")) {
4810 if (version < LE_11)
4811 slow = 1;
4812 } else if (!strcmp(m, "win32")) {
4813 if (version < LE_11B)
4814 buggy = 1;
4817 /* Libevent versions before 1.3b do very badly on operating systems with
4818 * user-space threading implementations. */
4819 #if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__)
4820 if (server && version < LE_13B) {
4821 thread_unsafe = 1;
4822 sad_os = "BSD variants";
4824 #elif defined(__APPLE__) || defined(__darwin__)
4825 if (server && version < LE_13B) {
4826 thread_unsafe = 1;
4827 sad_os = "Mac OS X";
4829 #endif
4831 if (thread_unsafe) {
4832 log(LOG_WARN, LD_GENERAL,
4833 "Libevent version %s often crashes when running a Tor server with %s. "
4834 "Please use the latest version of libevent (1.3b or later)",v,sad_os);
4835 badness = "BROKEN";
4836 } else if (buggy) {
4837 log(LOG_WARN, LD_GENERAL,
4838 "There are serious bugs in using %s with libevent %s. "
4839 "Please use the latest version of libevent.", m, v);
4840 badness = "BROKEN";
4841 } else if (iffy) {
4842 log(LOG_WARN, LD_GENERAL,
4843 "There are minor bugs in using %s with libevent %s. "
4844 "You may want to use the latest version of libevent.", m, v);
4845 badness = "BUGGY";
4846 } else if (slow && server) {
4847 log(LOG_WARN, LD_GENERAL,
4848 "libevent %s can be very slow with %s. "
4849 "When running a server, please use the latest version of libevent.",
4850 v,m);
4851 badness = "SLOW";
4853 if (badness) {
4854 control_event_general_status(LOG_WARN,
4855 "BAD_LIBEVENT VERSION=%s METHOD=%s BADNESS=%s RECOVERED=NO",
4856 v, m, badness);
4860 #else
4861 static le_version_t
4862 decode_libevent_version(void)
4864 return LE_OLD;
4866 #endif
4868 /** Return the persistent state struct for this Tor. */
4869 or_state_t *
4870 get_or_state(void)
4872 tor_assert(global_state);
4873 return global_state;
4876 /** Return a newly allocated string holding a filename relative to the data
4877 * directory. If <b>sub1</b> is present, it is the first path component after
4878 * the data directory. If <b>sub2</b> is also present, it is the second path
4879 * component after the data directory. If <b>suffix</b> is present, it
4880 * is appended to the filename.
4882 * Examples:
4883 * get_datadir_fname2_suffix("a", NULL, NULL) -> $DATADIR/a
4884 * get_datadir_fname2_suffix("a", NULL, ".tmp") -> $DATADIR/a.tmp
4885 * get_datadir_fname2_suffix("a", "b", ".tmp") -> $DATADIR/a/b/.tmp
4886 * get_datadir_fname2_suffix("a", "b", NULL) -> $DATADIR/a/b
4888 * Note: Consider using the get_datadir_fname* macros in or.h.
4890 char *
4891 options_get_datadir_fname2_suffix(or_options_t *options,
4892 const char *sub1, const char *sub2,
4893 const char *suffix)
4895 char *fname = NULL;
4896 size_t len;
4897 tor_assert(options);
4898 tor_assert(options->DataDirectory);
4899 tor_assert(sub1 || !sub2); /* If sub2 is present, sub1 must be present. */
4900 len = strlen(options->DataDirectory);
4901 if (sub1) {
4902 len += strlen(sub1)+1;
4903 if (sub2)
4904 len += strlen(sub2)+1;
4906 if (suffix)
4907 len += strlen(suffix);
4908 len++;
4909 fname = tor_malloc(len);
4910 if (sub1) {
4911 if (sub2) {
4912 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s",
4913 options->DataDirectory, sub1, sub2);
4914 } else {
4915 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s",
4916 options->DataDirectory, sub1);
4918 } else {
4919 strlcpy(fname, options->DataDirectory, len);
4921 if (suffix)
4922 strlcat(fname, suffix, len);
4923 return fname;
4926 /** Return 0 if every setting in <b>state</b> is reasonable, and a
4927 * permissible transition from <b>old_state</b>. Else warn and return -1.
4928 * Should have no side effects, except for normalizing the contents of
4929 * <b>state</b>.
4931 /* XXX from_setconf is here because of bug 238 */
4932 static int
4933 or_state_validate(or_state_t *old_state, or_state_t *state,
4934 int from_setconf, char **msg)
4936 /* We don't use these; only options do. Still, we need to match that
4937 * signature. */
4938 (void) from_setconf;
4939 (void) old_state;
4941 if (entry_guards_parse_state(state, 0, msg)<0)
4942 return -1;
4944 return 0;
4947 /** Replace the current persistent state with <b>new_state</b> */
4948 static void
4949 or_state_set(or_state_t *new_state)
4951 char *err = NULL;
4952 tor_assert(new_state);
4953 if (global_state)
4954 config_free(&state_format, global_state);
4955 global_state = new_state;
4956 if (entry_guards_parse_state(global_state, 1, &err)<0) {
4957 log_warn(LD_GENERAL,"%s",err);
4958 tor_free(err);
4960 if (rep_hist_load_state(global_state, &err)<0) {
4961 log_warn(LD_GENERAL,"Unparseable bandwidth history state: %s",err);
4962 tor_free(err);
4966 /** Reload the persistent state from disk, generating a new state as needed.
4967 * Return 0 on success, less than 0 on failure.
4969 static int
4970 or_state_load(void)
4972 or_state_t *new_state = NULL;
4973 char *contents = NULL, *fname;
4974 char *errmsg = NULL;
4975 int r = -1, badstate = 0;
4977 fname = get_datadir_fname("state");
4978 switch (file_status(fname)) {
4979 case FN_FILE:
4980 if (!(contents = read_file_to_str(fname, 0, NULL))) {
4981 log_warn(LD_FS, "Unable to read state file \"%s\"", fname);
4982 goto done;
4984 break;
4985 case FN_NOENT:
4986 break;
4987 case FN_ERROR:
4988 case FN_DIR:
4989 default:
4990 log_warn(LD_GENERAL,"State file \"%s\" is not a file? Failing.", fname);
4991 goto done;
4993 new_state = tor_malloc_zero(sizeof(or_state_t));
4994 new_state->_magic = OR_STATE_MAGIC;
4995 config_init(&state_format, new_state);
4996 if (contents) {
4997 config_line_t *lines=NULL;
4998 int assign_retval;
4999 if (config_get_lines(contents, &lines)<0)
5000 goto done;
5001 assign_retval = config_assign(&state_format, new_state,
5002 lines, 0, 0, &errmsg);
5003 config_free_lines(lines);
5004 if (assign_retval<0)
5005 badstate = 1;
5006 if (errmsg) {
5007 log_warn(LD_GENERAL, "%s", errmsg);
5008 tor_free(errmsg);
5012 if (!badstate && or_state_validate(NULL, new_state, 1, &errmsg) < 0)
5013 badstate = 1;
5015 if (errmsg) {
5016 log_warn(LD_GENERAL, "%s", errmsg);
5017 tor_free(errmsg);
5020 if (badstate && !contents) {
5021 log_warn(LD_BUG, "Uh oh. We couldn't even validate our own default state."
5022 " This is a bug in Tor.");
5023 goto done;
5024 } else if (badstate && contents) {
5025 int i;
5026 file_status_t status;
5027 size_t len = strlen(fname)+16;
5028 char *fname2 = tor_malloc(len);
5029 for (i = 0; i < 100; ++i) {
5030 tor_snprintf(fname2, len, "%s.%d", fname, i);
5031 status = file_status(fname2);
5032 if (status == FN_NOENT)
5033 break;
5035 if (i == 100) {
5036 log_warn(LD_BUG, "Unable to parse state in \"%s\"; too many saved bad "
5037 "state files to move aside. Discarding the old state file.",
5038 fname);
5039 unlink(fname);
5040 } else {
5041 log_warn(LD_BUG, "Unable to parse state in \"%s\". Moving it aside "
5042 "to \"%s\". This could be a bug in Tor; please tell "
5043 "the developers.", fname, fname2);
5044 if (rename(fname, fname2) < 0) {
5045 log_warn(LD_BUG, "Weirdly, I couldn't even move the state aside. The "
5046 "OS gave an error of %s", strerror(errno));
5049 tor_free(fname2);
5050 tor_free(contents);
5051 config_free(&state_format, new_state);
5053 new_state = tor_malloc_zero(sizeof(or_state_t));
5054 new_state->_magic = OR_STATE_MAGIC;
5055 config_init(&state_format, new_state);
5056 } else if (contents) {
5057 log_info(LD_GENERAL, "Loaded state from \"%s\"", fname);
5058 } else {
5059 log_info(LD_GENERAL, "Initialized state");
5061 or_state_set(new_state);
5062 new_state = NULL;
5063 if (!contents) {
5064 global_state->next_write = 0;
5065 or_state_save(time(NULL));
5067 r = 0;
5069 done:
5070 tor_free(fname);
5071 tor_free(contents);
5072 if (new_state)
5073 config_free(&state_format, new_state);
5075 return r;
5078 /** Write the persistent state to disk. Return 0 for success, <0 on failure. */
5080 or_state_save(time_t now)
5082 char *state, *contents;
5083 char tbuf[ISO_TIME_LEN+1];
5084 size_t len;
5085 char *fname;
5087 tor_assert(global_state);
5089 if (global_state->next_write > now)
5090 return 0;
5092 /* Call everything else that might dirty the state even more, in order
5093 * to avoid redundant writes. */
5094 entry_guards_update_state(global_state);
5095 rep_hist_update_state(global_state);
5096 if (accounting_is_enabled(get_options()))
5097 accounting_run_housekeeping(now);
5099 global_state->LastWritten = time(NULL);
5100 tor_free(global_state->TorVersion);
5101 len = strlen(get_version())+8;
5102 global_state->TorVersion = tor_malloc(len);
5103 tor_snprintf(global_state->TorVersion, len, "Tor %s", get_version());
5105 state = config_dump(&state_format, global_state, 1, 0);
5106 len = strlen(state)+256;
5107 contents = tor_malloc(len);
5108 format_local_iso_time(tbuf, time(NULL));
5109 tor_snprintf(contents, len,
5110 "# Tor state file last generated on %s local time\n"
5111 "# Other times below are in GMT\n"
5112 "# You *do not* need to edit this file.\n\n%s",
5113 tbuf, state);
5114 tor_free(state);
5115 fname = get_datadir_fname("state");
5116 if (write_str_to_file(fname, contents, 0)<0) {
5117 log_warn(LD_FS, "Unable to write state to file \"%s\"", fname);
5118 tor_free(fname);
5119 tor_free(contents);
5120 return -1;
5122 log_info(LD_GENERAL, "Saved state to \"%s\"", fname);
5123 tor_free(fname);
5124 tor_free(contents);
5126 global_state->next_write = TIME_MAX;
5127 return 0;
5130 /** Given a file name check to see whether the file exists but has not been
5131 * modified for a very long time. If so, remove it. */
5132 void
5133 remove_file_if_very_old(const char *fname, time_t now)
5135 #define VERY_OLD_FILE_AGE (28*24*60*60)
5136 struct stat st;
5138 if (stat(fname, &st)==0 && st.st_mtime < now-VERY_OLD_FILE_AGE) {
5139 char buf[ISO_TIME_LEN+1];
5140 format_local_iso_time(buf, st.st_mtime);
5141 log_notice(LD_GENERAL, "Obsolete file %s hasn't been modified since %s. "
5142 "Removing it.", fname, buf);
5143 unlink(fname);
5147 /** Helper to implement GETINFO functions about configuration variables (not
5148 * their values). Given a "config/names" question, set *<b>answer</b> to a
5149 * new string describing the supported configuration variables and their
5150 * types. */
5152 getinfo_helper_config(control_connection_t *conn,
5153 const char *question, char **answer)
5155 (void) conn;
5156 if (!strcmp(question, "config/names")) {
5157 smartlist_t *sl = smartlist_create();
5158 int i;
5159 for (i = 0; _option_vars[i].name; ++i) {
5160 config_var_t *var = &_option_vars[i];
5161 const char *type, *desc;
5162 char *line;
5163 size_t len;
5164 desc = config_find_description(&options_format, var->name);
5165 switch (var->type) {
5166 case CONFIG_TYPE_STRING: type = "String"; break;
5167 case CONFIG_TYPE_FILENAME: type = "Filename"; break;
5168 case CONFIG_TYPE_UINT: type = "Integer"; break;
5169 case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
5170 case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
5171 case CONFIG_TYPE_DOUBLE: type = "Float"; break;
5172 case CONFIG_TYPE_BOOL: type = "Boolean"; break;
5173 case CONFIG_TYPE_ISOTIME: type = "Time"; break;
5174 case CONFIG_TYPE_ROUTERSET: type = "RouterList"; break;
5175 case CONFIG_TYPE_CSV: type = "CommaList"; break;
5176 case CONFIG_TYPE_LINELIST: type = "LineList"; break;
5177 case CONFIG_TYPE_LINELIST_S: type = "Dependant"; break;
5178 case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
5179 default:
5180 case CONFIG_TYPE_OBSOLETE:
5181 type = NULL; break;
5183 if (!type)
5184 continue;
5185 len = strlen(var->name)+strlen(type)+16;
5186 if (desc)
5187 len += strlen(desc);
5188 line = tor_malloc(len);
5189 if (desc)
5190 tor_snprintf(line, len, "%s %s %s\n",var->name,type,desc);
5191 else
5192 tor_snprintf(line, len, "%s %s\n",var->name,type);
5193 smartlist_add(sl, line);
5195 *answer = smartlist_join_strings(sl, "", 0, NULL);
5196 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
5197 smartlist_free(sl);
5199 return 0;
5202 #include "aes.h"
5203 #include "ht.h"
5204 #include "test.h"
5206 extern const char address_c_id[];
5207 extern const char aes_c_id[];
5208 extern const char compat_c_id[];
5209 extern const char container_c_id[];
5210 extern const char crypto_c_id[];
5211 extern const char log_c_id[];
5212 extern const char torgzip_c_id[];
5213 extern const char tortls_c_id[];
5214 extern const char util_c_id[];
5216 extern const char buffers_c_id[];
5217 extern const char circuitbuild_c_id[];
5218 extern const char circuitlist_c_id[];
5219 extern const char circuituse_c_id[];
5220 extern const char command_c_id[];
5221 // extern const char config_c_id[];
5222 extern const char connection_c_id[];
5223 extern const char connection_edge_c_id[];
5224 extern const char connection_or_c_id[];
5225 extern const char control_c_id[];
5226 extern const char cpuworker_c_id[];
5227 extern const char directory_c_id[];
5228 extern const char dirserv_c_id[];
5229 extern const char dns_c_id[];
5230 extern const char hibernate_c_id[];
5231 extern const char main_c_id[];
5232 #ifdef NT_SERVICE
5233 extern const char ntmain_c_id[];
5234 #endif
5235 extern const char onion_c_id[];
5236 extern const char policies_c_id[];
5237 extern const char relay_c_id[];
5238 extern const char rendclient_c_id[];
5239 extern const char rendcommon_c_id[];
5240 extern const char rendmid_c_id[];
5241 extern const char rendservice_c_id[];
5242 extern const char rephist_c_id[];
5243 extern const char router_c_id[];
5244 extern const char routerlist_c_id[];
5245 extern const char routerparse_c_id[];
5247 /** Dump the version of every file to the log. */
5248 static void
5249 print_svn_version(void)
5251 puts(ADDRESS_H_ID);
5252 puts(AES_H_ID);
5253 puts(COMPAT_H_ID);
5254 puts(CONTAINER_H_ID);
5255 puts(CRYPTO_H_ID);
5256 puts(HT_H_ID);
5257 puts(TEST_H_ID);
5258 puts(LOG_H_ID);
5259 puts(TORGZIP_H_ID);
5260 puts(TORINT_H_ID);
5261 puts(TORTLS_H_ID);
5262 puts(UTIL_H_ID);
5263 puts(address_c_id);
5264 puts(aes_c_id);
5265 puts(compat_c_id);
5266 puts(container_c_id);
5267 puts(crypto_c_id);
5268 puts(log_c_id);
5269 puts(torgzip_c_id);
5270 puts(tortls_c_id);
5271 puts(util_c_id);
5273 puts(OR_H_ID);
5274 puts(buffers_c_id);
5275 puts(circuitbuild_c_id);
5276 puts(circuitlist_c_id);
5277 puts(circuituse_c_id);
5278 puts(command_c_id);
5279 puts(config_c_id);
5280 puts(connection_c_id);
5281 puts(connection_edge_c_id);
5282 puts(connection_or_c_id);
5283 puts(control_c_id);
5284 puts(cpuworker_c_id);
5285 puts(directory_c_id);
5286 puts(dirserv_c_id);
5287 puts(dns_c_id);
5288 puts(hibernate_c_id);
5289 puts(main_c_id);
5290 #ifdef NT_SERVICE
5291 puts(ntmain_c_id);
5292 #endif
5293 puts(onion_c_id);
5294 puts(policies_c_id);
5295 puts(relay_c_id);
5296 puts(rendclient_c_id);
5297 puts(rendcommon_c_id);
5298 puts(rendmid_c_id);
5299 puts(rendservice_c_id);
5300 puts(rephist_c_id);
5301 puts(router_c_id);
5302 puts(routerlist_c_id);
5303 puts(routerparse_c_id);