Add support for a new option: FetchDirInfoExtraEarly
[tor.git] / src / or / config.c
blob5495b252cbaf001067729562464207da8d9b1570
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-2009, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file config.c
9 * \brief Code to parse and interpret configuration files.
10 **/
12 #define CONFIG_PRIVATE
14 #include "or.h"
15 #ifdef MS_WINDOWS
16 #include <shlobj.h>
17 #endif
19 /** Enumeration of types which option values can take */
20 typedef enum config_type_t {
21 CONFIG_TYPE_STRING = 0, /**< An arbitrary string. */
22 CONFIG_TYPE_FILENAME, /**< A filename: some prefixes get expanded. */
23 CONFIG_TYPE_UINT, /**< A non-negative integer less than MAX_INT */
24 CONFIG_TYPE_INTERVAL, /**< A number of seconds, with optional units*/
25 CONFIG_TYPE_MEMUNIT, /**< A number of bytes, with optional units*/
26 CONFIG_TYPE_DOUBLE, /**< A floating-point value */
27 CONFIG_TYPE_BOOL, /**< A boolean value, expressed as 0 or 1. */
28 CONFIG_TYPE_ISOTIME, /**< An ISO-formatted time relative to GMT. */
29 CONFIG_TYPE_CSV, /**< A list of strings, separated by commas and
30 * optional whitespace. */
31 CONFIG_TYPE_LINELIST, /**< Uninterpreted config lines */
32 CONFIG_TYPE_LINELIST_S, /**< Uninterpreted, context-sensitive config lines,
33 * mixed with other keywords. */
34 CONFIG_TYPE_LINELIST_V, /**< Catch-all "virtual" option to summarize
35 * context-sensitive config lines when fetching.
37 CONFIG_TYPE_ROUTERSET, /**< A list of router names, addrs, and fps,
38 * parsed into a routerset_t. */
39 CONFIG_TYPE_OBSOLETE, /**< Obsolete (ignored) option. */
40 } config_type_t;
42 /** An abbreviation for a configuration option allowed on the command line. */
43 typedef struct config_abbrev_t {
44 const char *abbreviated;
45 const char *full;
46 int commandline_only;
47 int warn;
48 } config_abbrev_t;
50 /* Handy macro for declaring "In the config file or on the command line,
51 * you can abbreviate <b>tok</b>s as <b>tok</b>". */
52 #define PLURAL(tok) { #tok, #tok "s", 0, 0 }
54 /** A list of abbreviations and aliases to map command-line options, obsolete
55 * option names, or alternative option names, to their current values. */
56 static config_abbrev_t _option_abbrevs[] = {
57 PLURAL(ExitNode),
58 PLURAL(EntryNode),
59 PLURAL(ExcludeNode),
60 PLURAL(FirewallPort),
61 PLURAL(LongLivedPort),
62 PLURAL(HiddenServiceNode),
63 PLURAL(HiddenServiceExcludeNode),
64 PLURAL(NumCpu),
65 PLURAL(RendNode),
66 PLURAL(RendExcludeNode),
67 PLURAL(StrictEntryNode),
68 PLURAL(StrictExitNode),
69 { "l", "Log", 1, 0},
70 { "AllowUnverifiedNodes", "AllowInvalidNodes", 0, 0},
71 { "AutomapHostSuffixes", "AutomapHostsSuffixes", 0, 0},
72 { "AutomapHostOnResolve", "AutomapHostsOnResolve", 0, 0},
73 { "BandwidthRateBytes", "BandwidthRate", 0, 0},
74 { "BandwidthBurstBytes", "BandwidthBurst", 0, 0},
75 { "DirFetchPostPeriod", "StatusFetchPeriod", 0, 0},
76 { "MaxConn", "ConnLimit", 0, 1},
77 { "ORBindAddress", "ORListenAddress", 0, 0},
78 { "DirBindAddress", "DirListenAddress", 0, 0},
79 { "SocksBindAddress", "SocksListenAddress", 0, 0},
80 { "UseHelperNodes", "UseEntryGuards", 0, 0},
81 { "NumHelperNodes", "NumEntryGuards", 0, 0},
82 { "UseEntryNodes", "UseEntryGuards", 0, 0},
83 { "NumEntryNodes", "NumEntryGuards", 0, 0},
84 { "ResolvConf", "ServerDNSResolvConfFile", 0, 1},
85 { "SearchDomains", "ServerDNSSearchDomains", 0, 1},
86 { "ServerDNSAllowBrokenResolvConf", "ServerDNSAllowBrokenConfig", 0, 0 },
87 { "PreferTunnelledDirConns", "PreferTunneledDirConns", 0, 0},
88 { "BridgeAuthoritativeDirectory", "BridgeAuthoritativeDir", 0, 0},
89 { "HashedControlPassword", "__HashedControlSessionPassword", 1, 0},
90 { NULL, NULL, 0, 0},
93 /** A list of state-file "abbreviations," for compatibility. */
94 static config_abbrev_t _state_abbrevs[] = {
95 { "AccountingBytesReadInterval", "AccountingBytesReadInInterval", 0, 0 },
96 { "HelperNode", "EntryGuard", 0, 0 },
97 { "HelperNodeDownSince", "EntryGuardDownSince", 0, 0 },
98 { "HelperNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
99 { "EntryNode", "EntryGuard", 0, 0 },
100 { "EntryNodeDownSince", "EntryGuardDownSince", 0, 0 },
101 { "EntryNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
102 { NULL, NULL, 0, 0},
104 #undef PLURAL
106 /** A variable allowed in the configuration file or on the command line. */
107 typedef struct config_var_t {
108 const char *name; /**< The full keyword (case insensitive). */
109 config_type_t type; /**< How to interpret the type and turn it into a
110 * value. */
111 off_t var_offset; /**< Offset of the corresponding member of or_options_t. */
112 const char *initvalue; /**< String (or null) describing initial value. */
113 } config_var_t;
115 /** An entry for config_vars: "The option <b>name</b> has type
116 * CONFIG_TYPE_<b>conftype</b>, and corresponds to
117 * or_options_t.<b>member</b>"
119 #define VAR(name,conftype,member,initvalue) \
120 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_options_t, member), \
121 initvalue }
122 /** As VAR, but the option name and member name are the same. */
123 #define V(member,conftype,initvalue) \
124 VAR(#member, conftype, member, initvalue)
125 /** An entry for config_vars: "The option <b>name</b> is obsolete." */
126 #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL }
128 /** Array of configuration options. Until we disallow nonstandard
129 * abbreviations, order is significant, since the first matching option will
130 * be chosen first.
132 static config_var_t _option_vars[] = {
133 OBSOLETE("AccountingMaxKB"),
134 V(AccountingMax, MEMUNIT, "0 bytes"),
135 V(AccountingStart, STRING, NULL),
136 V(Address, STRING, NULL),
137 V(AllowInvalidNodes, CSV, "middle,rendezvous"),
138 V(AllowNonRFC953Hostnames, BOOL, "0"),
139 V(AllowSingleHopCircuits, BOOL, "0"),
140 V(AllowSingleHopExits, BOOL, "0"),
141 V(AlternateBridgeAuthority, LINELIST, NULL),
142 V(AlternateDirAuthority, LINELIST, NULL),
143 V(AlternateHSAuthority, LINELIST, NULL),
144 V(AssumeReachable, BOOL, "0"),
145 V(AuthDirBadDir, LINELIST, NULL),
146 V(AuthDirBadExit, LINELIST, NULL),
147 V(AuthDirInvalid, LINELIST, NULL),
148 V(AuthDirReject, LINELIST, NULL),
149 V(AuthDirRejectUnlisted, BOOL, "0"),
150 V(AuthDirListBadDirs, BOOL, "0"),
151 V(AuthDirListBadExits, BOOL, "0"),
152 V(AuthDirMaxServersPerAddr, UINT, "2"),
153 V(AuthDirMaxServersPerAuthAddr,UINT, "5"),
154 VAR("AuthoritativeDirectory", BOOL, AuthoritativeDir, "0"),
155 V(AutomapHostsOnResolve, BOOL, "0"),
156 V(AutomapHostsSuffixes, CSV, ".onion,.exit"),
157 V(AvoidDiskWrites, BOOL, "0"),
158 V(BandwidthBurst, MEMUNIT, "10 MB"),
159 V(BandwidthRate, MEMUNIT, "5 MB"),
160 V(BridgeAuthoritativeDir, BOOL, "0"),
161 VAR("Bridge", LINELIST, Bridges, NULL),
162 V(BridgePassword, STRING, NULL),
163 V(BridgeRecordUsageByCountry, BOOL, "1"),
164 V(BridgeRelay, BOOL, "0"),
165 V(CellStatistics, BOOL, "0"),
166 V(CircuitBuildTimeout, INTERVAL, "1 minute"),
167 V(CircuitIdleTimeout, INTERVAL, "1 hour"),
168 V(ClientDNSRejectInternalAddresses, BOOL,"1"),
169 V(ClientOnly, BOOL, "0"),
170 V(ConnLimit, UINT, "1000"),
171 V(ConstrainedSockets, BOOL, "0"),
172 V(ConstrainedSockSize, MEMUNIT, "8192"),
173 V(ContactInfo, STRING, NULL),
174 V(ControlListenAddress, LINELIST, NULL),
175 V(ControlPort, UINT, "0"),
176 V(ControlSocket, LINELIST, NULL),
177 V(CookieAuthentication, BOOL, "0"),
178 V(CookieAuthFileGroupReadable, BOOL, "0"),
179 V(CookieAuthFile, STRING, NULL),
180 V(DataDirectory, FILENAME, NULL),
181 OBSOLETE("DebugLogFile"),
182 V(DirAllowPrivateAddresses, BOOL, NULL),
183 V(TestingAuthDirTimeToLearnReachability, INTERVAL, "30 minutes"),
184 V(DirListenAddress, LINELIST, NULL),
185 OBSOLETE("DirFetchPeriod"),
186 V(DirPolicy, LINELIST, NULL),
187 V(DirPort, UINT, "0"),
188 V(DirPortFrontPage, FILENAME, NULL),
189 OBSOLETE("DirPostPeriod"),
190 #ifdef ENABLE_GEOIP_STATS
191 OBSOLETE("DirRecordUsageByCountry"),
192 OBSOLETE("DirRecordUsageGranularity"),
193 OBSOLETE("DirRecordUsageRetainIPs"),
194 OBSOLETE("DirRecordUsageSaveInterval"),
195 #endif
196 VAR("DirServer", LINELIST, DirServers, NULL),
197 V(DNSPort, UINT, "0"),
198 V(DNSListenAddress, LINELIST, NULL),
199 V(DownloadExtraInfo, BOOL, "0"),
200 V(EnforceDistinctSubnets, BOOL, "1"),
201 V(EntryNodes, ROUTERSET, NULL),
202 V(EntryStatistics, BOOL, "0"),
203 V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "10 minutes"),
204 V(ExcludeNodes, ROUTERSET, NULL),
205 V(ExcludeExitNodes, ROUTERSET, NULL),
206 V(ExcludeSingleHopRelays, BOOL, "1"),
207 V(ExitNodes, ROUTERSET, NULL),
208 V(ExitPolicy, LINELIST, NULL),
209 V(ExitPolicyRejectPrivate, BOOL, "1"),
210 V(ExitPortStatistics, BOOL, "0"),
211 V(FallbackNetworkstatusFile, FILENAME,
212 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "fallback-consensus"),
213 V(FascistFirewall, BOOL, "0"),
214 V(FirewallPorts, CSV, ""),
215 V(FastFirstHopPK, BOOL, "1"),
216 V(FetchDirInfoEarly, BOOL, "0"),
217 V(FetchDirInfoExtraEarly, BOOL, "0"),
218 V(FetchServerDescriptors, BOOL, "1"),
219 V(FetchHidServDescriptors, BOOL, "1"),
220 V(FetchUselessDescriptors, BOOL, "0"),
221 #ifdef WIN32
222 V(GeoIPFile, FILENAME, "<default>"),
223 #else
224 V(GeoIPFile, FILENAME,
225 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip"),
226 #endif
227 OBSOLETE("Group"),
228 V(HardwareAccel, BOOL, "0"),
229 V(AccelName, STRING, NULL),
230 V(AccelDir, FILENAME, NULL),
231 V(HashedControlPassword, LINELIST, NULL),
232 V(HidServDirectoryV2, BOOL, "1"),
233 VAR("HiddenServiceDir", LINELIST_S, RendConfigLines, NULL),
234 OBSOLETE("HiddenServiceExcludeNodes"),
235 OBSOLETE("HiddenServiceNodes"),
236 VAR("HiddenServiceOptions",LINELIST_V, RendConfigLines, NULL),
237 VAR("HiddenServicePort", LINELIST_S, RendConfigLines, NULL),
238 VAR("HiddenServiceVersion",LINELIST_S, RendConfigLines, NULL),
239 VAR("HiddenServiceAuthorizeClient",LINELIST_S,RendConfigLines, NULL),
240 V(HidServAuth, LINELIST, NULL),
241 V(HSAuthoritativeDir, BOOL, "0"),
242 V(HSAuthorityRecordStats, BOOL, "0"),
243 V(HttpProxy, STRING, NULL),
244 V(HttpProxyAuthenticator, STRING, NULL),
245 V(HttpsProxy, STRING, NULL),
246 V(HttpsProxyAuthenticator, STRING, NULL),
247 OBSOLETE("IgnoreVersion"),
248 V(KeepalivePeriod, INTERVAL, "5 minutes"),
249 VAR("Log", LINELIST, Logs, NULL),
250 OBSOLETE("LinkPadding"),
251 OBSOLETE("LogLevel"),
252 OBSOLETE("LogFile"),
253 V(LongLivedPorts, CSV,
254 "21,22,706,1863,5050,5190,5222,5223,6667,6697,8300"),
255 VAR("MapAddress", LINELIST, AddressMap, NULL),
256 V(MaxAdvertisedBandwidth, MEMUNIT, "1 GB"),
257 V(MaxCircuitDirtiness, INTERVAL, "10 minutes"),
258 V(MaxOnionsPending, UINT, "100"),
259 OBSOLETE("MonthlyAccountingStart"),
260 V(MyFamily, STRING, NULL),
261 V(NewCircuitPeriod, INTERVAL, "30 seconds"),
262 VAR("NamingAuthoritativeDirectory",BOOL, NamingAuthoritativeDir, "0"),
263 V(NatdListenAddress, LINELIST, NULL),
264 V(NatdPort, UINT, "0"),
265 V(Nickname, STRING, NULL),
266 V(NoPublish, BOOL, "0"),
267 VAR("NodeFamily", LINELIST, NodeFamilies, NULL),
268 V(NumCpus, UINT, "1"),
269 V(NumEntryGuards, UINT, "3"),
270 V(ORListenAddress, LINELIST, NULL),
271 V(ORPort, UINT, "0"),
272 V(OutboundBindAddress, STRING, NULL),
273 OBSOLETE("PathlenCoinWeight"),
274 V(PidFile, STRING, NULL),
275 V(TestingTorNetwork, BOOL, "0"),
276 V(PreferTunneledDirConns, BOOL, "1"),
277 V(ProtocolWarnings, BOOL, "0"),
278 V(PublishServerDescriptor, CSV, "1"),
279 V(PublishHidServDescriptors, BOOL, "1"),
280 V(ReachableAddresses, LINELIST, NULL),
281 V(ReachableDirAddresses, LINELIST, NULL),
282 V(ReachableORAddresses, LINELIST, NULL),
283 V(RecommendedVersions, LINELIST, NULL),
284 V(RecommendedClientVersions, LINELIST, NULL),
285 V(RecommendedServerVersions, LINELIST, NULL),
286 OBSOLETE("RedirectExit"),
287 V(RejectPlaintextPorts, CSV, ""),
288 V(RelayBandwidthBurst, MEMUNIT, "0"),
289 V(RelayBandwidthRate, MEMUNIT, "0"),
290 OBSOLETE("RendExcludeNodes"),
291 OBSOLETE("RendNodes"),
292 V(RendPostPeriod, INTERVAL, "1 hour"),
293 V(RephistTrackTime, INTERVAL, "24 hours"),
294 OBSOLETE("RouterFile"),
295 V(RunAsDaemon, BOOL, "0"),
296 V(RunTesting, BOOL, "0"),
297 V(SafeLogging, BOOL, "1"),
298 V(SafeSocks, BOOL, "0"),
299 V(ServerDNSAllowBrokenConfig, BOOL, "1"),
300 V(ServerDNSAllowNonRFC953Hostnames, BOOL,"0"),
301 V(ServerDNSDetectHijacking, BOOL, "1"),
302 V(ServerDNSRandomizeCase, BOOL, "1"),
303 V(ServerDNSResolvConfFile, STRING, NULL),
304 V(ServerDNSSearchDomains, BOOL, "0"),
305 V(ServerDNSTestAddresses, CSV,
306 "www.google.com,www.mit.edu,www.yahoo.com,www.slashdot.org"),
307 V(ShutdownWaitLength, INTERVAL, "30 seconds"),
308 V(SocksListenAddress, LINELIST, NULL),
309 V(SocksPolicy, LINELIST, NULL),
310 V(SocksPort, UINT, "9050"),
311 V(SocksTimeout, INTERVAL, "2 minutes"),
312 OBSOLETE("StatusFetchPeriod"),
313 V(StrictEntryNodes, BOOL, "0"),
314 V(StrictExitNodes, BOOL, "0"),
315 OBSOLETE("SysLog"),
316 V(TestSocks, BOOL, "0"),
317 OBSOLETE("TestVia"),
318 V(TrackHostExits, CSV, NULL),
319 V(TrackHostExitsExpire, INTERVAL, "30 minutes"),
320 OBSOLETE("TrafficShaping"),
321 V(TransListenAddress, LINELIST, NULL),
322 V(TransPort, UINT, "0"),
323 V(TunnelDirConns, BOOL, "1"),
324 V(UpdateBridgesFromAuthority, BOOL, "0"),
325 V(UseBridges, BOOL, "0"),
326 V(UseEntryGuards, BOOL, "1"),
327 V(User, STRING, NULL),
328 VAR("V1AuthoritativeDirectory",BOOL, V1AuthoritativeDir, "0"),
329 VAR("V2AuthoritativeDirectory",BOOL, V2AuthoritativeDir, "0"),
330 VAR("V3AuthoritativeDirectory",BOOL, V3AuthoritativeDir, "0"),
331 V(TestingV3AuthInitialVotingInterval, INTERVAL, "30 minutes"),
332 V(TestingV3AuthInitialVoteDelay, INTERVAL, "5 minutes"),
333 V(TestingV3AuthInitialDistDelay, INTERVAL, "5 minutes"),
334 V(V3AuthVotingInterval, INTERVAL, "1 hour"),
335 V(V3AuthVoteDelay, INTERVAL, "5 minutes"),
336 V(V3AuthDistDelay, INTERVAL, "5 minutes"),
337 V(V3AuthNIntervalsValid, UINT, "3"),
338 V(V3AuthUseLegacyKey, BOOL, "0"),
339 VAR("VersioningAuthoritativeDirectory",BOOL,VersioningAuthoritativeDir, "0"),
340 V(VirtualAddrNetwork, STRING, "127.192.0.0/10"),
341 V(WarnPlaintextPorts, CSV, "23,109,110,143"),
342 VAR("__ReloadTorrcOnSIGHUP", BOOL, ReloadTorrcOnSIGHUP, "1"),
343 VAR("__AllDirActionsPrivate", BOOL, AllDirActionsPrivate, "0"),
344 VAR("__DisablePredictedCircuits",BOOL,DisablePredictedCircuits, "0"),
345 VAR("__LeaveStreamsUnattached",BOOL, LeaveStreamsUnattached, "0"),
346 VAR("__HashedControlSessionPassword", LINELIST, HashedControlSessionPassword,
347 NULL),
348 V(MinUptimeHidServDirectoryV2, INTERVAL, "24 hours"),
349 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
352 /** Override default values with these if the user sets the TestingTorNetwork
353 * option. */
354 static config_var_t testing_tor_network_defaults[] = {
355 V(ServerDNSAllowBrokenConfig, BOOL, "1"),
356 V(DirAllowPrivateAddresses, BOOL, "1"),
357 V(EnforceDistinctSubnets, BOOL, "0"),
358 V(AssumeReachable, BOOL, "1"),
359 V(AuthDirMaxServersPerAddr, UINT, "0"),
360 V(AuthDirMaxServersPerAuthAddr,UINT, "0"),
361 V(ClientDNSRejectInternalAddresses, BOOL,"0"),
362 V(ExitPolicyRejectPrivate, BOOL, "0"),
363 V(V3AuthVotingInterval, INTERVAL, "5 minutes"),
364 V(V3AuthVoteDelay, INTERVAL, "20 seconds"),
365 V(V3AuthDistDelay, INTERVAL, "20 seconds"),
366 V(TestingV3AuthInitialVotingInterval, INTERVAL, "5 minutes"),
367 V(TestingV3AuthInitialVoteDelay, INTERVAL, "20 seconds"),
368 V(TestingV3AuthInitialDistDelay, INTERVAL, "20 seconds"),
369 V(TestingAuthDirTimeToLearnReachability, INTERVAL, "0 minutes"),
370 V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "0 minutes"),
371 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
373 #undef VAR
375 #define VAR(name,conftype,member,initvalue) \
376 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_state_t, member), \
377 initvalue }
379 /** Array of "state" variables saved to the ~/.tor/state file. */
380 static config_var_t _state_vars[] = {
381 V(AccountingBytesReadInInterval, MEMUNIT, NULL),
382 V(AccountingBytesWrittenInInterval, MEMUNIT, NULL),
383 V(AccountingExpectedUsage, MEMUNIT, NULL),
384 V(AccountingIntervalStart, ISOTIME, NULL),
385 V(AccountingSecondsActive, INTERVAL, NULL),
387 VAR("EntryGuard", LINELIST_S, EntryGuards, NULL),
388 VAR("EntryGuardDownSince", LINELIST_S, EntryGuards, NULL),
389 VAR("EntryGuardUnlistedSince", LINELIST_S, EntryGuards, NULL),
390 VAR("EntryGuardAddedBy", LINELIST_S, EntryGuards, NULL),
391 V(EntryGuards, LINELIST_V, NULL),
393 V(BWHistoryReadEnds, ISOTIME, NULL),
394 V(BWHistoryReadInterval, UINT, "900"),
395 V(BWHistoryReadValues, CSV, ""),
396 V(BWHistoryWriteEnds, ISOTIME, NULL),
397 V(BWHistoryWriteInterval, UINT, "900"),
398 V(BWHistoryWriteValues, CSV, ""),
400 V(TorVersion, STRING, NULL),
402 V(LastRotatedOnionKey, ISOTIME, NULL),
403 V(LastWritten, ISOTIME, NULL),
405 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
408 #undef VAR
409 #undef V
410 #undef OBSOLETE
412 /** Represents an English description of a configuration variable; used when
413 * generating configuration file comments. */
414 typedef struct config_var_description_t {
415 const char *name;
416 const char *description;
417 } config_var_description_t;
419 /** Descriptions of the configuration options, to be displayed by online
420 * option browsers */
421 /* XXXX022 did anybody want this? at all? If not, kill it.*/
422 static config_var_description_t options_description[] = {
423 /* ==== general options */
424 { "AvoidDiskWrites", "If non-zero, try to write to disk less frequently than"
425 " we would otherwise." },
426 { "BandwidthRate", "A token bucket limits the average incoming bandwidth on "
427 "this node to the specified number of bytes per second." },
428 { "BandwidthBurst", "Limit the maximum token buffer size (also known as "
429 "burst) to the given number of bytes." },
430 { "ConnLimit", "Minimum number of simultaneous sockets we must have." },
431 { "ConstrainedSockets", "Shrink tx and rx buffers for sockets to avoid "
432 "system limits on vservers and related environments. See man page for "
433 "more information regarding this option." },
434 { "ConstrainedSockSize", "Limit socket buffers to this size when "
435 "ConstrainedSockets is enabled." },
436 /* ControlListenAddress */
437 { "ControlPort", "If set, Tor will accept connections from the same machine "
438 "(localhost only) on this port, and allow those connections to control "
439 "the Tor process using the Tor Control Protocol (described in "
440 "control-spec.txt).", },
441 { "CookieAuthentication", "If this option is set to 1, don't allow any "
442 "connections to the control port except when the connecting process "
443 "can read a file that Tor creates in its data directory." },
444 { "DataDirectory", "Store working data, state, keys, and caches here." },
445 { "DirServer", "Tor only trusts directories signed with one of these "
446 "servers' keys. Used to override the standard list of directory "
447 "authorities." },
448 /* { "FastFirstHopPK", "" }, */
449 /* FetchServerDescriptors, FetchHidServDescriptors,
450 * FetchUselessDescriptors */
451 { "HardwareAccel", "If set, Tor tries to use hardware crypto accelerators "
452 "when it can." },
453 { "AccelName", "If set, try to use hardware crypto accelerator with this "
454 "specific ID." },
455 { "AccelDir", "If set, look in this directory for the dynamic hardware "
456 "engine in addition to OpenSSL default path." },
457 /* HashedControlPassword */
458 { "HTTPProxy", "Force Tor to make all HTTP directory requests through this "
459 "host:port (or host:80 if port is not set)." },
460 { "HTTPProxyAuthenticator", "A username:password pair to be used with "
461 "HTTPProxy." },
462 { "HTTPSProxy", "Force Tor to make all TLS (SSL) connections through this "
463 "host:port (or host:80 if port is not set)." },
464 { "HTTPSProxyAuthenticator", "A username:password pair to be used with "
465 "HTTPSProxy." },
466 { "KeepalivePeriod", "Send a padding cell every N seconds to keep firewalls "
467 "from closing our connections while Tor is not in use." },
468 { "Log", "Where to send logging messages. Format is "
469 "minSeverity[-maxSeverity] (stderr|stdout|syslog|file FILENAME)." },
470 { "OutboundBindAddress", "Make all outbound connections originate from the "
471 "provided IP address (only useful for multiple network interfaces)." },
472 { "PIDFile", "On startup, write our PID to this file. On clean shutdown, "
473 "remove the file." },
474 { "PreferTunneledDirConns", "If non-zero, avoid directory servers that "
475 "don't support tunneled connections." },
476 /* PreferTunneledDirConns */
477 /* ProtocolWarnings */
478 /* RephistTrackTime */
479 { "RunAsDaemon", "If set, Tor forks and daemonizes to the background when "
480 "started. Unix only." },
481 { "SafeLogging", "If set to 0, Tor logs potentially sensitive strings "
482 "rather than replacing them with the string [scrubbed]." },
483 { "TunnelDirConns", "If non-zero, when a directory server we contact "
484 "supports it, we will build a one-hop circuit and make an encrypted "
485 "connection via its ORPort." },
486 { "User", "On startup, setuid to this user." },
488 /* ==== client options */
489 { "AllowInvalidNodes", "Where on our circuits should Tor allow servers "
490 "that the directory authorities haven't called \"valid\"?" },
491 { "AllowNonRFC953Hostnames", "If set to 1, we don't automatically reject "
492 "hostnames for having invalid characters." },
493 /* CircuitBuildTimeout, CircuitIdleTimeout */
494 { "ClientOnly", "If set to 1, Tor will under no circumstances run as a "
495 "server, even if ORPort is enabled." },
496 { "EntryNodes", "A list of preferred entry nodes to use for the first hop "
497 "in circuits, when possible." },
498 /* { "EnforceDistinctSubnets" , "" }, */
499 { "ExitNodes", "A list of preferred nodes to use for the last hop in "
500 "circuits, when possible." },
501 { "ExcludeNodes", "A list of nodes never to use when building a circuit." },
502 { "FascistFirewall", "If set, Tor will only create outgoing connections to "
503 "servers running on the ports listed in FirewallPorts." },
504 { "FirewallPorts", "A list of ports that we can connect to. Only used "
505 "when FascistFirewall is set." },
506 { "LongLivedPorts", "A list of ports for services that tend to require "
507 "high-uptime connections." },
508 { "MapAddress", "Force Tor to treat all requests for one address as if "
509 "they were for another." },
510 { "NewCircuitPeriod", "Force Tor to consider whether to build a new circuit "
511 "every NUM seconds." },
512 { "MaxCircuitDirtiness", "Do not attach new streams to a circuit that has "
513 "been used more than this many seconds ago." },
514 /* NatdPort, NatdListenAddress */
515 { "NodeFamily", "A list of servers that constitute a 'family' and should "
516 "never be used in the same circuit." },
517 { "NumEntryGuards", "How many entry guards should we keep at a time?" },
518 /* PathlenCoinWeight */
519 { "ReachableAddresses", "Addresses we can connect to, as IP/bits:port-port. "
520 "By default, we assume all addresses are reachable." },
521 /* reachablediraddresses, reachableoraddresses. */
522 /* SafeSOCKS */
523 { "SOCKSPort", "The port where we listen for SOCKS connections from "
524 "applications." },
525 { "SOCKSListenAddress", "Bind to this address to listen to connections from "
526 "SOCKS-speaking applications." },
527 { "SOCKSPolicy", "Set an entry policy to limit which addresses can connect "
528 "to the SOCKSPort." },
529 /* SocksTimeout */
530 { "StrictExitNodes", "If set, Tor will fail to operate when none of the "
531 "configured ExitNodes can be used." },
532 { "StrictEntryNodes", "If set, Tor will fail to operate when none of the "
533 "configured EntryNodes can be used." },
534 /* TestSocks */
535 { "TrackHostsExit", "Hosts and domains which should, if possible, be "
536 "accessed from the same exit node each time we connect to them." },
537 { "TrackHostsExitExpire", "Time after which we forget which exit we were "
538 "using to connect to hosts in TrackHostsExit." },
539 /* "TransPort", "TransListenAddress */
540 { "UseEntryGuards", "Set to 0 if we want to pick from the whole set of "
541 "servers for the first position in each circuit, rather than picking a "
542 "set of 'Guards' to prevent profiling attacks." },
544 /* === server options */
545 { "Address", "The advertised (external) address we should use." },
546 /* Accounting* options. */
547 /* AssumeReachable */
548 { "ContactInfo", "Administrative contact information to advertise for this "
549 "server." },
550 { "ExitPolicy", "Address/port ranges for which to accept or reject outgoing "
551 "connections on behalf of Tor users." },
552 /* { "ExitPolicyRejectPrivate, "" }, */
553 { "MaxAdvertisedBandwidth", "If set, we will not advertise more than this "
554 "amount of bandwidth for our bandwidth rate, regardless of how much "
555 "bandwidth we actually detect." },
556 { "MaxOnionsPending", "Reject new attempts to extend circuits when we "
557 "already have this many pending." },
558 { "MyFamily", "Declare a list of other servers as belonging to the same "
559 "family as this one, so that clients will not use two from the same "
560 "family in the same circuit." },
561 { "Nickname", "Set the server nickname." },
562 { "NoPublish", "{DEPRECATED}" },
563 { "NumCPUs", "How many processes to use at once for public-key crypto." },
564 { "ORPort", "Advertise this port to listen for connections from Tor clients "
565 "and servers." },
566 { "ORListenAddress", "Bind to this address to listen for connections from "
567 "clients and servers, instead of the default 0.0.0.0:ORPort." },
568 { "PublishServerDescriptor", "Set to 0 to keep the server from "
569 "uploading info to the directory authorities." },
570 /* ServerDNS: DetectHijacking, ResolvConfFile, SearchDomains */
571 { "ShutdownWaitLength", "Wait this long for clients to finish when "
572 "shutting down because of a SIGINT." },
574 /* === directory cache options */
575 { "DirPort", "Serve directory information from this port, and act as a "
576 "directory cache." },
577 { "DirPortFrontPage", "Serve a static html disclaimer on DirPort." },
578 { "DirListenAddress", "Bind to this address to listen for connections from "
579 "clients and servers, instead of the default 0.0.0.0:DirPort." },
580 { "DirPolicy", "Set a policy to limit who can connect to the directory "
581 "port." },
583 /* Authority options: AuthDirBadExit, AuthDirInvalid, AuthDirReject,
584 * AuthDirRejectUnlisted, AuthDirListBadExits, AuthoritativeDirectory,
585 * DirAllowPrivateAddresses, HSAuthoritativeDir,
586 * NamingAuthoritativeDirectory, RecommendedVersions,
587 * RecommendedClientVersions, RecommendedServerVersions, RendPostPeriod,
588 * RunTesting, V1AuthoritativeDirectory, VersioningAuthoritativeDirectory, */
590 /* Hidden service options: HiddenService: dir,excludenodes, nodes,
591 * options, port. PublishHidServDescriptor */
593 /* Nonpersistent options: __LeaveStreamsUnattached, __AllDirActionsPrivate */
594 { NULL, NULL },
597 /** Online description of state variables. */
598 static config_var_description_t state_description[] = {
599 { "AccountingBytesReadInInterval",
600 "How many bytes have we read in this accounting period?" },
601 { "AccountingBytesWrittenInInterval",
602 "How many bytes have we written in this accounting period?" },
603 { "AccountingExpectedUsage",
604 "How many bytes did we expect to use per minute? (0 for no estimate.)" },
605 { "AccountingIntervalStart", "When did this accounting period begin?" },
606 { "AccountingSecondsActive", "How long have we been awake in this period?" },
608 { "BWHistoryReadEnds", "When does the last-recorded read-interval end?" },
609 { "BWHistoryReadInterval", "How long is each read-interval (in seconds)?" },
610 { "BWHistoryReadValues", "Number of bytes read in each interval." },
611 { "BWHistoryWriteEnds", "When does the last-recorded write-interval end?" },
612 { "BWHistoryWriteInterval", "How long is each write-interval (in seconds)?"},
613 { "BWHistoryWriteValues", "Number of bytes written in each interval." },
615 { "EntryGuard", "One of the nodes we have chosen as a fixed entry" },
616 { "EntryGuardDownSince",
617 "The last entry guard has been unreachable since this time." },
618 { "EntryGuardUnlistedSince",
619 "The last entry guard has been unusable since this time." },
621 { "LastRotatedOnionKey",
622 "The last time at which we changed the medium-term private key used for "
623 "building circuits." },
624 { "LastWritten", "When was this state file last regenerated?" },
626 { "TorVersion", "Which version of Tor generated this state file?" },
627 { NULL, NULL },
630 /** Type of a callback to validate whether a given configuration is
631 * well-formed and consistent. See options_trial_assign() for documentation
632 * of arguments. */
633 typedef int (*validate_fn_t)(void*,void*,int,char**);
635 /** Information on the keys, value types, key-to-struct-member mappings,
636 * variable descriptions, validation functions, and abbreviations for a
637 * configuration or storage format. */
638 typedef struct {
639 size_t size; /**< Size of the struct that everything gets parsed into. */
640 uint32_t magic; /**< Required 'magic value' to make sure we have a struct
641 * of the right type. */
642 off_t magic_offset; /**< Offset of the magic value within the struct. */
643 config_abbrev_t *abbrevs; /**< List of abbreviations that we expand when
644 * parsing this format. */
645 config_var_t *vars; /**< List of variables we recognize, their default
646 * values, and where we stick them in the structure. */
647 validate_fn_t validate_fn; /**< Function to validate config. */
648 /** Documentation for configuration variables. */
649 config_var_description_t *descriptions;
650 /** If present, extra is a LINELIST variable for unrecognized
651 * lines. Otherwise, unrecognized lines are an error. */
652 config_var_t *extra;
653 } config_format_t;
655 /** Macro: assert that <b>cfg</b> has the right magic field for format
656 * <b>fmt</b>. */
657 #define CHECK(fmt, cfg) STMT_BEGIN \
658 tor_assert(fmt && cfg); \
659 tor_assert((fmt)->magic == \
660 *(uint32_t*)STRUCT_VAR_P(cfg,fmt->magic_offset)); \
661 STMT_END
663 #ifdef MS_WINDOWS
664 static char *get_windows_conf_root(void);
665 #endif
666 static void config_line_append(config_line_t **lst,
667 const char *key, const char *val);
668 static void option_clear(config_format_t *fmt, or_options_t *options,
669 config_var_t *var);
670 static void option_reset(config_format_t *fmt, or_options_t *options,
671 config_var_t *var, int use_defaults);
672 static void config_free(config_format_t *fmt, void *options);
673 static int config_lines_eq(config_line_t *a, config_line_t *b);
674 static int option_is_same(config_format_t *fmt,
675 or_options_t *o1, or_options_t *o2,
676 const char *name);
677 static or_options_t *options_dup(config_format_t *fmt, or_options_t *old);
678 static int options_validate(or_options_t *old_options, or_options_t *options,
679 int from_setconf, char **msg);
680 static int options_act_reversible(or_options_t *old_options, char **msg);
681 static int options_act(or_options_t *old_options);
682 static int options_transition_allowed(or_options_t *old, or_options_t *new,
683 char **msg);
684 static int options_transition_affects_workers(or_options_t *old_options,
685 or_options_t *new_options);
686 static int options_transition_affects_descriptor(or_options_t *old_options,
687 or_options_t *new_options);
688 static int check_nickname_list(const char *lst, const char *name, char **msg);
689 static void config_register_addressmaps(or_options_t *options);
691 static int parse_bridge_line(const char *line, int validate_only);
692 static int parse_dir_server_line(const char *line,
693 authority_type_t required_type,
694 int validate_only);
695 static int validate_data_directory(or_options_t *options);
696 static int write_configuration_file(const char *fname, or_options_t *options);
697 static config_line_t *get_assigned_option(config_format_t *fmt,
698 void *options, const char *key,
699 int escape_val);
700 static void config_init(config_format_t *fmt, void *options);
701 static int or_state_validate(or_state_t *old_options, or_state_t *options,
702 int from_setconf, char **msg);
703 static int or_state_load(void);
704 static int options_init_logs(or_options_t *options, int validate_only);
706 static int is_listening_on_low_port(uint16_t port_option,
707 const config_line_t *listen_options);
709 static uint64_t config_parse_memunit(const char *s, int *ok);
710 static int config_parse_interval(const char *s, int *ok);
711 static void init_libevent(void);
712 static int opt_streq(const char *s1, const char *s2);
714 /** Magic value for or_options_t. */
715 #define OR_OPTIONS_MAGIC 9090909
717 /** Configuration format for or_options_t. */
718 static config_format_t options_format = {
719 sizeof(or_options_t),
720 OR_OPTIONS_MAGIC,
721 STRUCT_OFFSET(or_options_t, _magic),
722 _option_abbrevs,
723 _option_vars,
724 (validate_fn_t)options_validate,
725 options_description,
726 NULL
729 /** Magic value for or_state_t. */
730 #define OR_STATE_MAGIC 0x57A73f57
732 /** "Extra" variable in the state that receives lines we can't parse. This
733 * lets us preserve options from versions of Tor newer than us. */
734 static config_var_t state_extra_var = {
735 "__extra", CONFIG_TYPE_LINELIST, STRUCT_OFFSET(or_state_t, ExtraLines), NULL
738 /** Configuration format for or_state_t. */
739 static config_format_t state_format = {
740 sizeof(or_state_t),
741 OR_STATE_MAGIC,
742 STRUCT_OFFSET(or_state_t, _magic),
743 _state_abbrevs,
744 _state_vars,
745 (validate_fn_t)or_state_validate,
746 state_description,
747 &state_extra_var,
751 * Functions to read and write the global options pointer.
754 /** Command-line and config-file options. */
755 static or_options_t *global_options = NULL;
756 /** Name of most recently read torrc file. */
757 static char *torrc_fname = NULL;
758 /** Persistent serialized state. */
759 static or_state_t *global_state = NULL;
760 /** Configuration Options set by command line. */
761 static config_line_t *global_cmdline_options = NULL;
762 /** Contents of most recently read DirPortFrontPage file. */
763 static char *global_dirfrontpagecontents = NULL;
765 /** Return the contents of our frontpage string, or NULL if not configured. */
766 const char *
767 get_dirportfrontpage(void)
769 return global_dirfrontpagecontents;
772 /** Allocate an empty configuration object of a given format type. */
773 static void *
774 config_alloc(config_format_t *fmt)
776 void *opts = tor_malloc_zero(fmt->size);
777 *(uint32_t*)STRUCT_VAR_P(opts, fmt->magic_offset) = fmt->magic;
778 CHECK(fmt, opts);
779 return opts;
782 /** Return the currently configured options. */
783 or_options_t *
784 get_options(void)
786 tor_assert(global_options);
787 return global_options;
790 /** Change the current global options to contain <b>new_val</b> instead of
791 * their current value; take action based on the new value; free the old value
792 * as necessary. Returns 0 on success, -1 on failure.
795 set_options(or_options_t *new_val, char **msg)
797 or_options_t *old_options = global_options;
798 global_options = new_val;
799 /* Note that we pass the *old* options below, for comparison. It
800 * pulls the new options directly out of global_options. */
801 if (options_act_reversible(old_options, msg)<0) {
802 tor_assert(*msg);
803 global_options = old_options;
804 return -1;
806 if (options_act(old_options) < 0) { /* acting on the options failed. die. */
807 log_err(LD_BUG,
808 "Acting on config options left us in a broken state. Dying.");
809 exit(1);
811 if (old_options)
812 config_free(&options_format, old_options);
814 return 0;
817 extern const char tor_svn_revision[]; /* from tor_main.c */
819 /** The version of this Tor process, as parsed. */
820 static char *_version = NULL;
822 /** Return the current Tor version. */
823 const char *
824 get_version(void)
826 if (_version == NULL) {
827 if (strlen(tor_svn_revision)) {
828 size_t len = strlen(VERSION)+strlen(tor_svn_revision)+8;
829 _version = tor_malloc(len);
830 tor_snprintf(_version, len, "%s (r%s)", VERSION, tor_svn_revision);
831 } else {
832 _version = tor_strdup(VERSION);
835 return _version;
838 /** Release additional memory allocated in options
840 static void
841 or_options_free(or_options_t *options)
843 if (options->_ExcludeExitNodesUnion)
844 routerset_free(options->_ExcludeExitNodesUnion);
845 config_free(&options_format, options);
848 /** Release all memory and resources held by global configuration structures.
850 void
851 config_free_all(void)
853 if (global_options) {
854 or_options_free(global_options);
855 global_options = NULL;
857 if (global_state) {
858 config_free(&state_format, global_state);
859 global_state = NULL;
861 if (global_cmdline_options) {
862 config_free_lines(global_cmdline_options);
863 global_cmdline_options = NULL;
865 tor_free(torrc_fname);
866 tor_free(_version);
867 tor_free(global_dirfrontpagecontents);
870 /** If options->SafeLogging is on, return a not very useful string,
871 * else return address.
873 const char *
874 safe_str(const char *address)
876 tor_assert(address);
877 if (get_options()->SafeLogging)
878 return "[scrubbed]";
879 else
880 return address;
883 /** Equivalent to escaped(safe_str(address)). See reentrancy note on
884 * escaped(): don't use this outside the main thread, or twice in the same
885 * log statement. */
886 const char *
887 escaped_safe_str(const char *address)
889 if (get_options()->SafeLogging)
890 return "[scrubbed]";
891 else
892 return escaped(address);
895 /** Add the default directory authorities directly into the trusted dir list,
896 * but only add them insofar as they share bits with <b>type</b>. */
897 static void
898 add_default_trusted_dir_authorities(authority_type_t type)
900 int i;
901 const char *dirservers[] = {
902 "moria1 v1 orport=9001 v3ident=E2A2AF570166665D738736D0DD58169CC61D8A8B "
903 "128.31.0.34:9031 FFCB 46DB 1339 DA84 674C 70D7 CB58 6434 C437 0441",
904 "moria2 v1 orport=9002 128.31.0.34:9032 "
905 "719B E45D E224 B607 C537 07D0 E214 3E2D 423E 74CF",
906 "tor26 v1 orport=443 v3ident=14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4 "
907 "86.59.21.38:80 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D",
908 "dizum orport=443 v3ident=E8A9C45EDE6D711294FADF8E7951F4DE6CA56B58 "
909 "194.109.206.212:80 7EA6 EAD6 FD83 083C 538F 4403 8BBF A077 587D D755",
910 "Tonga orport=443 bridge no-v2 82.94.251.206:80 "
911 "4A0C CD2D DC79 9508 3D73 F5D6 6710 0C8A 5831 F16D",
912 "ides orport=9090 no-v2 v3ident=27B6B5996C426270A5C95488AA5BCEB6BCC86956 "
913 "216.224.124.114:9030 F397 038A DC51 3361 35E7 B80B D99C A384 4360 292B",
914 "gabelmoo orport=443 no-v2 "
915 "v3ident=81349FC1F2DBA2C2C11B45CB9706637D480AB913 "
916 "80.190.246.100:80 6833 3D07 61BC F397 A587 A0C0 B963 E4A9 E99E C4D3",
917 "dannenberg orport=443 no-v2 "
918 "v3ident=585769C78764D58426B8B52B6651A5A71137189A "
919 "213.73.91.31:80 7BE6 83E6 5D48 1413 21C5 ED92 F075 C553 64AC 7123",
920 NULL
922 for (i=0; dirservers[i]; i++) {
923 if (parse_dir_server_line(dirservers[i], type, 0)<0) {
924 log_err(LD_BUG, "Couldn't parse internal dirserver line %s",
925 dirservers[i]);
930 /** Look at all the config options for using alternate directory
931 * authorities, and make sure none of them are broken. Also, warn the
932 * user if we changed any dangerous ones.
934 static int
935 validate_dir_authorities(or_options_t *options, or_options_t *old_options)
937 config_line_t *cl;
939 if (options->DirServers &&
940 (options->AlternateDirAuthority || options->AlternateBridgeAuthority ||
941 options->AlternateHSAuthority)) {
942 log_warn(LD_CONFIG,
943 "You cannot set both DirServers and Alternate*Authority.");
944 return -1;
947 /* do we want to complain to the user about being partitionable? */
948 if ((options->DirServers &&
949 (!old_options ||
950 !config_lines_eq(options->DirServers, old_options->DirServers))) ||
951 (options->AlternateDirAuthority &&
952 (!old_options ||
953 !config_lines_eq(options->AlternateDirAuthority,
954 old_options->AlternateDirAuthority)))) {
955 log_warn(LD_CONFIG,
956 "You have used DirServer or AlternateDirAuthority to "
957 "specify alternate directory authorities in "
958 "your configuration. This is potentially dangerous: it can "
959 "make you look different from all other Tor users, and hurt "
960 "your anonymity. Even if you've specified the same "
961 "authorities as Tor uses by default, the defaults could "
962 "change in the future. Be sure you know what you're doing.");
965 /* Now go through the four ways you can configure an alternate
966 * set of directory authorities, and make sure none are broken. */
967 for (cl = options->DirServers; cl; cl = cl->next)
968 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
969 return -1;
970 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
971 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
972 return -1;
973 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
974 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
975 return -1;
976 for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
977 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
978 return -1;
979 return 0;
982 /** Look at all the config options and assign new dir authorities
983 * as appropriate.
985 static int
986 consider_adding_dir_authorities(or_options_t *options,
987 or_options_t *old_options)
989 config_line_t *cl;
990 int need_to_update =
991 !smartlist_len(router_get_trusted_dir_servers()) || !old_options ||
992 !config_lines_eq(options->DirServers, old_options->DirServers) ||
993 !config_lines_eq(options->AlternateBridgeAuthority,
994 old_options->AlternateBridgeAuthority) ||
995 !config_lines_eq(options->AlternateDirAuthority,
996 old_options->AlternateDirAuthority) ||
997 !config_lines_eq(options->AlternateHSAuthority,
998 old_options->AlternateHSAuthority);
1000 if (!need_to_update)
1001 return 0; /* all done */
1003 /* Start from a clean slate. */
1004 clear_trusted_dir_servers();
1006 if (!options->DirServers) {
1007 /* then we may want some of the defaults */
1008 authority_type_t type = NO_AUTHORITY;
1009 if (!options->AlternateBridgeAuthority)
1010 type |= BRIDGE_AUTHORITY;
1011 if (!options->AlternateDirAuthority)
1012 type |= V1_AUTHORITY | V2_AUTHORITY | V3_AUTHORITY;
1013 if (!options->AlternateHSAuthority)
1014 type |= HIDSERV_AUTHORITY;
1015 add_default_trusted_dir_authorities(type);
1018 for (cl = options->DirServers; cl; cl = cl->next)
1019 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1020 return -1;
1021 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
1022 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1023 return -1;
1024 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
1025 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1026 return -1;
1027 for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
1028 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1029 return -1;
1030 return 0;
1033 /** Fetch the active option list, and take actions based on it. All of the
1034 * things we do should survive being done repeatedly. If present,
1035 * <b>old_options</b> contains the previous value of the options.
1037 * Return 0 if all goes well, return -1 if things went badly.
1039 static int
1040 options_act_reversible(or_options_t *old_options, char **msg)
1042 smartlist_t *new_listeners = smartlist_create();
1043 smartlist_t *replaced_listeners = smartlist_create();
1044 static int libevent_initialized = 0;
1045 or_options_t *options = get_options();
1046 int running_tor = options->command == CMD_RUN_TOR;
1047 int set_conn_limit = 0;
1048 int r = -1;
1049 int logs_marked = 0;
1051 /* Daemonize _first_, since we only want to open most of this stuff in
1052 * the subprocess. Libevent bases can't be reliably inherited across
1053 * processes. */
1054 if (running_tor && options->RunAsDaemon) {
1055 /* No need to roll back, since you can't change the value. */
1056 start_daemon();
1059 #ifndef HAVE_SYS_UN_H
1060 if (options->ControlSocket) {
1061 *msg = tor_strdup("Unix domain sockets (ControlSocket) not supported"
1062 " on this OS/with this build.");
1063 goto rollback;
1065 #endif
1067 if (running_tor) {
1068 /* We need to set the connection limit before we can open the listeners. */
1069 if (set_max_file_descriptors((unsigned)options->ConnLimit,
1070 &options->_ConnLimit) < 0) {
1071 *msg = tor_strdup("Problem with ConnLimit value. See logs for details.");
1072 goto rollback;
1074 set_conn_limit = 1;
1076 /* Set up libevent. (We need to do this before we can register the
1077 * listeners as listeners.) */
1078 if (running_tor && !libevent_initialized) {
1079 init_libevent();
1080 libevent_initialized = 1;
1083 /* Launch the listeners. (We do this before we setuid, so we can bind to
1084 * ports under 1024.) */
1085 if (retry_all_listeners(replaced_listeners, new_listeners) < 0) {
1086 *msg = tor_strdup("Failed to bind one of the listener ports.");
1087 goto rollback;
1091 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
1092 /* Open /dev/pf before dropping privileges. */
1093 if (options->TransPort) {
1094 if (get_pf_socket() < 0) {
1095 *msg = tor_strdup("Unable to open /dev/pf for transparent proxy.");
1096 goto rollback;
1099 #endif
1101 /* Setuid/setgid as appropriate */
1102 if (options->User) {
1103 if (switch_id(options->User) != 0) {
1104 /* No need to roll back, since you can't change the value. */
1105 *msg = tor_strdup("Problem with User value. See logs for details.");
1106 goto done;
1110 /* Ensure data directory is private; create if possible. */
1111 if (check_private_dir(options->DataDirectory,
1112 running_tor ? CPD_CREATE : CPD_CHECK)<0) {
1113 char buf[1024];
1114 int tmp = tor_snprintf(buf, sizeof(buf),
1115 "Couldn't access/create private data directory \"%s\"",
1116 options->DataDirectory);
1117 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1118 goto done;
1119 /* No need to roll back, since you can't change the value. */
1122 if (directory_caches_v2_dir_info(options)) {
1123 size_t len = strlen(options->DataDirectory)+32;
1124 char *fn = tor_malloc(len);
1125 tor_snprintf(fn, len, "%s"PATH_SEPARATOR"cached-status",
1126 options->DataDirectory);
1127 if (check_private_dir(fn, running_tor ? CPD_CREATE : CPD_CHECK) < 0) {
1128 char buf[1024];
1129 int tmp = tor_snprintf(buf, sizeof(buf),
1130 "Couldn't access/create private data directory \"%s\"", fn);
1131 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1132 tor_free(fn);
1133 goto done;
1135 tor_free(fn);
1138 /* Bail out at this point if we're not going to be a client or server:
1139 * we don't run Tor itself. */
1140 if (!running_tor)
1141 goto commit;
1143 mark_logs_temp(); /* Close current logs once new logs are open. */
1144 logs_marked = 1;
1145 if (options_init_logs(options, 0)<0) { /* Configure the log(s) */
1146 *msg = tor_strdup("Failed to init Log options. See logs for details.");
1147 goto rollback;
1150 commit:
1151 r = 0;
1152 if (logs_marked) {
1153 log_severity_list_t *severity =
1154 tor_malloc_zero(sizeof(log_severity_list_t));
1155 close_temp_logs();
1156 add_callback_log(severity, control_event_logmsg);
1157 control_adjust_event_log_severity();
1158 tor_free(severity);
1160 SMARTLIST_FOREACH(replaced_listeners, connection_t *, conn,
1162 log_notice(LD_NET, "Closing old %s on %s:%d",
1163 conn_type_to_string(conn->type), conn->address, conn->port);
1164 connection_close_immediate(conn);
1165 connection_mark_for_close(conn);
1167 goto done;
1169 rollback:
1170 r = -1;
1171 tor_assert(*msg);
1173 if (logs_marked) {
1174 rollback_log_changes();
1175 control_adjust_event_log_severity();
1178 if (set_conn_limit && old_options)
1179 set_max_file_descriptors((unsigned)old_options->ConnLimit,
1180 &options->_ConnLimit);
1182 SMARTLIST_FOREACH(new_listeners, connection_t *, conn,
1184 log_notice(LD_NET, "Closing partially-constructed listener %s on %s:%d",
1185 conn_type_to_string(conn->type), conn->address, conn->port);
1186 connection_close_immediate(conn);
1187 connection_mark_for_close(conn);
1190 done:
1191 smartlist_free(new_listeners);
1192 smartlist_free(replaced_listeners);
1193 return r;
1196 /** If we need to have a GEOIP ip-to-country map to run with our configured
1197 * options, return 1 and set *<b>reason_out</b> to a description of why. */
1199 options_need_geoip_info(or_options_t *options, const char **reason_out)
1201 int bridge_usage =
1202 options->BridgeRelay && options->BridgeRecordUsageByCountry;
1203 int routerset_usage =
1204 routerset_needs_geoip(options->EntryNodes) ||
1205 routerset_needs_geoip(options->ExitNodes) ||
1206 routerset_needs_geoip(options->ExcludeExitNodes) ||
1207 routerset_needs_geoip(options->ExcludeNodes);
1209 if (routerset_usage && reason_out) {
1210 *reason_out = "We've been configured to use (or avoid) nodes in certain "
1211 "countries, and we need GEOIP information to figure out which ones they "
1212 "are.";
1213 } else if (bridge_usage && reason_out) {
1214 *reason_out = "We've been configured to see which countries can access "
1215 "us as a bridge, and we need GEOIP information to tell which countries "
1216 "clients are in.";
1218 return bridge_usage || routerset_usage;
1221 /** Fetch the active option list, and take actions based on it. All of the
1222 * things we do should survive being done repeatedly. If present,
1223 * <b>old_options</b> contains the previous value of the options.
1225 * Return 0 if all goes well, return -1 if it's time to die.
1227 * Note: We haven't moved all the "act on new configuration" logic
1228 * here yet. Some is still in do_hup() and other places.
1230 static int
1231 options_act(or_options_t *old_options)
1233 config_line_t *cl;
1234 or_options_t *options = get_options();
1235 int running_tor = options->command == CMD_RUN_TOR;
1236 char *msg;
1238 if (running_tor && !have_lockfile()) {
1239 if (try_locking(options, 1) < 0)
1240 return -1;
1243 if (consider_adding_dir_authorities(options, old_options) < 0)
1244 return -1;
1246 if (options->Bridges) {
1247 clear_bridge_list();
1248 for (cl = options->Bridges; cl; cl = cl->next) {
1249 if (parse_bridge_line(cl->value, 0)<0) {
1250 log_warn(LD_BUG,
1251 "Previously validated Bridge line could not be added!");
1252 return -1;
1257 if (running_tor && rend_config_services(options, 0)<0) {
1258 log_warn(LD_BUG,
1259 "Previously validated hidden services line could not be added!");
1260 return -1;
1263 if (running_tor && rend_parse_service_authorization(options, 0) < 0) {
1264 log_warn(LD_BUG, "Previously validated client authorization for "
1265 "hidden services could not be added!");
1266 return -1;
1269 /* Load state */
1270 if (! global_state && running_tor) {
1271 if (or_state_load())
1272 return -1;
1273 rep_hist_load_mtbf_data(time(NULL));
1276 /* Bail out at this point if we're not going to be a client or server:
1277 * we want to not fork, and to log stuff to stderr. */
1278 if (!running_tor)
1279 return 0;
1281 /* Finish backgrounding the process */
1282 if (options->RunAsDaemon) {
1283 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
1284 finish_daemon(options->DataDirectory);
1287 /* Write our PID to the PID file. If we do not have write permissions we
1288 * will log a warning */
1289 if (options->PidFile)
1290 write_pidfile(options->PidFile);
1292 /* Register addressmap directives */
1293 config_register_addressmaps(options);
1294 parse_virtual_addr_network(options->VirtualAddrNetwork, 0, &msg);
1296 /* Update address policies. */
1297 if (policies_parse_from_options(options) < 0) {
1298 /* This should be impossible, but let's be sure. */
1299 log_warn(LD_BUG,"Error parsing already-validated policy options.");
1300 return -1;
1303 if (init_cookie_authentication(options->CookieAuthentication) < 0) {
1304 log_warn(LD_CONFIG,"Error creating cookie authentication file.");
1305 return -1;
1308 /* reload keys as needed for rendezvous services. */
1309 if (rend_service_load_keys()<0) {
1310 log_warn(LD_GENERAL,"Error loading rendezvous service keys");
1311 return -1;
1314 /* Set up accounting */
1315 if (accounting_parse_options(options, 0)<0) {
1316 log_warn(LD_CONFIG,"Error in accounting options");
1317 return -1;
1319 if (accounting_is_enabled(options))
1320 configure_accounting(time(NULL));
1322 /* Check for transitions that need action. */
1323 if (old_options) {
1324 if (options->UseEntryGuards && !old_options->UseEntryGuards) {
1325 log_info(LD_CIRC,
1326 "Switching to entry guards; abandoning previous circuits");
1327 circuit_mark_all_unused_circs();
1328 circuit_expire_all_dirty_circs();
1331 if (! bool_eq(options->BridgeRelay, old_options->BridgeRelay)) {
1332 log_info(LD_GENERAL, "Bridge status changed. Forgetting GeoIP stats.");
1333 geoip_remove_old_clients(time(NULL)+(2*60*60));
1336 if (options_transition_affects_workers(old_options, options)) {
1337 log_info(LD_GENERAL,
1338 "Worker-related options changed. Rotating workers.");
1339 if (server_mode(options) && !server_mode(old_options)) {
1340 if (init_keys() < 0) {
1341 log_warn(LD_BUG,"Error initializing keys; exiting");
1342 return -1;
1344 ip_address_changed(0);
1345 if (has_completed_circuit || !any_predicted_circuits(time(NULL)))
1346 inform_testing_reachability();
1348 cpuworkers_rotate();
1349 if (dns_reset())
1350 return -1;
1351 } else {
1352 if (dns_reset())
1353 return -1;
1356 if (options->V3AuthoritativeDir && !old_options->V3AuthoritativeDir)
1357 init_keys();
1360 /* Maybe load geoip file */
1361 if (options->GeoIPFile &&
1362 ((!old_options || !opt_streq(old_options->GeoIPFile, options->GeoIPFile))
1363 || !geoip_is_loaded())) {
1364 /* XXXX Don't use this "<default>" junk; make our filename options
1365 * understand prefixes somehow. -NM */
1366 /* XXXX021 Reload GeoIPFile on SIGHUP. -NM */
1367 char *actual_fname = tor_strdup(options->GeoIPFile);
1368 #ifdef WIN32
1369 if (!strcmp(actual_fname, "<default>")) {
1370 const char *conf_root = get_windows_conf_root();
1371 size_t len = strlen(conf_root)+16;
1372 tor_free(actual_fname);
1373 actual_fname = tor_malloc(len+1);
1374 tor_snprintf(actual_fname, len, "%s\\geoip", conf_root);
1376 #endif
1377 geoip_load_file(actual_fname, options);
1378 tor_free(actual_fname);
1380 #ifdef ENABLE_GEOIP_STATS
1381 /* Check if GeoIP database could be loaded. */
1382 if (!geoip_is_loaded()) {
1383 log_warn(LD_CONFIG, "Configured to measure GeoIP statistics, but no "
1384 "GeoIP database found!");
1385 return -1;
1387 log_notice(LD_CONFIG, "Configured to measure usage by country and "
1388 "write aggregate statistics to disk. Check the geoip-stats file "
1389 "in your data directory once I've been running for 24 hours.");
1390 #endif
1391 #ifdef ENABLE_EXIT_STATS
1392 if (options->ExitPortStatistics)
1393 log_notice(LD_CONFIG, "Configured to measure exit port statistics. "
1394 "Look for the exit-stats file that will first be written to "
1395 "the data directory in 24 hours from now.");
1396 #else
1397 if (options->ExitPortStatistics)
1398 log_warn(LD_CONFIG, "ExitPortStatistics enabled, but Tor was built "
1399 "without port statistics support.");
1400 #endif
1402 #ifdef ENABLE_BUFFER_STATS
1403 if (options->CellStatistics)
1404 log_notice(LD_CONFIG, "Configured to measure cell statistics. Look "
1405 "for the buffer-stats file that will first be written to "
1406 "the data directory in 24 hours from now.");
1407 #else
1408 if (options->CellStatistics)
1409 log_warn(LD_CONFIG, "CellStatistics enabled, but Tor was built "
1410 "without cell statistics support.");
1411 #endif
1413 #ifdef ENABLE_ENTRY_STATS
1414 if (options->EntryStatistics) {
1415 if (should_record_bridge_info(options)) {
1416 /* Don't allow measuring statistics on entry guards when configured
1417 * as bridge. */
1418 log_warn(LD_CONFIG, "Bridges cannot be configured to measure "
1419 "additional GeoIP statistics as entry guards.");
1420 return -1;
1421 } else
1422 log_notice(LD_CONFIG, "Configured to measure entry node "
1423 "statistics. Look for the entry-stats file that will "
1424 "first be written to the data directory in 24 hours "
1425 "from now.");
1427 #else
1428 if (options->EntryStatistics)
1429 log_warn(LD_CONFIG, "EntryStatistics enabled, but Tor was built "
1430 "without entry node statistics support.");
1431 #endif
1432 /* Check if we need to parse and add the EntryNodes config option. */
1433 if (options->EntryNodes &&
1434 (!old_options ||
1435 (!routerset_equal(old_options->EntryNodes,options->EntryNodes))))
1436 entry_nodes_should_be_added();
1438 /* Since our options changed, we might need to regenerate and upload our
1439 * server descriptor.
1441 if (!old_options ||
1442 options_transition_affects_descriptor(old_options, options))
1443 mark_my_descriptor_dirty();
1445 /* We may need to reschedule some directory stuff if our status changed. */
1446 if (old_options) {
1447 if (authdir_mode_v3(options) && !authdir_mode_v3(old_options))
1448 dirvote_recalculate_timing(options, time(NULL));
1449 if (!bool_eq(directory_fetches_dir_info_early(options),
1450 directory_fetches_dir_info_early(old_options)) ||
1451 !bool_eq(directory_fetches_dir_info_later(options),
1452 directory_fetches_dir_info_later(old_options))) {
1453 /* Make sure update_router_have_min_dir_info gets called. */
1454 router_dir_info_changed();
1455 /* We might need to download a new consensus status later or sooner than
1456 * we had expected. */
1457 update_consensus_networkstatus_fetch_time(time(NULL));
1461 /* Load the webpage we're going to serve every time someone asks for '/' on
1462 our DirPort. */
1463 tor_free(global_dirfrontpagecontents);
1464 if (options->DirPortFrontPage) {
1465 global_dirfrontpagecontents =
1466 read_file_to_str(options->DirPortFrontPage, 0, NULL);
1467 if (!global_dirfrontpagecontents) {
1468 log_warn(LD_CONFIG,
1469 "DirPortFrontPage file '%s' not found. Continuing anyway.",
1470 options->DirPortFrontPage);
1474 return 0;
1478 * Functions to parse config options
1481 /** If <b>option</b> is an official abbreviation for a longer option,
1482 * return the longer option. Otherwise return <b>option</b>.
1483 * If <b>command_line</b> is set, apply all abbreviations. Otherwise, only
1484 * apply abbreviations that work for the config file and the command line.
1485 * If <b>warn_obsolete</b> is set, warn about deprecated names. */
1486 static const char *
1487 expand_abbrev(config_format_t *fmt, const char *option, int command_line,
1488 int warn_obsolete)
1490 int i;
1491 if (! fmt->abbrevs)
1492 return option;
1493 for (i=0; fmt->abbrevs[i].abbreviated; ++i) {
1494 /* Abbreviations are case insensitive. */
1495 if (!strcasecmp(option,fmt->abbrevs[i].abbreviated) &&
1496 (command_line || !fmt->abbrevs[i].commandline_only)) {
1497 if (warn_obsolete && fmt->abbrevs[i].warn) {
1498 log_warn(LD_CONFIG,
1499 "The configuration option '%s' is deprecated; "
1500 "use '%s' instead.",
1501 fmt->abbrevs[i].abbreviated,
1502 fmt->abbrevs[i].full);
1504 return fmt->abbrevs[i].full;
1507 return option;
1510 /** Helper: Read a list of configuration options from the command line.
1511 * If successful, put them in *<b>result</b> and return 0, and return
1512 * -1 and leave *<b>result</b> alone. */
1513 static int
1514 config_get_commandlines(int argc, char **argv, config_line_t **result)
1516 config_line_t *front = NULL;
1517 config_line_t **new = &front;
1518 char *s;
1519 int i = 1;
1521 while (i < argc) {
1522 if (!strcmp(argv[i],"-f") ||
1523 !strcmp(argv[i],"--hash-password")) {
1524 i += 2; /* command-line option with argument. ignore them. */
1525 continue;
1526 } else if (!strcmp(argv[i],"--list-fingerprint") ||
1527 !strcmp(argv[i],"--verify-config") ||
1528 !strcmp(argv[i],"--ignore-missing-torrc") ||
1529 !strcmp(argv[i],"--quiet") ||
1530 !strcmp(argv[i],"--hush")) {
1531 i += 1; /* command-line option. ignore it. */
1532 continue;
1533 } else if (!strcmp(argv[i],"--nt-service") ||
1534 !strcmp(argv[i],"-nt-service")) {
1535 i += 1;
1536 continue;
1539 if (i == argc-1) {
1540 log_warn(LD_CONFIG,"Command-line option '%s' with no value. Failing.",
1541 argv[i]);
1542 config_free_lines(front);
1543 return -1;
1546 *new = tor_malloc_zero(sizeof(config_line_t));
1547 s = argv[i];
1549 while (*s == '-')
1550 s++;
1552 (*new)->key = tor_strdup(expand_abbrev(&options_format, s, 1, 1));
1553 (*new)->value = tor_strdup(argv[i+1]);
1554 (*new)->next = NULL;
1555 log(LOG_DEBUG, LD_CONFIG, "command line: parsed keyword '%s', value '%s'",
1556 (*new)->key, (*new)->value);
1558 new = &((*new)->next);
1559 i += 2;
1561 *result = front;
1562 return 0;
1565 /** Helper: allocate a new configuration option mapping 'key' to 'val',
1566 * append it to *<b>lst</b>. */
1567 static void
1568 config_line_append(config_line_t **lst,
1569 const char *key,
1570 const char *val)
1572 config_line_t *newline;
1574 newline = tor_malloc(sizeof(config_line_t));
1575 newline->key = tor_strdup(key);
1576 newline->value = tor_strdup(val);
1577 newline->next = NULL;
1578 while (*lst)
1579 lst = &((*lst)->next);
1581 (*lst) = newline;
1584 /** Helper: parse the config string and strdup into key/value
1585 * strings. Set *result to the list, or NULL if parsing the string
1586 * failed. Return 0 on success, -1 on failure. Warn and ignore any
1587 * misformatted lines. */
1589 config_get_lines(const char *string, config_line_t **result)
1591 config_line_t *list = NULL, **next;
1592 char *k, *v;
1594 next = &list;
1595 do {
1596 k = v = NULL;
1597 string = parse_config_line_from_str(string, &k, &v);
1598 if (!string) {
1599 config_free_lines(list);
1600 tor_free(k);
1601 tor_free(v);
1602 return -1;
1604 if (k && v) {
1605 /* This list can get long, so we keep a pointer to the end of it
1606 * rather than using config_line_append over and over and getting
1607 * n^2 performance. */
1608 *next = tor_malloc(sizeof(config_line_t));
1609 (*next)->key = k;
1610 (*next)->value = v;
1611 (*next)->next = NULL;
1612 next = &((*next)->next);
1613 } else {
1614 tor_free(k);
1615 tor_free(v);
1617 } while (*string);
1619 *result = list;
1620 return 0;
1624 * Free all the configuration lines on the linked list <b>front</b>.
1626 void
1627 config_free_lines(config_line_t *front)
1629 config_line_t *tmp;
1631 while (front) {
1632 tmp = front;
1633 front = tmp->next;
1635 tor_free(tmp->key);
1636 tor_free(tmp->value);
1637 tor_free(tmp);
1641 /** Return the description for a given configuration variable, or NULL if no
1642 * description exists. */
1643 static const char *
1644 config_find_description(config_format_t *fmt, const char *name)
1646 int i;
1647 for (i=0; fmt->descriptions[i].name; ++i) {
1648 if (!strcasecmp(name, fmt->descriptions[i].name))
1649 return fmt->descriptions[i].description;
1651 return NULL;
1654 /** If <b>key</b> is a configuration option, return the corresponding
1655 * config_var_t. Otherwise, if <b>key</b> is a non-standard abbreviation,
1656 * warn, and return the corresponding config_var_t. Otherwise return NULL.
1658 static config_var_t *
1659 config_find_option(config_format_t *fmt, const char *key)
1661 int i;
1662 size_t keylen = strlen(key);
1663 if (!keylen)
1664 return NULL; /* if they say "--" on the command line, it's not an option */
1665 /* First, check for an exact (case-insensitive) match */
1666 for (i=0; fmt->vars[i].name; ++i) {
1667 if (!strcasecmp(key, fmt->vars[i].name)) {
1668 return &fmt->vars[i];
1671 /* If none, check for an abbreviated match */
1672 for (i=0; fmt->vars[i].name; ++i) {
1673 if (!strncasecmp(key, fmt->vars[i].name, keylen)) {
1674 log_warn(LD_CONFIG, "The abbreviation '%s' is deprecated. "
1675 "Please use '%s' instead",
1676 key, fmt->vars[i].name);
1677 return &fmt->vars[i];
1680 /* Okay, unrecognized option */
1681 return NULL;
1685 * Functions to assign config options.
1688 /** <b>c</b>-\>key is known to be a real key. Update <b>options</b>
1689 * with <b>c</b>-\>value and return 0, or return -1 if bad value.
1691 * Called from config_assign_line() and option_reset().
1693 static int
1694 config_assign_value(config_format_t *fmt, or_options_t *options,
1695 config_line_t *c, char **msg)
1697 int i, r, ok;
1698 char buf[1024];
1699 config_var_t *var;
1700 void *lvalue;
1702 CHECK(fmt, options);
1704 var = config_find_option(fmt, c->key);
1705 tor_assert(var);
1707 lvalue = STRUCT_VAR_P(options, var->var_offset);
1709 switch (var->type) {
1711 case CONFIG_TYPE_UINT:
1712 i = (int)tor_parse_long(c->value, 10, 0, INT_MAX, &ok, NULL);
1713 if (!ok) {
1714 r = tor_snprintf(buf, sizeof(buf),
1715 "Int keyword '%s %s' is malformed or out of bounds.",
1716 c->key, c->value);
1717 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1718 return -1;
1720 *(int *)lvalue = i;
1721 break;
1723 case CONFIG_TYPE_INTERVAL: {
1724 i = config_parse_interval(c->value, &ok);
1725 if (!ok) {
1726 r = tor_snprintf(buf, sizeof(buf),
1727 "Interval '%s %s' is malformed or out of bounds.",
1728 c->key, c->value);
1729 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1730 return -1;
1732 *(int *)lvalue = i;
1733 break;
1736 case CONFIG_TYPE_MEMUNIT: {
1737 uint64_t u64 = config_parse_memunit(c->value, &ok);
1738 if (!ok) {
1739 r = tor_snprintf(buf, sizeof(buf),
1740 "Value '%s %s' is malformed or out of bounds.",
1741 c->key, c->value);
1742 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1743 return -1;
1745 *(uint64_t *)lvalue = u64;
1746 break;
1749 case CONFIG_TYPE_BOOL:
1750 i = (int)tor_parse_long(c->value, 10, 0, 1, &ok, NULL);
1751 if (!ok) {
1752 r = tor_snprintf(buf, sizeof(buf),
1753 "Boolean '%s %s' expects 0 or 1.",
1754 c->key, c->value);
1755 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1756 return -1;
1758 *(int *)lvalue = i;
1759 break;
1761 case CONFIG_TYPE_STRING:
1762 case CONFIG_TYPE_FILENAME:
1763 tor_free(*(char **)lvalue);
1764 *(char **)lvalue = tor_strdup(c->value);
1765 break;
1767 case CONFIG_TYPE_DOUBLE:
1768 *(double *)lvalue = atof(c->value);
1769 break;
1771 case CONFIG_TYPE_ISOTIME:
1772 if (parse_iso_time(c->value, (time_t *)lvalue)) {
1773 r = tor_snprintf(buf, sizeof(buf),
1774 "Invalid time '%s' for keyword '%s'", c->value, c->key);
1775 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1776 return -1;
1778 break;
1780 case CONFIG_TYPE_ROUTERSET:
1781 if (*(routerset_t**)lvalue) {
1782 routerset_free(*(routerset_t**)lvalue);
1784 *(routerset_t**)lvalue = routerset_new();
1785 if (routerset_parse(*(routerset_t**)lvalue, c->value, c->key)<0) {
1786 tor_snprintf(buf, sizeof(buf), "Invalid exit list '%s' for option '%s'",
1787 c->value, c->key);
1788 *msg = tor_strdup(buf);
1789 return -1;
1791 break;
1793 case CONFIG_TYPE_CSV:
1794 if (*(smartlist_t**)lvalue) {
1795 SMARTLIST_FOREACH(*(smartlist_t**)lvalue, char *, cp, tor_free(cp));
1796 smartlist_clear(*(smartlist_t**)lvalue);
1797 } else {
1798 *(smartlist_t**)lvalue = smartlist_create();
1801 smartlist_split_string(*(smartlist_t**)lvalue, c->value, ",",
1802 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1803 break;
1805 case CONFIG_TYPE_LINELIST:
1806 case CONFIG_TYPE_LINELIST_S:
1807 config_line_append((config_line_t**)lvalue, c->key, c->value);
1808 break;
1809 case CONFIG_TYPE_OBSOLETE:
1810 log_warn(LD_CONFIG, "Skipping obsolete configuration option '%s'", c->key);
1811 break;
1812 case CONFIG_TYPE_LINELIST_V:
1813 r = tor_snprintf(buf, sizeof(buf),
1814 "You may not provide a value for virtual option '%s'", c->key);
1815 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1816 return -1;
1817 default:
1818 tor_assert(0);
1819 break;
1821 return 0;
1824 /** If <b>c</b> is a syntactically valid configuration line, update
1825 * <b>options</b> with its value and return 0. Otherwise return -1 for bad
1826 * key, -2 for bad value.
1828 * If <b>clear_first</b> is set, clear the value first. Then if
1829 * <b>use_defaults</b> is set, set the value to the default.
1831 * Called from config_assign().
1833 static int
1834 config_assign_line(config_format_t *fmt, or_options_t *options,
1835 config_line_t *c, int use_defaults,
1836 int clear_first, char **msg)
1838 config_var_t *var;
1840 CHECK(fmt, options);
1842 var = config_find_option(fmt, c->key);
1843 if (!var) {
1844 if (fmt->extra) {
1845 void *lvalue = STRUCT_VAR_P(options, fmt->extra->var_offset);
1846 log_info(LD_CONFIG,
1847 "Found unrecognized option '%s'; saving it.", c->key);
1848 config_line_append((config_line_t**)lvalue, c->key, c->value);
1849 return 0;
1850 } else {
1851 char buf[1024];
1852 int tmp = tor_snprintf(buf, sizeof(buf),
1853 "Unknown option '%s'. Failing.", c->key);
1854 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1855 return -1;
1858 /* Put keyword into canonical case. */
1859 if (strcmp(var->name, c->key)) {
1860 tor_free(c->key);
1861 c->key = tor_strdup(var->name);
1864 if (!strlen(c->value)) {
1865 /* reset or clear it, then return */
1866 if (!clear_first) {
1867 if (var->type == CONFIG_TYPE_LINELIST ||
1868 var->type == CONFIG_TYPE_LINELIST_S) {
1869 /* We got an empty linelist from the torrc or command line.
1870 As a special case, call this an error. Warn and ignore. */
1871 log_warn(LD_CONFIG,
1872 "Linelist option '%s' has no value. Skipping.", c->key);
1873 } else { /* not already cleared */
1874 option_reset(fmt, options, var, use_defaults);
1877 return 0;
1880 if (config_assign_value(fmt, options, c, msg) < 0)
1881 return -2;
1882 return 0;
1885 /** Restore the option named <b>key</b> in options to its default value.
1886 * Called from config_assign(). */
1887 static void
1888 config_reset_line(config_format_t *fmt, or_options_t *options,
1889 const char *key, int use_defaults)
1891 config_var_t *var;
1893 CHECK(fmt, options);
1895 var = config_find_option(fmt, key);
1896 if (!var)
1897 return; /* give error on next pass. */
1899 option_reset(fmt, options, var, use_defaults);
1902 /** Return true iff key is a valid configuration option. */
1904 option_is_recognized(const char *key)
1906 config_var_t *var = config_find_option(&options_format, key);
1907 return (var != NULL);
1910 /** Return the canonical name of a configuration option, or NULL
1911 * if no such option exists. */
1912 const char *
1913 option_get_canonical_name(const char *key)
1915 config_var_t *var = config_find_option(&options_format, key);
1916 return var ? var->name : NULL;
1919 /** Return a canonical list of the options assigned for key.
1921 config_line_t *
1922 option_get_assignment(or_options_t *options, const char *key)
1924 return get_assigned_option(&options_format, options, key, 1);
1927 /** Return true iff value needs to be quoted and escaped to be used in
1928 * a configuration file. */
1929 static int
1930 config_value_needs_escape(const char *value)
1932 if (*value == '\"')
1933 return 1;
1934 while (*value) {
1935 switch (*value)
1937 case '\r':
1938 case '\n':
1939 case '#':
1940 /* Note: quotes and backspaces need special handling when we are using
1941 * quotes, not otherwise, so they don't trigger escaping on their
1942 * own. */
1943 return 1;
1944 default:
1945 if (!TOR_ISPRINT(*value))
1946 return 1;
1948 ++value;
1950 return 0;
1953 /** Return a newly allocated deep copy of the lines in <b>inp</b>. */
1954 static config_line_t *
1955 config_lines_dup(const config_line_t *inp)
1957 config_line_t *result = NULL;
1958 config_line_t **next_out = &result;
1959 while (inp) {
1960 *next_out = tor_malloc(sizeof(config_line_t));
1961 (*next_out)->key = tor_strdup(inp->key);
1962 (*next_out)->value = tor_strdup(inp->value);
1963 inp = inp->next;
1964 next_out = &((*next_out)->next);
1966 (*next_out) = NULL;
1967 return result;
1970 /** Return newly allocated line or lines corresponding to <b>key</b> in the
1971 * configuration <b>options</b>. If <b>escape_val</b> is true and a
1972 * value needs to be quoted before it's put in a config file, quote and
1973 * escape that value. Return NULL if no such key exists. */
1974 static config_line_t *
1975 get_assigned_option(config_format_t *fmt, void *options,
1976 const char *key, int escape_val)
1978 config_var_t *var;
1979 const void *value;
1980 char buf[32];
1981 config_line_t *result;
1982 tor_assert(options && key);
1984 CHECK(fmt, options);
1986 var = config_find_option(fmt, key);
1987 if (!var) {
1988 log_warn(LD_CONFIG, "Unknown option '%s'. Failing.", key);
1989 return NULL;
1991 value = STRUCT_VAR_P(options, var->var_offset);
1993 result = tor_malloc_zero(sizeof(config_line_t));
1994 result->key = tor_strdup(var->name);
1995 switch (var->type)
1997 case CONFIG_TYPE_STRING:
1998 case CONFIG_TYPE_FILENAME:
1999 if (*(char**)value) {
2000 result->value = tor_strdup(*(char**)value);
2001 } else {
2002 tor_free(result->key);
2003 tor_free(result);
2004 return NULL;
2006 break;
2007 case CONFIG_TYPE_ISOTIME:
2008 if (*(time_t*)value) {
2009 result->value = tor_malloc(ISO_TIME_LEN+1);
2010 format_iso_time(result->value, *(time_t*)value);
2011 } else {
2012 tor_free(result->key);
2013 tor_free(result);
2015 escape_val = 0; /* Can't need escape. */
2016 break;
2017 case CONFIG_TYPE_INTERVAL:
2018 case CONFIG_TYPE_UINT:
2019 /* This means every or_options_t uint or bool element
2020 * needs to be an int. Not, say, a uint16_t or char. */
2021 tor_snprintf(buf, sizeof(buf), "%d", *(int*)value);
2022 result->value = tor_strdup(buf);
2023 escape_val = 0; /* Can't need escape. */
2024 break;
2025 case CONFIG_TYPE_MEMUNIT:
2026 tor_snprintf(buf, sizeof(buf), U64_FORMAT,
2027 U64_PRINTF_ARG(*(uint64_t*)value));
2028 result->value = tor_strdup(buf);
2029 escape_val = 0; /* Can't need escape. */
2030 break;
2031 case CONFIG_TYPE_DOUBLE:
2032 tor_snprintf(buf, sizeof(buf), "%f", *(double*)value);
2033 result->value = tor_strdup(buf);
2034 escape_val = 0; /* Can't need escape. */
2035 break;
2036 case CONFIG_TYPE_BOOL:
2037 result->value = tor_strdup(*(int*)value ? "1" : "0");
2038 escape_val = 0; /* Can't need escape. */
2039 break;
2040 case CONFIG_TYPE_ROUTERSET:
2041 result->value = routerset_to_string(*(routerset_t**)value);
2042 break;
2043 case CONFIG_TYPE_CSV:
2044 if (*(smartlist_t**)value)
2045 result->value =
2046 smartlist_join_strings(*(smartlist_t**)value, ",", 0, NULL);
2047 else
2048 result->value = tor_strdup("");
2049 break;
2050 case CONFIG_TYPE_OBSOLETE:
2051 log_fn(LOG_PROTOCOL_WARN, LD_CONFIG,
2052 "You asked me for the value of an obsolete config option '%s'.",
2053 key);
2054 tor_free(result->key);
2055 tor_free(result);
2056 return NULL;
2057 case CONFIG_TYPE_LINELIST_S:
2058 log_warn(LD_CONFIG,
2059 "Can't return context-sensitive '%s' on its own", key);
2060 tor_free(result->key);
2061 tor_free(result);
2062 return NULL;
2063 case CONFIG_TYPE_LINELIST:
2064 case CONFIG_TYPE_LINELIST_V:
2065 tor_free(result->key);
2066 tor_free(result);
2067 result = config_lines_dup(*(const config_line_t**)value);
2068 break;
2069 default:
2070 tor_free(result->key);
2071 tor_free(result);
2072 log_warn(LD_BUG,"Unknown type %d for known key '%s'",
2073 var->type, key);
2074 return NULL;
2077 if (escape_val) {
2078 config_line_t *line;
2079 for (line = result; line; line = line->next) {
2080 if (line->value && config_value_needs_escape(line->value)) {
2081 char *newval = esc_for_log(line->value);
2082 tor_free(line->value);
2083 line->value = newval;
2088 return result;
2091 /** Iterate through the linked list of requested options <b>list</b>.
2092 * For each item, convert as appropriate and assign to <b>options</b>.
2093 * If an item is unrecognized, set *msg and return -1 immediately,
2094 * else return 0 for success.
2096 * If <b>clear_first</b>, interpret config options as replacing (not
2097 * extending) their previous values. If <b>clear_first</b> is set,
2098 * then <b>use_defaults</b> to decide if you set to defaults after
2099 * clearing, or make the value 0 or NULL.
2101 * Here are the use cases:
2102 * 1. A non-empty AllowInvalid line in your torrc. Appends to current
2103 * if linelist, replaces current if csv.
2104 * 2. An empty AllowInvalid line in your torrc. Should clear it.
2105 * 3. "RESETCONF AllowInvalid" sets it to default.
2106 * 4. "SETCONF AllowInvalid" makes it NULL.
2107 * 5. "SETCONF AllowInvalid=foo" clears it and sets it to "foo".
2109 * Use_defaults Clear_first
2110 * 0 0 "append"
2111 * 1 0 undefined, don't use
2112 * 0 1 "set to null first"
2113 * 1 1 "set to defaults first"
2114 * Return 0 on success, -1 on bad key, -2 on bad value.
2116 * As an additional special case, if a LINELIST config option has
2117 * no value and clear_first is 0, then warn and ignore it.
2121 There are three call cases for config_assign() currently.
2123 Case one: Torrc entry
2124 options_init_from_torrc() calls config_assign(0, 0)
2125 calls config_assign_line(0, 0).
2126 if value is empty, calls option_reset(0) and returns.
2127 calls config_assign_value(), appends.
2129 Case two: setconf
2130 options_trial_assign() calls config_assign(0, 1)
2131 calls config_reset_line(0)
2132 calls option_reset(0)
2133 calls option_clear().
2134 calls config_assign_line(0, 1).
2135 if value is empty, returns.
2136 calls config_assign_value(), appends.
2138 Case three: resetconf
2139 options_trial_assign() calls config_assign(1, 1)
2140 calls config_reset_line(1)
2141 calls option_reset(1)
2142 calls option_clear().
2143 calls config_assign_value(default)
2144 calls config_assign_line(1, 1).
2145 returns.
2147 static int
2148 config_assign(config_format_t *fmt, void *options, config_line_t *list,
2149 int use_defaults, int clear_first, char **msg)
2151 config_line_t *p;
2153 CHECK(fmt, options);
2155 /* pass 1: normalize keys */
2156 for (p = list; p; p = p->next) {
2157 const char *full = expand_abbrev(fmt, p->key, 0, 1);
2158 if (strcmp(full,p->key)) {
2159 tor_free(p->key);
2160 p->key = tor_strdup(full);
2164 /* pass 2: if we're reading from a resetting source, clear all
2165 * mentioned config options, and maybe set to their defaults. */
2166 if (clear_first) {
2167 for (p = list; p; p = p->next)
2168 config_reset_line(fmt, options, p->key, use_defaults);
2171 /* pass 3: assign. */
2172 while (list) {
2173 int r;
2174 if ((r=config_assign_line(fmt, options, list, use_defaults,
2175 clear_first, msg)))
2176 return r;
2177 list = list->next;
2179 return 0;
2182 /** Try assigning <b>list</b> to the global options. You do this by duping
2183 * options, assigning list to the new one, then validating it. If it's
2184 * ok, then throw out the old one and stick with the new one. Else,
2185 * revert to old and return failure. Return SETOPT_OK on success, or
2186 * a setopt_err_t on failure.
2188 * If not success, point *<b>msg</b> to a newly allocated string describing
2189 * what went wrong.
2191 setopt_err_t
2192 options_trial_assign(config_line_t *list, int use_defaults,
2193 int clear_first, char **msg)
2195 int r;
2196 or_options_t *trial_options = options_dup(&options_format, get_options());
2198 if ((r=config_assign(&options_format, trial_options,
2199 list, use_defaults, clear_first, msg)) < 0) {
2200 config_free(&options_format, trial_options);
2201 return r;
2204 if (options_validate(get_options(), trial_options, 1, msg) < 0) {
2205 config_free(&options_format, trial_options);
2206 return SETOPT_ERR_PARSE; /*XXX make this a separate return value. */
2209 if (options_transition_allowed(get_options(), trial_options, msg) < 0) {
2210 config_free(&options_format, trial_options);
2211 return SETOPT_ERR_TRANSITION;
2214 if (set_options(trial_options, msg)<0) {
2215 config_free(&options_format, trial_options);
2216 return SETOPT_ERR_SETTING;
2219 /* we liked it. put it in place. */
2220 return SETOPT_OK;
2223 /** Reset config option <b>var</b> to 0, 0.0, NULL, or the equivalent.
2224 * Called from option_reset() and config_free(). */
2225 static void
2226 option_clear(config_format_t *fmt, or_options_t *options, config_var_t *var)
2228 void *lvalue = STRUCT_VAR_P(options, var->var_offset);
2229 (void)fmt; /* unused */
2230 switch (var->type) {
2231 case CONFIG_TYPE_STRING:
2232 case CONFIG_TYPE_FILENAME:
2233 tor_free(*(char**)lvalue);
2234 break;
2235 case CONFIG_TYPE_DOUBLE:
2236 *(double*)lvalue = 0.0;
2237 break;
2238 case CONFIG_TYPE_ISOTIME:
2239 *(time_t*)lvalue = 0;
2240 case CONFIG_TYPE_INTERVAL:
2241 case CONFIG_TYPE_UINT:
2242 case CONFIG_TYPE_BOOL:
2243 *(int*)lvalue = 0;
2244 break;
2245 case CONFIG_TYPE_MEMUNIT:
2246 *(uint64_t*)lvalue = 0;
2247 break;
2248 case CONFIG_TYPE_ROUTERSET:
2249 if (*(routerset_t**)lvalue) {
2250 routerset_free(*(routerset_t**)lvalue);
2251 *(routerset_t**)lvalue = NULL;
2253 case CONFIG_TYPE_CSV:
2254 if (*(smartlist_t**)lvalue) {
2255 SMARTLIST_FOREACH(*(smartlist_t **)lvalue, char *, cp, tor_free(cp));
2256 smartlist_free(*(smartlist_t **)lvalue);
2257 *(smartlist_t **)lvalue = NULL;
2259 break;
2260 case CONFIG_TYPE_LINELIST:
2261 case CONFIG_TYPE_LINELIST_S:
2262 config_free_lines(*(config_line_t **)lvalue);
2263 *(config_line_t **)lvalue = NULL;
2264 break;
2265 case CONFIG_TYPE_LINELIST_V:
2266 /* handled by linelist_s. */
2267 break;
2268 case CONFIG_TYPE_OBSOLETE:
2269 break;
2273 /** Clear the option indexed by <b>var</b> in <b>options</b>. Then if
2274 * <b>use_defaults</b>, set it to its default value.
2275 * Called by config_init() and option_reset_line() and option_assign_line(). */
2276 static void
2277 option_reset(config_format_t *fmt, or_options_t *options,
2278 config_var_t *var, int use_defaults)
2280 config_line_t *c;
2281 char *msg = NULL;
2282 CHECK(fmt, options);
2283 option_clear(fmt, options, var); /* clear it first */
2284 if (!use_defaults)
2285 return; /* all done */
2286 if (var->initvalue) {
2287 c = tor_malloc_zero(sizeof(config_line_t));
2288 c->key = tor_strdup(var->name);
2289 c->value = tor_strdup(var->initvalue);
2290 if (config_assign_value(fmt, options, c, &msg) < 0) {
2291 log_warn(LD_BUG, "Failed to assign default: %s", msg);
2292 tor_free(msg); /* if this happens it's a bug */
2294 config_free_lines(c);
2298 /** Print a usage message for tor. */
2299 static void
2300 print_usage(void)
2302 printf(
2303 "Copyright (c) 2001-2004, Roger Dingledine\n"
2304 "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
2305 "Copyright (c) 2007-2009, The Tor Project, Inc.\n\n"
2306 "tor -f <torrc> [args]\n"
2307 "See man page for options, or https://www.torproject.org/ for "
2308 "documentation.\n");
2311 /** Print all non-obsolete torrc options. */
2312 static void
2313 list_torrc_options(void)
2315 int i;
2316 smartlist_t *lines = smartlist_create();
2317 for (i = 0; _option_vars[i].name; ++i) {
2318 config_var_t *var = &_option_vars[i];
2319 const char *desc;
2320 if (var->type == CONFIG_TYPE_OBSOLETE ||
2321 var->type == CONFIG_TYPE_LINELIST_V)
2322 continue;
2323 desc = config_find_description(&options_format, var->name);
2324 printf("%s\n", var->name);
2325 if (desc) {
2326 wrap_string(lines, desc, 76, " ", " ");
2327 SMARTLIST_FOREACH(lines, char *, cp, {
2328 printf("%s", cp);
2329 tor_free(cp);
2331 smartlist_clear(lines);
2334 smartlist_free(lines);
2337 /** Last value actually set by resolve_my_address. */
2338 static uint32_t last_resolved_addr = 0;
2340 * Based on <b>options-\>Address</b>, guess our public IP address and put it
2341 * (in host order) into *<b>addr_out</b>. If <b>hostname_out</b> is provided,
2342 * set *<b>hostname_out</b> to a new string holding the hostname we used to
2343 * get the address. Return 0 if all is well, or -1 if we can't find a suitable
2344 * public IP address.
2347 resolve_my_address(int warn_severity, or_options_t *options,
2348 uint32_t *addr_out, char **hostname_out)
2350 struct in_addr in;
2351 struct hostent *rent;
2352 char hostname[256];
2353 int explicit_ip=1;
2354 int explicit_hostname=1;
2355 int from_interface=0;
2356 char tmpbuf[INET_NTOA_BUF_LEN];
2357 const char *address = options->Address;
2358 int notice_severity = warn_severity <= LOG_NOTICE ?
2359 LOG_NOTICE : warn_severity;
2361 tor_assert(addr_out);
2363 if (address && *address) {
2364 strlcpy(hostname, address, sizeof(hostname));
2365 } else { /* then we need to guess our address */
2366 explicit_ip = 0; /* it's implicit */
2367 explicit_hostname = 0; /* it's implicit */
2369 if (gethostname(hostname, sizeof(hostname)) < 0) {
2370 log_fn(warn_severity, LD_NET,"Error obtaining local hostname");
2371 return -1;
2373 log_debug(LD_CONFIG,"Guessed local host name as '%s'",hostname);
2376 /* now we know hostname. resolve it and keep only the IP address */
2378 if (tor_inet_aton(hostname, &in) == 0) {
2379 /* then we have to resolve it */
2380 explicit_ip = 0;
2381 rent = (struct hostent *)gethostbyname(hostname);
2382 if (!rent) {
2383 uint32_t interface_ip;
2385 if (explicit_hostname) {
2386 log_fn(warn_severity, LD_CONFIG,
2387 "Could not resolve local Address '%s'. Failing.", hostname);
2388 return -1;
2390 log_fn(notice_severity, LD_CONFIG,
2391 "Could not resolve guessed local hostname '%s'. "
2392 "Trying something else.", hostname);
2393 if (get_interface_address(warn_severity, &interface_ip)) {
2394 log_fn(warn_severity, LD_CONFIG,
2395 "Could not get local interface IP address. Failing.");
2396 return -1;
2398 from_interface = 1;
2399 in.s_addr = htonl(interface_ip);
2400 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2401 log_fn(notice_severity, LD_CONFIG, "Learned IP address '%s' for "
2402 "local interface. Using that.", tmpbuf);
2403 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2404 } else {
2405 tor_assert(rent->h_length == 4);
2406 memcpy(&in.s_addr, rent->h_addr, rent->h_length);
2408 if (!explicit_hostname &&
2409 is_internal_IP(ntohl(in.s_addr), 0)) {
2410 uint32_t interface_ip;
2412 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2413 log_fn(notice_severity, LD_CONFIG, "Guessed local hostname '%s' "
2414 "resolves to a private IP address (%s). Trying something "
2415 "else.", hostname, tmpbuf);
2417 if (get_interface_address(warn_severity, &interface_ip)) {
2418 log_fn(warn_severity, LD_CONFIG,
2419 "Could not get local interface IP address. Too bad.");
2420 } else if (is_internal_IP(interface_ip, 0)) {
2421 struct in_addr in2;
2422 in2.s_addr = htonl(interface_ip);
2423 tor_inet_ntoa(&in2,tmpbuf,sizeof(tmpbuf));
2424 log_fn(notice_severity, LD_CONFIG,
2425 "Interface IP address '%s' is a private address too. "
2426 "Ignoring.", tmpbuf);
2427 } else {
2428 from_interface = 1;
2429 in.s_addr = htonl(interface_ip);
2430 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2431 log_fn(notice_severity, LD_CONFIG,
2432 "Learned IP address '%s' for local interface."
2433 " Using that.", tmpbuf);
2434 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2440 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2441 if (is_internal_IP(ntohl(in.s_addr), 0) &&
2442 options->_PublishServerDescriptor) {
2443 /* make sure we're ok with publishing an internal IP */
2444 if (!options->DirServers && !options->AlternateDirAuthority) {
2445 /* if they are using the default dirservers, disallow internal IPs
2446 * always. */
2447 log_fn(warn_severity, LD_CONFIG,
2448 "Address '%s' resolves to private IP address '%s'. "
2449 "Tor servers that use the default DirServers must have public "
2450 "IP addresses.", hostname, tmpbuf);
2451 return -1;
2453 if (!explicit_ip) {
2454 /* even if they've set their own dirservers, require an explicit IP if
2455 * they're using an internal address. */
2456 log_fn(warn_severity, LD_CONFIG, "Address '%s' resolves to private "
2457 "IP address '%s'. Please set the Address config option to be "
2458 "the IP address you want to use.", hostname, tmpbuf);
2459 return -1;
2463 log_debug(LD_CONFIG, "Resolved Address to '%s'.", tmpbuf);
2464 *addr_out = ntohl(in.s_addr);
2465 if (last_resolved_addr && last_resolved_addr != *addr_out) {
2466 /* Leave this as a notice, regardless of the requested severity,
2467 * at least until dynamic IP address support becomes bulletproof. */
2468 log_notice(LD_NET,
2469 "Your IP address seems to have changed to %s. Updating.",
2470 tmpbuf);
2471 ip_address_changed(0);
2473 if (last_resolved_addr != *addr_out) {
2474 const char *method;
2475 const char *h = hostname;
2476 if (explicit_ip) {
2477 method = "CONFIGURED";
2478 h = NULL;
2479 } else if (explicit_hostname) {
2480 method = "RESOLVED";
2481 } else if (from_interface) {
2482 method = "INTERFACE";
2483 h = NULL;
2484 } else {
2485 method = "GETHOSTNAME";
2487 control_event_server_status(LOG_NOTICE,
2488 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s %s%s",
2489 tmpbuf, method, h?"HOSTNAME=":"", h);
2491 last_resolved_addr = *addr_out;
2492 if (hostname_out)
2493 *hostname_out = tor_strdup(hostname);
2494 return 0;
2497 /** Return true iff <b>addr</b> is judged to be on the same network as us, or
2498 * on a private network.
2501 is_local_addr(const tor_addr_t *addr)
2503 if (tor_addr_is_internal(addr, 0))
2504 return 1;
2505 /* Check whether ip is on the same /24 as we are. */
2506 if (get_options()->EnforceDistinctSubnets == 0)
2507 return 0;
2508 if (tor_addr_family(addr) == AF_INET) {
2509 /*XXXX022 IP6 what corresponds to an /24? */
2510 uint32_t ip = tor_addr_to_ipv4h(addr);
2512 /* It's possible that this next check will hit before the first time
2513 * resolve_my_address actually succeeds. (For clients, it is likely that
2514 * resolve_my_address will never be called at all). In those cases,
2515 * last_resolved_addr will be 0, and so checking to see whether ip is on
2516 * the same /24 as last_resolved_addr will be the same as checking whether
2517 * it was on net 0, which is already done by is_internal_IP.
2519 if ((last_resolved_addr & 0xffffff00ul) == (ip & 0xffffff00ul))
2520 return 1;
2522 return 0;
2525 /** Called when we don't have a nickname set. Try to guess a good nickname
2526 * based on the hostname, and return it in a newly allocated string. If we
2527 * can't, return NULL and let the caller warn if it wants to. */
2528 static char *
2529 get_default_nickname(void)
2531 static const char * const bad_default_nicknames[] = {
2532 "localhost",
2533 NULL,
2535 char localhostname[256];
2536 char *cp, *out, *outp;
2537 int i;
2539 if (gethostname(localhostname, sizeof(localhostname)) < 0)
2540 return NULL;
2542 /* Put it in lowercase; stop at the first dot. */
2543 if ((cp = strchr(localhostname, '.')))
2544 *cp = '\0';
2545 tor_strlower(localhostname);
2547 /* Strip invalid characters. */
2548 cp = localhostname;
2549 out = outp = tor_malloc(strlen(localhostname) + 1);
2550 while (*cp) {
2551 if (strchr(LEGAL_NICKNAME_CHARACTERS, *cp))
2552 *outp++ = *cp++;
2553 else
2554 cp++;
2556 *outp = '\0';
2558 /* Enforce length. */
2559 if (strlen(out) > MAX_NICKNAME_LEN)
2560 out[MAX_NICKNAME_LEN]='\0';
2562 /* Check for dumb names. */
2563 for (i = 0; bad_default_nicknames[i]; ++i) {
2564 if (!strcmp(out, bad_default_nicknames[i])) {
2565 tor_free(out);
2566 return NULL;
2570 return out;
2573 /** Release storage held by <b>options</b>. */
2574 static void
2575 config_free(config_format_t *fmt, void *options)
2577 int i;
2579 tor_assert(options);
2581 for (i=0; fmt->vars[i].name; ++i)
2582 option_clear(fmt, options, &(fmt->vars[i]));
2583 if (fmt->extra) {
2584 config_line_t **linep = STRUCT_VAR_P(options, fmt->extra->var_offset);
2585 config_free_lines(*linep);
2586 *linep = NULL;
2588 tor_free(options);
2591 /** Return true iff a and b contain identical keys and values in identical
2592 * order. */
2593 static int
2594 config_lines_eq(config_line_t *a, config_line_t *b)
2596 while (a && b) {
2597 if (strcasecmp(a->key, b->key) || strcmp(a->value, b->value))
2598 return 0;
2599 a = a->next;
2600 b = b->next;
2602 if (a || b)
2603 return 0;
2604 return 1;
2607 /** Return true iff the option <b>name</b> has the same value in <b>o1</b>
2608 * and <b>o2</b>. Must not be called for LINELIST_S or OBSOLETE options.
2610 static int
2611 option_is_same(config_format_t *fmt,
2612 or_options_t *o1, or_options_t *o2, const char *name)
2614 config_line_t *c1, *c2;
2615 int r = 1;
2616 CHECK(fmt, o1);
2617 CHECK(fmt, o2);
2619 c1 = get_assigned_option(fmt, o1, name, 0);
2620 c2 = get_assigned_option(fmt, o2, name, 0);
2621 r = config_lines_eq(c1, c2);
2622 config_free_lines(c1);
2623 config_free_lines(c2);
2624 return r;
2627 /** Copy storage held by <b>old</b> into a new or_options_t and return it. */
2628 static or_options_t *
2629 options_dup(config_format_t *fmt, or_options_t *old)
2631 or_options_t *newopts;
2632 int i;
2633 config_line_t *line;
2635 newopts = config_alloc(fmt);
2636 for (i=0; fmt->vars[i].name; ++i) {
2637 if (fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
2638 continue;
2639 if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE)
2640 continue;
2641 line = get_assigned_option(fmt, old, fmt->vars[i].name, 0);
2642 if (line) {
2643 char *msg = NULL;
2644 if (config_assign(fmt, newopts, line, 0, 0, &msg) < 0) {
2645 log_err(LD_BUG, "Config_get_assigned_option() generated "
2646 "something we couldn't config_assign(): %s", msg);
2647 tor_free(msg);
2648 tor_assert(0);
2651 config_free_lines(line);
2653 return newopts;
2656 /** Return a new empty or_options_t. Used for testing. */
2657 or_options_t *
2658 options_new(void)
2660 return config_alloc(&options_format);
2663 /** Set <b>options</b> to hold reasonable defaults for most options.
2664 * Each option defaults to zero. */
2665 void
2666 options_init(or_options_t *options)
2668 config_init(&options_format, options);
2671 /* Check if the port number given in <b>port_option</b> in combination with
2672 * the specified port in <b>listen_options</b> will result in Tor actually
2673 * opening a low port (meaning a port lower than 1024). Return 1 if
2674 * it is, or 0 if it isn't or the concept of a low port isn't applicable for
2675 * the platform we're on. */
2676 static int
2677 is_listening_on_low_port(uint16_t port_option,
2678 const config_line_t *listen_options)
2680 #ifdef MS_WINDOWS
2681 return 0; /* No port is too low for windows. */
2682 #else
2683 const config_line_t *l;
2684 uint16_t p;
2685 if (port_option == 0)
2686 return 0; /* We're not listening */
2687 if (listen_options == NULL)
2688 return (port_option < 1024);
2690 for (l = listen_options; l; l = l->next) {
2691 parse_addr_port(LOG_WARN, l->value, NULL, NULL, &p);
2692 if (p<1024) {
2693 return 1;
2696 return 0;
2697 #endif
2700 /** Set all vars in the configuration object <b>options</b> to their default
2701 * values. */
2702 static void
2703 config_init(config_format_t *fmt, void *options)
2705 int i;
2706 config_var_t *var;
2707 CHECK(fmt, options);
2709 for (i=0; fmt->vars[i].name; ++i) {
2710 var = &fmt->vars[i];
2711 if (!var->initvalue)
2712 continue; /* defaults to NULL or 0 */
2713 option_reset(fmt, options, var, 1);
2717 /** Allocate and return a new string holding the written-out values of the vars
2718 * in 'options'. If 'minimal', do not write out any default-valued vars.
2719 * Else, if comment_defaults, write default values as comments.
2721 static char *
2722 config_dump(config_format_t *fmt, void *options, int minimal,
2723 int comment_defaults)
2725 smartlist_t *elements;
2726 or_options_t *defaults;
2727 config_line_t *line, *assigned;
2728 char *result;
2729 int i;
2730 const char *desc;
2731 char *msg = NULL;
2733 defaults = config_alloc(fmt);
2734 config_init(fmt, defaults);
2736 /* XXX use a 1 here so we don't add a new log line while dumping */
2737 if (fmt->validate_fn(NULL,defaults, 1, &msg) < 0) {
2738 log_err(LD_BUG, "Failed to validate default config.");
2739 tor_free(msg);
2740 tor_assert(0);
2743 elements = smartlist_create();
2744 for (i=0; fmt->vars[i].name; ++i) {
2745 int comment_option = 0;
2746 if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE ||
2747 fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
2748 continue;
2749 /* Don't save 'hidden' control variables. */
2750 if (!strcmpstart(fmt->vars[i].name, "__"))
2751 continue;
2752 if (minimal && option_is_same(fmt, options, defaults, fmt->vars[i].name))
2753 continue;
2754 else if (comment_defaults &&
2755 option_is_same(fmt, options, defaults, fmt->vars[i].name))
2756 comment_option = 1;
2758 desc = config_find_description(fmt, fmt->vars[i].name);
2759 line = assigned = get_assigned_option(fmt, options, fmt->vars[i].name, 1);
2761 if (line && desc) {
2762 /* Only dump the description if there's something to describe. */
2763 wrap_string(elements, desc, 78, "# ", "# ");
2766 for (; line; line = line->next) {
2767 size_t len = strlen(line->key) + strlen(line->value) + 5;
2768 char *tmp;
2769 tmp = tor_malloc(len);
2770 if (tor_snprintf(tmp, len, "%s%s %s\n",
2771 comment_option ? "# " : "",
2772 line->key, line->value)<0) {
2773 log_err(LD_BUG,"Internal error writing option value");
2774 tor_assert(0);
2776 smartlist_add(elements, tmp);
2778 config_free_lines(assigned);
2781 if (fmt->extra) {
2782 line = *(config_line_t**)STRUCT_VAR_P(options, fmt->extra->var_offset);
2783 for (; line; line = line->next) {
2784 size_t len = strlen(line->key) + strlen(line->value) + 3;
2785 char *tmp;
2786 tmp = tor_malloc(len);
2787 if (tor_snprintf(tmp, len, "%s %s\n", line->key, line->value)<0) {
2788 log_err(LD_BUG,"Internal error writing option value");
2789 tor_assert(0);
2791 smartlist_add(elements, tmp);
2795 result = smartlist_join_strings(elements, "", 0, NULL);
2796 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
2797 smartlist_free(elements);
2798 config_free(fmt, defaults);
2799 return result;
2802 /** Return a string containing a possible configuration file that would give
2803 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
2804 * include options that are the same as Tor's defaults.
2806 static char *
2807 options_dump(or_options_t *options, int minimal)
2809 return config_dump(&options_format, options, minimal, 0);
2812 /** Return 0 if every element of sl is a string holding a decimal
2813 * representation of a port number, or if sl is NULL.
2814 * Otherwise set *msg and return -1. */
2815 static int
2816 validate_ports_csv(smartlist_t *sl, const char *name, char **msg)
2818 int i;
2819 char buf[1024];
2820 tor_assert(name);
2822 if (!sl)
2823 return 0;
2825 SMARTLIST_FOREACH(sl, const char *, cp,
2827 i = atoi(cp);
2828 if (i < 1 || i > 65535) {
2829 int r = tor_snprintf(buf, sizeof(buf),
2830 "Port '%s' out of range in %s", cp, name);
2831 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2832 return -1;
2835 return 0;
2838 /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
2839 * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
2840 * Else return 0.
2842 static int
2843 ensure_bandwidth_cap(uint64_t *value, const char *desc, char **msg)
2845 int r;
2846 char buf[1024];
2847 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2848 /* This handles an understandable special case where somebody says "2gb"
2849 * whereas our actual maximum is 2gb-1 (INT_MAX) */
2850 --*value;
2852 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2853 r = tor_snprintf(buf, sizeof(buf), "%s ("U64_FORMAT") must be at most %d",
2854 desc, U64_PRINTF_ARG(*value),
2855 ROUTER_MAX_DECLARED_BANDWIDTH);
2856 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2857 return -1;
2859 return 0;
2862 /** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
2863 * and write it to <b>options</b>-\>_PublishServerDescriptor. Treat "1"
2864 * as "v2,v3" unless BridgeRelay is 1, in which case treat it as "bridge".
2865 * Treat "0" as "".
2866 * Return 0 on success or -1 if not a recognized authority type (in which
2867 * case the value of _PublishServerDescriptor is undefined). */
2868 static int
2869 compute_publishserverdescriptor(or_options_t *options)
2871 smartlist_t *list = options->PublishServerDescriptor;
2872 authority_type_t *auth = &options->_PublishServerDescriptor;
2873 *auth = NO_AUTHORITY;
2874 if (!list) /* empty list, answer is none */
2875 return 0;
2876 SMARTLIST_FOREACH(list, const char *, string, {
2877 if (!strcasecmp(string, "v1"))
2878 *auth |= V1_AUTHORITY;
2879 else if (!strcmp(string, "1"))
2880 if (options->BridgeRelay)
2881 *auth |= BRIDGE_AUTHORITY;
2882 else
2883 *auth |= V2_AUTHORITY | V3_AUTHORITY;
2884 else if (!strcasecmp(string, "v2"))
2885 *auth |= V2_AUTHORITY;
2886 else if (!strcasecmp(string, "v3"))
2887 *auth |= V3_AUTHORITY;
2888 else if (!strcasecmp(string, "bridge"))
2889 *auth |= BRIDGE_AUTHORITY;
2890 else if (!strcasecmp(string, "hidserv"))
2891 *auth |= HIDSERV_AUTHORITY;
2892 else if (!strcasecmp(string, "") || !strcmp(string, "0"))
2893 /* no authority */;
2894 else
2895 return -1;
2897 return 0;
2900 /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
2901 * services can overload the directory system. */
2902 #define MIN_REND_POST_PERIOD (10*60)
2904 /** Highest allowable value for RendPostPeriod. */
2905 #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
2907 /** Lowest allowable value for CircuitBuildTimeout; values too low will
2908 * increase network load because of failing connections being retried, and
2909 * might prevent users from connecting to the network at all. */
2910 #define MIN_CIRCUIT_BUILD_TIMEOUT 30
2912 /** Lowest allowable value for MaxCircuitDirtiness; if this is too low, Tor
2913 * will generate too many circuits and potentially overload the network. */
2914 #define MIN_MAX_CIRCUIT_DIRTINESS 10
2916 /** Return 0 if every setting in <b>options</b> is reasonable, and a
2917 * permissible transition from <b>old_options</b>. Else return -1.
2918 * Should have no side effects, except for normalizing the contents of
2919 * <b>options</b>.
2921 * On error, tor_strdup an error explanation into *<b>msg</b>.
2923 * XXX
2924 * If <b>from_setconf</b>, we were called by the controller, and our
2925 * Log line should stay empty. If it's 0, then give us a default log
2926 * if there are no logs defined.
2928 static int
2929 options_validate(or_options_t *old_options, or_options_t *options,
2930 int from_setconf, char **msg)
2932 int i, r;
2933 config_line_t *cl;
2934 const char *uname = get_uname();
2935 char buf[1024];
2936 #define REJECT(arg) \
2937 STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
2938 #define COMPLAIN(arg) STMT_BEGIN log(LOG_WARN, LD_CONFIG, arg); STMT_END
2940 tor_assert(msg);
2941 *msg = NULL;
2943 if (options->ORPort < 0 || options->ORPort > 65535)
2944 REJECT("ORPort option out of bounds.");
2946 if (server_mode(options) &&
2947 (!strcmpstart(uname, "Windows 95") ||
2948 !strcmpstart(uname, "Windows 98") ||
2949 !strcmpstart(uname, "Windows Me"))) {
2950 log(LOG_WARN, LD_CONFIG, "Tor is running as a server, but you are "
2951 "running %s; this probably won't work. See "
2952 "http://wiki.noreply.org/noreply/TheOnionRouter/TorFAQ#ServerOS "
2953 "for details.", uname);
2956 if (options->ORPort == 0 && options->ORListenAddress != NULL)
2957 REJECT("ORPort must be defined if ORListenAddress is defined.");
2959 if (options->DirPort == 0 && options->DirListenAddress != NULL)
2960 REJECT("DirPort must be defined if DirListenAddress is defined.");
2962 if (options->DNSPort == 0 && options->DNSListenAddress != NULL)
2963 REJECT("DNSPort must be defined if DNSListenAddress is defined.");
2965 if (options->ControlPort == 0 && options->ControlListenAddress != NULL)
2966 REJECT("ControlPort must be defined if ControlListenAddress is defined.");
2968 if (options->TransPort == 0 && options->TransListenAddress != NULL)
2969 REJECT("TransPort must be defined if TransListenAddress is defined.");
2971 if (options->NatdPort == 0 && options->NatdListenAddress != NULL)
2972 REJECT("NatdPort must be defined if NatdListenAddress is defined.");
2974 /* Don't gripe about SocksPort 0 with SocksListenAddress set; a standard
2975 * configuration does this. */
2977 for (i = 0; i < 3; ++i) {
2978 int is_socks = i==0;
2979 int is_trans = i==1;
2980 config_line_t *line, *opt, *old;
2981 const char *tp;
2982 if (is_socks) {
2983 opt = options->SocksListenAddress;
2984 old = old_options ? old_options->SocksListenAddress : NULL;
2985 tp = "SOCKS proxy";
2986 } else if (is_trans) {
2987 opt = options->TransListenAddress;
2988 old = old_options ? old_options->TransListenAddress : NULL;
2989 tp = "transparent proxy";
2990 } else {
2991 opt = options->NatdListenAddress;
2992 old = old_options ? old_options->NatdListenAddress : NULL;
2993 tp = "natd proxy";
2996 for (line = opt; line; line = line->next) {
2997 char *address = NULL;
2998 uint16_t port;
2999 uint32_t addr;
3000 if (parse_addr_port(LOG_WARN, line->value, &address, &addr, &port)<0)
3001 continue; /* We'll warn about this later. */
3002 if (!is_internal_IP(addr, 1) &&
3003 (!old_options || !config_lines_eq(old, opt))) {
3004 log_warn(LD_CONFIG,
3005 "You specified a public address '%s' for a %s. Other "
3006 "people on the Internet might find your computer and use it as "
3007 "an open %s. Please don't allow this unless you have "
3008 "a good reason.", address, tp, tp);
3010 tor_free(address);
3014 if (validate_data_directory(options)<0)
3015 REJECT("Invalid DataDirectory");
3017 if (options->Nickname == NULL) {
3018 if (server_mode(options)) {
3019 if (!(options->Nickname = get_default_nickname())) {
3020 log_notice(LD_CONFIG, "Couldn't pick a nickname based on "
3021 "our hostname; using %s instead.", UNNAMED_ROUTER_NICKNAME);
3022 options->Nickname = tor_strdup(UNNAMED_ROUTER_NICKNAME);
3023 } else {
3024 log_notice(LD_CONFIG, "Choosing default nickname '%s'",
3025 options->Nickname);
3028 } else {
3029 if (!is_legal_nickname(options->Nickname)) {
3030 r = tor_snprintf(buf, sizeof(buf),
3031 "Nickname '%s' is wrong length or contains illegal characters.",
3032 options->Nickname);
3033 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3034 return -1;
3038 if (server_mode(options) && !options->ContactInfo)
3039 log(LOG_NOTICE, LD_CONFIG, "Your ContactInfo config option is not set. "
3040 "Please consider setting it, so we can contact you if your server is "
3041 "misconfigured or something else goes wrong.");
3043 /* Special case on first boot if no Log options are given. */
3044 if (!options->Logs && !options->RunAsDaemon && !from_setconf)
3045 config_line_append(&options->Logs, "Log", "notice stdout");
3047 if (options_init_logs(options, 1)<0) /* Validate the log(s) */
3048 REJECT("Failed to validate Log options. See logs for details.");
3050 if (options->NoPublish) {
3051 log(LOG_WARN, LD_CONFIG,
3052 "NoPublish is obsolete. Use PublishServerDescriptor instead.");
3053 SMARTLIST_FOREACH(options->PublishServerDescriptor, char *, s,
3054 tor_free(s));
3055 smartlist_clear(options->PublishServerDescriptor);
3058 if (authdir_mode(options)) {
3059 /* confirm that our address isn't broken, so we can complain now */
3060 uint32_t tmp;
3061 if (resolve_my_address(LOG_WARN, options, &tmp, NULL) < 0)
3062 REJECT("Failed to resolve/guess local address. See logs for details.");
3065 #ifndef MS_WINDOWS
3066 if (options->RunAsDaemon && torrc_fname && path_is_relative(torrc_fname))
3067 REJECT("Can't use a relative path to torrc when RunAsDaemon is set.");
3068 #endif
3070 if (options->SocksPort < 0 || options->SocksPort > 65535)
3071 REJECT("SocksPort option out of bounds.");
3073 if (options->DNSPort < 0 || options->DNSPort > 65535)
3074 REJECT("DNSPort option out of bounds.");
3076 if (options->TransPort < 0 || options->TransPort > 65535)
3077 REJECT("TransPort option out of bounds.");
3079 if (options->NatdPort < 0 || options->NatdPort > 65535)
3080 REJECT("NatdPort option out of bounds.");
3082 if (options->SocksPort == 0 && options->TransPort == 0 &&
3083 options->NatdPort == 0 && options->ORPort == 0 &&
3084 options->DNSPort == 0 && !options->RendConfigLines)
3085 log(LOG_WARN, LD_CONFIG,
3086 "SocksPort, TransPort, NatdPort, DNSPort, and ORPort are all "
3087 "undefined, and there aren't any hidden services configured. "
3088 "Tor will still run, but probably won't do anything.");
3090 if (options->ControlPort < 0 || options->ControlPort > 65535)
3091 REJECT("ControlPort option out of bounds.");
3093 if (options->DirPort < 0 || options->DirPort > 65535)
3094 REJECT("DirPort option out of bounds.");
3096 #ifndef USE_TRANSPARENT
3097 if (options->TransPort || options->TransListenAddress)
3098 REJECT("TransPort and TransListenAddress are disabled in this build.");
3099 #endif
3101 if (options->AccountingMax &&
3102 (is_listening_on_low_port(options->ORPort, options->ORListenAddress) ||
3103 is_listening_on_low_port(options->DirPort, options->DirListenAddress)))
3105 log(LOG_WARN, LD_CONFIG,
3106 "You have set AccountingMax to use hibernation. You have also "
3107 "chosen a low DirPort or OrPort. This combination can make Tor stop "
3108 "working when it tries to re-attach the port after a period of "
3109 "hibernation. Please choose a different port or turn off "
3110 "hibernation unless you know this combination will work on your "
3111 "platform.");
3114 if (options->ExcludeExitNodes || options->ExcludeNodes) {
3115 options->_ExcludeExitNodesUnion = routerset_new();
3116 routerset_union(options->_ExcludeExitNodesUnion,options->ExcludeExitNodes);
3117 routerset_union(options->_ExcludeExitNodesUnion,options->ExcludeNodes);
3120 if (options->StrictExitNodes &&
3121 (!options->ExitNodes) &&
3122 (!old_options ||
3123 (old_options->StrictExitNodes != options->StrictExitNodes) ||
3124 (!routerset_equal(old_options->ExitNodes,options->ExitNodes))))
3125 COMPLAIN("StrictExitNodes set, but no ExitNodes listed.");
3127 if (options->StrictEntryNodes &&
3128 (!options->EntryNodes) &&
3129 (!old_options ||
3130 (old_options->StrictEntryNodes != options->StrictEntryNodes) ||
3131 (!routerset_equal(old_options->EntryNodes,options->EntryNodes))))
3132 COMPLAIN("StrictEntryNodes set, but no EntryNodes listed.");
3134 if (options->EntryNodes && !routerset_is_list(options->EntryNodes)) {
3135 /* XXXX fix this; see entry_guards_prepend_from_config(). */
3136 REJECT("IPs or countries are not yet supported in EntryNodes.");
3139 if (options->AuthoritativeDir) {
3140 if (!options->ContactInfo && !options->TestingTorNetwork)
3141 REJECT("Authoritative directory servers must set ContactInfo");
3142 if (options->V1AuthoritativeDir && !options->RecommendedVersions)
3143 REJECT("V1 authoritative dir servers must set RecommendedVersions.");
3144 if (!options->RecommendedClientVersions)
3145 options->RecommendedClientVersions =
3146 config_lines_dup(options->RecommendedVersions);
3147 if (!options->RecommendedServerVersions)
3148 options->RecommendedServerVersions =
3149 config_lines_dup(options->RecommendedVersions);
3150 if (options->VersioningAuthoritativeDir &&
3151 (!options->RecommendedClientVersions ||
3152 !options->RecommendedServerVersions))
3153 REJECT("Versioning authoritative dir servers must set "
3154 "Recommended*Versions.");
3155 if (options->UseEntryGuards) {
3156 log_info(LD_CONFIG, "Authoritative directory servers can't set "
3157 "UseEntryGuards. Disabling.");
3158 options->UseEntryGuards = 0;
3160 if (!options->DownloadExtraInfo && authdir_mode_any_main(options)) {
3161 log_info(LD_CONFIG, "Authoritative directories always try to download "
3162 "extra-info documents. Setting DownloadExtraInfo.");
3163 options->DownloadExtraInfo = 1;
3165 if (!(options->BridgeAuthoritativeDir || options->HSAuthoritativeDir ||
3166 options->V1AuthoritativeDir || options->V2AuthoritativeDir ||
3167 options->V3AuthoritativeDir))
3168 REJECT("AuthoritativeDir is set, but none of "
3169 "(Bridge/HS/V1/V2/V3)AuthoritativeDir is set.");
3172 if (options->AuthoritativeDir && !options->DirPort)
3173 REJECT("Running as authoritative directory, but no DirPort set.");
3175 if (options->AuthoritativeDir && !options->ORPort)
3176 REJECT("Running as authoritative directory, but no ORPort set.");
3178 if (options->AuthoritativeDir && options->ClientOnly)
3179 REJECT("Running as authoritative directory, but ClientOnly also set.");
3181 if (options->HSAuthorityRecordStats && !options->HSAuthoritativeDir)
3182 REJECT("HSAuthorityRecordStats is set but we're not running as "
3183 "a hidden service authority.");
3185 if (options->FetchDirInfoExtraEarly && !options->FetchDirInfoEarly)
3186 REJECT("FetchDirInfoExtraEarly requires that you also set "
3187 "FetchDirInfoEarly");
3189 if (options->ConnLimit <= 0) {
3190 r = tor_snprintf(buf, sizeof(buf),
3191 "ConnLimit must be greater than 0, but was set to %d",
3192 options->ConnLimit);
3193 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3194 return -1;
3197 if (validate_ports_csv(options->FirewallPorts, "FirewallPorts", msg) < 0)
3198 return -1;
3200 if (validate_ports_csv(options->LongLivedPorts, "LongLivedPorts", msg) < 0)
3201 return -1;
3203 if (validate_ports_csv(options->RejectPlaintextPorts,
3204 "RejectPlaintextPorts", msg) < 0)
3205 return -1;
3207 if (validate_ports_csv(options->WarnPlaintextPorts,
3208 "WarnPlaintextPorts", msg) < 0)
3209 return -1;
3211 if (options->FascistFirewall && !options->ReachableAddresses) {
3212 if (options->FirewallPorts && smartlist_len(options->FirewallPorts)) {
3213 /* We already have firewall ports set, so migrate them to
3214 * ReachableAddresses, which will set ReachableORAddresses and
3215 * ReachableDirAddresses if they aren't set explicitly. */
3216 smartlist_t *instead = smartlist_create();
3217 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3218 new_line->key = tor_strdup("ReachableAddresses");
3219 /* If we're configured with the old format, we need to prepend some
3220 * open ports. */
3221 SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
3223 int p = atoi(portno);
3224 char *s;
3225 if (p<0) continue;
3226 s = tor_malloc(16);
3227 tor_snprintf(s, 16, "*:%d", p);
3228 smartlist_add(instead, s);
3230 new_line->value = smartlist_join_strings(instead,",",0,NULL);
3231 /* These have been deprecated since 0.1.1.5-alpha-cvs */
3232 log(LOG_NOTICE, LD_CONFIG,
3233 "Converting FascistFirewall and FirewallPorts "
3234 "config options to new format: \"ReachableAddresses %s\"",
3235 new_line->value);
3236 options->ReachableAddresses = new_line;
3237 SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
3238 smartlist_free(instead);
3239 } else {
3240 /* We do not have FirewallPorts set, so add 80 to
3241 * ReachableDirAddresses, and 443 to ReachableORAddresses. */
3242 if (!options->ReachableDirAddresses) {
3243 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3244 new_line->key = tor_strdup("ReachableDirAddresses");
3245 new_line->value = tor_strdup("*:80");
3246 options->ReachableDirAddresses = new_line;
3247 log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
3248 "to new format: \"ReachableDirAddresses *:80\"");
3250 if (!options->ReachableORAddresses) {
3251 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3252 new_line->key = tor_strdup("ReachableORAddresses");
3253 new_line->value = tor_strdup("*:443");
3254 options->ReachableORAddresses = new_line;
3255 log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
3256 "to new format: \"ReachableORAddresses *:443\"");
3261 for (i=0; i<3; i++) {
3262 config_line_t **linep =
3263 (i==0) ? &options->ReachableAddresses :
3264 (i==1) ? &options->ReachableORAddresses :
3265 &options->ReachableDirAddresses;
3266 if (!*linep)
3267 continue;
3268 /* We need to end with a reject *:*, not an implicit accept *:* */
3269 for (;;) {
3270 if (!strcmp((*linep)->value, "reject *:*")) /* already there */
3271 break;
3272 linep = &((*linep)->next);
3273 if (!*linep) {
3274 *linep = tor_malloc_zero(sizeof(config_line_t));
3275 (*linep)->key = tor_strdup(
3276 (i==0) ? "ReachableAddresses" :
3277 (i==1) ? "ReachableORAddresses" :
3278 "ReachableDirAddresses");
3279 (*linep)->value = tor_strdup("reject *:*");
3280 break;
3285 if ((options->ReachableAddresses ||
3286 options->ReachableORAddresses ||
3287 options->ReachableDirAddresses) &&
3288 server_mode(options))
3289 REJECT("Servers must be able to freely connect to the rest "
3290 "of the Internet, so they must not set Reachable*Addresses "
3291 "or FascistFirewall.");
3293 if (options->UseBridges &&
3294 server_mode(options))
3295 REJECT("Servers must be able to freely connect to the rest "
3296 "of the Internet, so they must not set UseBridges.");
3298 options->_AllowInvalid = 0;
3299 if (options->AllowInvalidNodes) {
3300 SMARTLIST_FOREACH(options->AllowInvalidNodes, const char *, cp, {
3301 if (!strcasecmp(cp, "entry"))
3302 options->_AllowInvalid |= ALLOW_INVALID_ENTRY;
3303 else if (!strcasecmp(cp, "exit"))
3304 options->_AllowInvalid |= ALLOW_INVALID_EXIT;
3305 else if (!strcasecmp(cp, "middle"))
3306 options->_AllowInvalid |= ALLOW_INVALID_MIDDLE;
3307 else if (!strcasecmp(cp, "introduction"))
3308 options->_AllowInvalid |= ALLOW_INVALID_INTRODUCTION;
3309 else if (!strcasecmp(cp, "rendezvous"))
3310 options->_AllowInvalid |= ALLOW_INVALID_RENDEZVOUS;
3311 else {
3312 r = tor_snprintf(buf, sizeof(buf),
3313 "Unrecognized value '%s' in AllowInvalidNodes", cp);
3314 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3315 return -1;
3320 if (compute_publishserverdescriptor(options) < 0) {
3321 r = tor_snprintf(buf, sizeof(buf),
3322 "Unrecognized value in PublishServerDescriptor");
3323 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3324 return -1;
3327 if ((options->BridgeRelay
3328 || options->_PublishServerDescriptor & BRIDGE_AUTHORITY)
3329 && (options->_PublishServerDescriptor
3330 & (V1_AUTHORITY|V2_AUTHORITY|V3_AUTHORITY))) {
3331 REJECT("Bridges are not supposed to publish router descriptors to the "
3332 "directory authorities. Please correct your "
3333 "PublishServerDescriptor line.");
3336 if (options->MinUptimeHidServDirectoryV2 < 0) {
3337 log_warn(LD_CONFIG, "MinUptimeHidServDirectoryV2 option must be at "
3338 "least 0 seconds. Changing to 0.");
3339 options->MinUptimeHidServDirectoryV2 = 0;
3342 if (options->RendPostPeriod < MIN_REND_POST_PERIOD) {
3343 log(LOG_WARN,LD_CONFIG,"RendPostPeriod option is too short; "
3344 "raising to %d seconds.", MIN_REND_POST_PERIOD);
3345 options->RendPostPeriod = MIN_REND_POST_PERIOD;
3348 if (options->RendPostPeriod > MAX_DIR_PERIOD) {
3349 log(LOG_WARN, LD_CONFIG, "RendPostPeriod is too large; clipping to %ds.",
3350 MAX_DIR_PERIOD);
3351 options->RendPostPeriod = MAX_DIR_PERIOD;
3354 if (options->CircuitBuildTimeout < MIN_CIRCUIT_BUILD_TIMEOUT) {
3355 log(LOG_WARN, LD_CONFIG, "CircuitBuildTimeout option is too short; "
3356 "raising to %d seconds.", MIN_CIRCUIT_BUILD_TIMEOUT);
3357 options->CircuitBuildTimeout = MIN_CIRCUIT_BUILD_TIMEOUT;
3360 if (options->MaxCircuitDirtiness < MIN_MAX_CIRCUIT_DIRTINESS) {
3361 log(LOG_WARN, LD_CONFIG, "MaxCircuitDirtiness option is too short; "
3362 "raising to %d seconds.", MIN_MAX_CIRCUIT_DIRTINESS);
3363 options->MaxCircuitDirtiness = MIN_MAX_CIRCUIT_DIRTINESS;
3366 if (options->KeepalivePeriod < 1)
3367 REJECT("KeepalivePeriod option must be positive.");
3369 if (ensure_bandwidth_cap(&options->BandwidthRate,
3370 "BandwidthRate", msg) < 0)
3371 return -1;
3372 if (ensure_bandwidth_cap(&options->BandwidthBurst,
3373 "BandwidthBurst", msg) < 0)
3374 return -1;
3375 if (ensure_bandwidth_cap(&options->MaxAdvertisedBandwidth,
3376 "MaxAdvertisedBandwidth", msg) < 0)
3377 return -1;
3378 if (ensure_bandwidth_cap(&options->RelayBandwidthRate,
3379 "RelayBandwidthRate", msg) < 0)
3380 return -1;
3381 if (ensure_bandwidth_cap(&options->RelayBandwidthBurst,
3382 "RelayBandwidthBurst", msg) < 0)
3383 return -1;
3385 if (server_mode(options)) {
3386 if (options->BandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
3387 r = tor_snprintf(buf, sizeof(buf),
3388 "BandwidthRate is set to %d bytes/second. "
3389 "For servers, it must be at least %d.",
3390 (int)options->BandwidthRate,
3391 ROUTER_REQUIRED_MIN_BANDWIDTH);
3392 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3393 return -1;
3394 } else if (options->MaxAdvertisedBandwidth <
3395 ROUTER_REQUIRED_MIN_BANDWIDTH/2) {
3396 r = tor_snprintf(buf, sizeof(buf),
3397 "MaxAdvertisedBandwidth is set to %d bytes/second. "
3398 "For servers, it must be at least %d.",
3399 (int)options->MaxAdvertisedBandwidth,
3400 ROUTER_REQUIRED_MIN_BANDWIDTH/2);
3401 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3402 return -1;
3404 if (options->RelayBandwidthRate &&
3405 options->RelayBandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
3406 r = tor_snprintf(buf, sizeof(buf),
3407 "RelayBandwidthRate is set to %d bytes/second. "
3408 "For servers, it must be at least %d.",
3409 (int)options->RelayBandwidthRate,
3410 ROUTER_REQUIRED_MIN_BANDWIDTH);
3411 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3412 return -1;
3416 if (options->RelayBandwidthRate && !options->RelayBandwidthBurst)
3417 options->RelayBandwidthBurst = options->RelayBandwidthRate;
3419 if (options->RelayBandwidthRate > options->RelayBandwidthBurst)
3420 REJECT("RelayBandwidthBurst must be at least equal "
3421 "to RelayBandwidthRate.");
3423 if (options->BandwidthRate > options->BandwidthBurst)
3424 REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
3426 /* if they set relaybandwidth* really high but left bandwidth*
3427 * at the default, raise the defaults. */
3428 if (options->RelayBandwidthRate > options->BandwidthRate)
3429 options->BandwidthRate = options->RelayBandwidthRate;
3430 if (options->RelayBandwidthBurst > options->BandwidthBurst)
3431 options->BandwidthBurst = options->RelayBandwidthBurst;
3433 if (accounting_parse_options(options, 1)<0)
3434 REJECT("Failed to parse accounting options. See logs for details.");
3436 if (options->HttpProxy) { /* parse it now */
3437 if (parse_addr_port(LOG_WARN, options->HttpProxy, NULL,
3438 &options->HttpProxyAddr, &options->HttpProxyPort) < 0)
3439 REJECT("HttpProxy failed to parse or resolve. Please fix.");
3440 if (options->HttpProxyPort == 0) { /* give it a default */
3441 options->HttpProxyPort = 80;
3445 if (options->HttpProxyAuthenticator) {
3446 if (strlen(options->HttpProxyAuthenticator) >= 48)
3447 REJECT("HttpProxyAuthenticator is too long (>= 48 chars).");
3450 if (options->HttpsProxy) { /* parse it now */
3451 if (parse_addr_port(LOG_WARN, options->HttpsProxy, NULL,
3452 &options->HttpsProxyAddr, &options->HttpsProxyPort) <0)
3453 REJECT("HttpsProxy failed to parse or resolve. Please fix.");
3454 if (options->HttpsProxyPort == 0) { /* give it a default */
3455 options->HttpsProxyPort = 443;
3459 if (options->HttpsProxyAuthenticator) {
3460 if (strlen(options->HttpsProxyAuthenticator) >= 48)
3461 REJECT("HttpsProxyAuthenticator is too long (>= 48 chars).");
3464 if (options->HashedControlPassword) {
3465 smartlist_t *sl = decode_hashed_passwords(options->HashedControlPassword);
3466 if (!sl) {
3467 REJECT("Bad HashedControlPassword: wrong length or bad encoding");
3468 } else {
3469 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3470 smartlist_free(sl);
3474 if (options->HashedControlSessionPassword) {
3475 smartlist_t *sl = decode_hashed_passwords(
3476 options->HashedControlSessionPassword);
3477 if (!sl) {
3478 REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
3479 } else {
3480 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3481 smartlist_free(sl);
3485 if (options->ControlListenAddress) {
3486 int all_are_local = 1;
3487 config_line_t *ln;
3488 for (ln = options->ControlListenAddress; ln; ln = ln->next) {
3489 if (strcmpstart(ln->value, "127."))
3490 all_are_local = 0;
3492 if (!all_are_local) {
3493 if (!options->HashedControlPassword &&
3494 !options->HashedControlSessionPassword &&
3495 !options->CookieAuthentication) {
3496 log_warn(LD_CONFIG,
3497 "You have a ControlListenAddress set to accept "
3498 "unauthenticated connections from a non-local address. "
3499 "This means that programs not running on your computer "
3500 "can reconfigure your Tor, without even having to guess a "
3501 "password. That's so bad that I'm closing your ControlPort "
3502 "for you. If you need to control your Tor remotely, try "
3503 "enabling authentication and using a tool like stunnel or "
3504 "ssh to encrypt remote access.");
3505 options->ControlPort = 0;
3506 } else {
3507 log_warn(LD_CONFIG, "You have a ControlListenAddress set to accept "
3508 "connections from a non-local address. This means that "
3509 "programs not running on your computer can reconfigure your "
3510 "Tor. That's pretty bad, since the controller "
3511 "protocol isn't encrypted! Maybe you should just listen on "
3512 "127.0.0.1 and use a tool like stunnel or ssh to encrypt "
3513 "remote connections to your control port.");
3518 if (options->ControlPort && !options->HashedControlPassword &&
3519 !options->HashedControlSessionPassword &&
3520 !options->CookieAuthentication) {
3521 log_warn(LD_CONFIG, "ControlPort is open, but no authentication method "
3522 "has been configured. This means that any program on your "
3523 "computer can reconfigure your Tor. That's bad! You should "
3524 "upgrade your Tor controller as soon as possible.");
3527 if (options->UseEntryGuards && ! options->NumEntryGuards)
3528 REJECT("Cannot enable UseEntryGuards with NumEntryGuards set to 0");
3530 if (check_nickname_list(options->MyFamily, "MyFamily", msg))
3531 return -1;
3532 for (cl = options->NodeFamilies; cl; cl = cl->next) {
3533 if (check_nickname_list(cl->value, "NodeFamily", msg))
3534 return -1;
3537 if (validate_addr_policies(options, msg) < 0)
3538 return -1;
3540 if (validate_dir_authorities(options, old_options) < 0)
3541 REJECT("Directory authority line did not parse. See logs for details.");
3543 if (options->UseBridges && !options->Bridges)
3544 REJECT("If you set UseBridges, you must specify at least one bridge.");
3545 if (options->UseBridges && !options->TunnelDirConns)
3546 REJECT("If you set UseBridges, you must set TunnelDirConns.");
3547 if (options->Bridges) {
3548 for (cl = options->Bridges; cl; cl = cl->next) {
3549 if (parse_bridge_line(cl->value, 1)<0)
3550 REJECT("Bridge line did not parse. See logs for details.");
3554 if (options->ConstrainedSockets) {
3555 /* If the user wants to constrain socket buffer use, make sure the desired
3556 * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
3557 if (options->ConstrainedSockSize < MIN_CONSTRAINED_TCP_BUFFER ||
3558 options->ConstrainedSockSize > MAX_CONSTRAINED_TCP_BUFFER ||
3559 options->ConstrainedSockSize % 1024) {
3560 r = tor_snprintf(buf, sizeof(buf),
3561 "ConstrainedSockSize is invalid. Must be a value between %d and %d "
3562 "in 1024 byte increments.",
3563 MIN_CONSTRAINED_TCP_BUFFER, MAX_CONSTRAINED_TCP_BUFFER);
3564 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3565 return -1;
3567 if (options->DirPort) {
3568 /* Providing cached directory entries while system TCP buffers are scarce
3569 * will exacerbate the socket errors. Suggest that this be disabled. */
3570 COMPLAIN("You have requested constrained socket buffers while also "
3571 "serving directory entries via DirPort. It is strongly "
3572 "suggested that you disable serving directory requests when "
3573 "system TCP buffer resources are scarce.");
3577 if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
3578 options->V3AuthVotingInterval/2) {
3579 REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
3580 "V3AuthVotingInterval");
3582 if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS)
3583 REJECT("V3AuthVoteDelay is way too low.");
3584 if (options->V3AuthDistDelay < MIN_DIST_SECONDS)
3585 REJECT("V3AuthDistDelay is way too low.");
3587 if (options->V3AuthNIntervalsValid < 2)
3588 REJECT("V3AuthNIntervalsValid must be at least 2.");
3590 if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL) {
3591 REJECT("V3AuthVotingInterval is insanely low.");
3592 } else if (options->V3AuthVotingInterval > 24*60*60) {
3593 REJECT("V3AuthVotingInterval is insanely high.");
3594 } else if (((24*60*60) % options->V3AuthVotingInterval) != 0) {
3595 COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
3598 if (rend_config_services(options, 1) < 0)
3599 REJECT("Failed to configure rendezvous options. See logs for details.");
3601 /* Parse client-side authorization for hidden services. */
3602 if (rend_parse_service_authorization(options, 1) < 0)
3603 REJECT("Failed to configure client authorization for hidden services. "
3604 "See logs for details.");
3606 if (parse_virtual_addr_network(options->VirtualAddrNetwork, 1, NULL)<0)
3607 return -1;
3609 if (options->PreferTunneledDirConns && !options->TunnelDirConns)
3610 REJECT("Must set TunnelDirConns if PreferTunneledDirConns is set.");
3612 if (options->AutomapHostsSuffixes) {
3613 SMARTLIST_FOREACH(options->AutomapHostsSuffixes, char *, suf,
3615 size_t len = strlen(suf);
3616 if (len && suf[len-1] == '.')
3617 suf[len-1] = '\0';
3621 if (options->TestingTorNetwork && !options->DirServers) {
3622 REJECT("TestingTorNetwork may only be configured in combination with "
3623 "a non-default set of DirServers.");
3626 /*XXXX022 checking for defaults manually like this is a bit fragile.*/
3628 /* Keep changes to hard-coded values synchronous to man page and default
3629 * values table. */
3630 if (options->TestingV3AuthInitialVotingInterval != 30*60 &&
3631 !options->TestingTorNetwork) {
3632 REJECT("TestingV3AuthInitialVotingInterval may only be changed in testing "
3633 "Tor networks!");
3634 } else if (options->TestingV3AuthInitialVotingInterval < MIN_VOTE_INTERVAL) {
3635 REJECT("TestingV3AuthInitialVotingInterval is insanely low.");
3636 } else if (((30*60) % options->TestingV3AuthInitialVotingInterval) != 0) {
3637 REJECT("TestingV3AuthInitialVotingInterval does not divide evenly into "
3638 "30 minutes.");
3641 if (options->TestingV3AuthInitialVoteDelay != 5*60 &&
3642 !options->TestingTorNetwork) {
3643 REJECT("TestingV3AuthInitialVoteDelay may only be changed in testing "
3644 "Tor networks!");
3645 } else if (options->TestingV3AuthInitialVoteDelay < MIN_VOTE_SECONDS) {
3646 REJECT("TestingV3AuthInitialVoteDelay is way too low.");
3649 if (options->TestingV3AuthInitialDistDelay != 5*60 &&
3650 !options->TestingTorNetwork) {
3651 REJECT("TestingV3AuthInitialDistDelay may only be changed in testing "
3652 "Tor networks!");
3653 } else if (options->TestingV3AuthInitialDistDelay < MIN_DIST_SECONDS) {
3654 REJECT("TestingV3AuthInitialDistDelay is way too low.");
3657 if (options->TestingV3AuthInitialVoteDelay +
3658 options->TestingV3AuthInitialDistDelay >=
3659 options->TestingV3AuthInitialVotingInterval/2) {
3660 REJECT("TestingV3AuthInitialVoteDelay plus TestingV3AuthInitialDistDelay "
3661 "must be less than half TestingV3AuthInitialVotingInterval");
3664 if (options->TestingAuthDirTimeToLearnReachability != 30*60 &&
3665 !options->TestingTorNetwork) {
3666 REJECT("TestingAuthDirTimeToLearnReachability may only be changed in "
3667 "testing Tor networks!");
3668 } else if (options->TestingAuthDirTimeToLearnReachability < 0) {
3669 REJECT("TestingAuthDirTimeToLearnReachability must be non-negative.");
3670 } else if (options->TestingAuthDirTimeToLearnReachability > 2*60*60) {
3671 COMPLAIN("TestingAuthDirTimeToLearnReachability is insanely high.");
3674 if (options->TestingEstimatedDescriptorPropagationTime != 10*60 &&
3675 !options->TestingTorNetwork) {
3676 REJECT("TestingEstimatedDescriptorPropagationTime may only be changed in "
3677 "testing Tor networks!");
3678 } else if (options->TestingEstimatedDescriptorPropagationTime < 0) {
3679 REJECT("TestingEstimatedDescriptorPropagationTime must be non-negative.");
3680 } else if (options->TestingEstimatedDescriptorPropagationTime > 60*60) {
3681 COMPLAIN("TestingEstimatedDescriptorPropagationTime is insanely high.");
3684 if (options->TestingTorNetwork) {
3685 log_warn(LD_CONFIG, "TestingTorNetwork is set. This will make your node "
3686 "almost unusable in the public Tor network, and is "
3687 "therefore only advised if you are building a "
3688 "testing Tor network!");
3691 if (options->AccelName && !options->HardwareAccel)
3692 options->HardwareAccel = 1;
3693 if (options->AccelDir && !options->AccelName)
3694 REJECT("Can't use hardware crypto accelerator dir without engine name.");
3696 return 0;
3697 #undef REJECT
3698 #undef COMPLAIN
3701 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
3702 * equal strings. */
3703 static int
3704 opt_streq(const char *s1, const char *s2)
3706 if (!s1 && !s2)
3707 return 1;
3708 else if (s1 && s2 && !strcmp(s1,s2))
3709 return 1;
3710 else
3711 return 0;
3714 /** Check if any of the previous options have changed but aren't allowed to. */
3715 static int
3716 options_transition_allowed(or_options_t *old, or_options_t *new_val,
3717 char **msg)
3719 if (!old)
3720 return 0;
3722 if (!opt_streq(old->PidFile, new_val->PidFile)) {
3723 *msg = tor_strdup("PidFile is not allowed to change.");
3724 return -1;
3727 if (old->RunAsDaemon != new_val->RunAsDaemon) {
3728 *msg = tor_strdup("While Tor is running, changing RunAsDaemon "
3729 "is not allowed.");
3730 return -1;
3733 if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
3734 char buf[1024];
3735 int r = tor_snprintf(buf, sizeof(buf),
3736 "While Tor is running, changing DataDirectory "
3737 "(\"%s\"->\"%s\") is not allowed.",
3738 old->DataDirectory, new_val->DataDirectory);
3739 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3740 return -1;
3743 if (!opt_streq(old->User, new_val->User)) {
3744 *msg = tor_strdup("While Tor is running, changing User is not allowed.");
3745 return -1;
3748 if (!opt_streq(old->Group, new_val->Group)) {
3749 *msg = tor_strdup("While Tor is running, changing Group is not allowed.");
3750 return -1;
3753 if ((old->HardwareAccel != new_val->HardwareAccel)
3754 || !opt_streq(old->AccelName, new_val->AccelName)
3755 || !opt_streq(old->AccelDir, new_val->AccelDir)) {
3756 *msg = tor_strdup("While Tor is running, changing OpenSSL hardware "
3757 "acceleration engine is not allowed.");
3758 return -1;
3761 if (old->TestingTorNetwork != new_val->TestingTorNetwork) {
3762 *msg = tor_strdup("While Tor is running, changing TestingTorNetwork "
3763 "is not allowed.");
3764 return -1;
3767 return 0;
3770 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3771 * will require us to rotate the CPU and DNS workers; else return 0. */
3772 static int
3773 options_transition_affects_workers(or_options_t *old_options,
3774 or_options_t *new_options)
3776 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
3777 old_options->NumCpus != new_options->NumCpus ||
3778 old_options->ORPort != new_options->ORPort ||
3779 old_options->ServerDNSSearchDomains !=
3780 new_options->ServerDNSSearchDomains ||
3781 old_options->SafeLogging != new_options->SafeLogging ||
3782 old_options->ClientOnly != new_options->ClientOnly ||
3783 !config_lines_eq(old_options->Logs, new_options->Logs))
3784 return 1;
3786 /* Check whether log options match. */
3788 /* Nothing that changed matters. */
3789 return 0;
3792 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3793 * will require us to generate a new descriptor; else return 0. */
3794 static int
3795 options_transition_affects_descriptor(or_options_t *old_options,
3796 or_options_t *new_options)
3798 /* XXX We can be smarter here. If your DirPort isn't being
3799 * published and you just turned it off, no need to republish. If
3800 * you changed your bandwidthrate but maxadvertisedbandwidth still
3801 * trumps, no need to republish. Etc. */
3802 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
3803 !opt_streq(old_options->Nickname,new_options->Nickname) ||
3804 !opt_streq(old_options->Address,new_options->Address) ||
3805 !config_lines_eq(old_options->ExitPolicy,new_options->ExitPolicy) ||
3806 old_options->ExitPolicyRejectPrivate !=
3807 new_options->ExitPolicyRejectPrivate ||
3808 old_options->ORPort != new_options->ORPort ||
3809 old_options->DirPort != new_options->DirPort ||
3810 old_options->ClientOnly != new_options->ClientOnly ||
3811 old_options->NoPublish != new_options->NoPublish ||
3812 old_options->_PublishServerDescriptor !=
3813 new_options->_PublishServerDescriptor ||
3814 old_options->BandwidthRate != new_options->BandwidthRate ||
3815 old_options->BandwidthBurst != new_options->BandwidthBurst ||
3816 old_options->MaxAdvertisedBandwidth !=
3817 new_options->MaxAdvertisedBandwidth ||
3818 !opt_streq(old_options->ContactInfo, new_options->ContactInfo) ||
3819 !opt_streq(old_options->MyFamily, new_options->MyFamily) ||
3820 !opt_streq(old_options->AccountingStart, new_options->AccountingStart) ||
3821 old_options->AccountingMax != new_options->AccountingMax)
3822 return 1;
3824 return 0;
3827 #ifdef MS_WINDOWS
3828 /** Return the directory on windows where we expect to find our application
3829 * data. */
3830 static char *
3831 get_windows_conf_root(void)
3833 static int is_set = 0;
3834 static char path[MAX_PATH+1];
3836 LPITEMIDLIST idl;
3837 IMalloc *m;
3838 HRESULT result;
3840 if (is_set)
3841 return path;
3843 /* Find X:\documents and settings\username\application data\ .
3844 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
3846 #ifdef ENABLE_LOCAL_APPDATA
3847 #define APPDATA_PATH CSIDL_LOCAL_APPDATA
3848 #else
3849 #define APPDATA_PATH CSIDL_APPDATA
3850 #endif
3851 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, APPDATA_PATH, &idl))) {
3852 GetCurrentDirectory(MAX_PATH, path);
3853 is_set = 1;
3854 log_warn(LD_CONFIG,
3855 "I couldn't find your application data folder: are you "
3856 "running an ancient version of Windows 95? Defaulting to \"%s\"",
3857 path);
3858 return path;
3860 /* Convert the path from an "ID List" (whatever that is!) to a path. */
3861 result = SHGetPathFromIDList(idl, path);
3862 /* Now we need to free the */
3863 SHGetMalloc(&m);
3864 if (m) {
3865 m->lpVtbl->Free(m, idl);
3866 m->lpVtbl->Release(m);
3868 if (!SUCCEEDED(result)) {
3869 return NULL;
3871 strlcat(path,"\\tor",MAX_PATH);
3872 is_set = 1;
3873 return path;
3875 #endif
3877 /** Return the default location for our torrc file. */
3878 static const char *
3879 get_default_conf_file(void)
3881 #ifdef MS_WINDOWS
3882 static char path[MAX_PATH+1];
3883 strlcpy(path, get_windows_conf_root(), MAX_PATH);
3884 strlcat(path,"\\torrc",MAX_PATH);
3885 return path;
3886 #else
3887 return (CONFDIR "/torrc");
3888 #endif
3891 /** Verify whether lst is a string containing valid-looking comma-separated
3892 * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
3894 static int
3895 check_nickname_list(const char *lst, const char *name, char **msg)
3897 int r = 0;
3898 smartlist_t *sl;
3900 if (!lst)
3901 return 0;
3902 sl = smartlist_create();
3904 smartlist_split_string(sl, lst, ",",
3905 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK|SPLIT_STRIP_SPACE, 0);
3907 SMARTLIST_FOREACH(sl, const char *, s,
3909 if (!is_legal_nickname_or_hexdigest(s)) {
3910 char buf[1024];
3911 int tmp = tor_snprintf(buf, sizeof(buf),
3912 "Invalid nickname '%s' in %s line", s, name);
3913 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
3914 r = -1;
3915 break;
3918 SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
3919 smartlist_free(sl);
3920 return r;
3923 /** Learn config file name from command line arguments, or use the default */
3924 static char *
3925 find_torrc_filename(int argc, char **argv,
3926 int *using_default_torrc, int *ignore_missing_torrc)
3928 char *fname=NULL;
3929 int i;
3931 for (i = 1; i < argc; ++i) {
3932 if (i < argc-1 && !strcmp(argv[i],"-f")) {
3933 if (fname) {
3934 log(LOG_WARN, LD_CONFIG, "Duplicate -f options on command line.");
3935 tor_free(fname);
3937 #ifdef MS_WINDOWS
3938 /* XXX one day we might want to extend expand_filename to work
3939 * under Windows as well. */
3940 fname = tor_strdup(argv[i+1]);
3941 #else
3942 fname = expand_filename(argv[i+1]);
3943 #endif
3944 *using_default_torrc = 0;
3945 ++i;
3946 } else if (!strcmp(argv[i],"--ignore-missing-torrc")) {
3947 *ignore_missing_torrc = 1;
3951 if (*using_default_torrc) {
3952 /* didn't find one, try CONFDIR */
3953 const char *dflt = get_default_conf_file();
3954 if (dflt && file_status(dflt) == FN_FILE) {
3955 fname = tor_strdup(dflt);
3956 } else {
3957 #ifndef MS_WINDOWS
3958 char *fn;
3959 fn = expand_filename("~/.torrc");
3960 if (fn && file_status(fn) == FN_FILE) {
3961 fname = fn;
3962 } else {
3963 tor_free(fn);
3964 fname = tor_strdup(dflt);
3966 #else
3967 fname = tor_strdup(dflt);
3968 #endif
3971 return fname;
3974 /** Load torrc from disk, setting torrc_fname if successful */
3975 static char *
3976 load_torrc_from_disk(int argc, char **argv)
3978 char *fname=NULL;
3979 char *cf = NULL;
3980 int using_default_torrc = 1;
3981 int ignore_missing_torrc = 0;
3983 fname = find_torrc_filename(argc, argv,
3984 &using_default_torrc, &ignore_missing_torrc);
3985 tor_assert(fname);
3986 log(LOG_DEBUG, LD_CONFIG, "Opening config file \"%s\"", fname);
3988 tor_free(torrc_fname);
3989 torrc_fname = fname;
3991 /* Open config file */
3992 if (file_status(fname) != FN_FILE ||
3993 !(cf = read_file_to_str(fname,0,NULL))) {
3994 if (using_default_torrc == 1 || ignore_missing_torrc ) {
3995 log(LOG_NOTICE, LD_CONFIG, "Configuration file \"%s\" not present, "
3996 "using reasonable defaults.", fname);
3997 tor_free(fname); /* sets fname to NULL */
3998 torrc_fname = NULL;
3999 cf = tor_strdup("");
4000 } else {
4001 log(LOG_WARN, LD_CONFIG,
4002 "Unable to open configuration file \"%s\".", fname);
4003 goto err;
4007 return cf;
4008 err:
4009 tor_free(fname);
4010 torrc_fname = NULL;
4011 return NULL;
4014 /** Read a configuration file into <b>options</b>, finding the configuration
4015 * file location based on the command line. After loading the file
4016 * call options_init_from_string() to load the config.
4017 * Return 0 if success, -1 if failure. */
4019 options_init_from_torrc(int argc, char **argv)
4021 char *cf=NULL;
4022 int i, retval, command;
4023 static char **backup_argv;
4024 static int backup_argc;
4025 char *command_arg = NULL;
4026 char *errmsg=NULL;
4028 if (argv) { /* first time we're called. save command line args */
4029 backup_argv = argv;
4030 backup_argc = argc;
4031 } else { /* we're reloading. need to clean up old options first. */
4032 argv = backup_argv;
4033 argc = backup_argc;
4035 if (argc > 1 && (!strcmp(argv[1], "-h") || !strcmp(argv[1],"--help"))) {
4036 print_usage();
4037 exit(0);
4039 if (argc > 1 && !strcmp(argv[1], "--list-torrc-options")) {
4040 /* For documenting validating whether we've documented everything. */
4041 list_torrc_options();
4042 exit(0);
4045 if (argc > 1 && (!strcmp(argv[1],"--version"))) {
4046 printf("Tor version %s.\n",get_version());
4047 exit(0);
4049 if (argc > 1 && (!strcmp(argv[1],"--digests"))) {
4050 printf("Tor version %s.\n",get_version());
4051 printf("%s", libor_get_digests());
4052 printf("%s", tor_get_digests());
4053 exit(0);
4056 /* Go through command-line variables */
4057 if (!global_cmdline_options) {
4058 /* Or we could redo the list every time we pass this place.
4059 * It does not really matter */
4060 if (config_get_commandlines(argc, argv, &global_cmdline_options) < 0) {
4061 goto err;
4065 command = CMD_RUN_TOR;
4066 for (i = 1; i < argc; ++i) {
4067 if (!strcmp(argv[i],"--list-fingerprint")) {
4068 command = CMD_LIST_FINGERPRINT;
4069 } else if (!strcmp(argv[i],"--hash-password")) {
4070 command = CMD_HASH_PASSWORD;
4071 command_arg = tor_strdup( (i < argc-1) ? argv[i+1] : "");
4072 ++i;
4073 } else if (!strcmp(argv[i],"--verify-config")) {
4074 command = CMD_VERIFY_CONFIG;
4078 if (command == CMD_HASH_PASSWORD) {
4079 cf = tor_strdup("");
4080 } else {
4081 cf = load_torrc_from_disk(argc, argv);
4082 if (!cf)
4083 goto err;
4086 retval = options_init_from_string(cf, command, command_arg, &errmsg);
4087 tor_free(cf);
4088 if (retval < 0)
4089 goto err;
4091 return 0;
4093 err:
4094 if (errmsg) {
4095 log(LOG_WARN,LD_CONFIG,"%s", errmsg);
4096 tor_free(errmsg);
4098 return -1;
4101 /** Load the options from the configuration in <b>cf</b>, validate
4102 * them for consistency and take actions based on them.
4104 * Return 0 if success, negative on error:
4105 * * -1 for general errors.
4106 * * -2 for failure to parse/validate,
4107 * * -3 for transition not allowed
4108 * * -4 for error while setting the new options
4110 setopt_err_t
4111 options_init_from_string(const char *cf,
4112 int command, const char *command_arg,
4113 char **msg)
4115 or_options_t *oldoptions, *newoptions;
4116 config_line_t *cl;
4117 int retval;
4118 setopt_err_t err = SETOPT_ERR_MISC;
4119 tor_assert(msg);
4121 oldoptions = global_options; /* get_options unfortunately asserts if
4122 this is the first time we run*/
4124 newoptions = tor_malloc_zero(sizeof(or_options_t));
4125 newoptions->_magic = OR_OPTIONS_MAGIC;
4126 options_init(newoptions);
4127 newoptions->command = command;
4128 newoptions->command_arg = command_arg;
4130 /* get config lines, assign them */
4131 retval = config_get_lines(cf, &cl);
4132 if (retval < 0) {
4133 err = SETOPT_ERR_PARSE;
4134 goto err;
4136 retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
4137 config_free_lines(cl);
4138 if (retval < 0) {
4139 err = SETOPT_ERR_PARSE;
4140 goto err;
4143 /* Go through command-line variables too */
4144 retval = config_assign(&options_format, newoptions,
4145 global_cmdline_options, 0, 0, msg);
4146 if (retval < 0) {
4147 err = SETOPT_ERR_PARSE;
4148 goto err;
4151 /* If this is a testing network configuration, change defaults
4152 * for a list of dependent config options, re-initialize newoptions
4153 * with the new defaults, and assign all options to it second time. */
4154 if (newoptions->TestingTorNetwork) {
4155 /* XXXX this is a bit of a kludge. perhaps there's a better way to do
4156 * this? We could, for example, make the parsing algorithm do two passes
4157 * over the configuration. If it finds any "suite" options like
4158 * TestingTorNetwork, it could change the defaults before its second pass.
4159 * Not urgent so long as this seems to work, but at any sign of trouble,
4160 * let's clean it up. -NM */
4162 /* Change defaults. */
4163 int i;
4164 for (i = 0; testing_tor_network_defaults[i].name; ++i) {
4165 config_var_t *new_var = &testing_tor_network_defaults[i];
4166 config_var_t *old_var =
4167 config_find_option(&options_format, new_var->name);
4168 tor_assert(new_var);
4169 tor_assert(old_var);
4170 old_var->initvalue = new_var->initvalue;
4173 /* Clear newoptions and re-initialize them with new defaults. */
4174 config_free(&options_format, newoptions);
4175 newoptions = tor_malloc_zero(sizeof(or_options_t));
4176 newoptions->_magic = OR_OPTIONS_MAGIC;
4177 options_init(newoptions);
4178 newoptions->command = command;
4179 newoptions->command_arg = command_arg;
4181 /* Assign all options a second time. */
4182 retval = config_get_lines(cf, &cl);
4183 if (retval < 0) {
4184 err = SETOPT_ERR_PARSE;
4185 goto err;
4187 retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
4188 config_free_lines(cl);
4189 if (retval < 0) {
4190 err = SETOPT_ERR_PARSE;
4191 goto err;
4193 retval = config_assign(&options_format, newoptions,
4194 global_cmdline_options, 0, 0, msg);
4195 if (retval < 0) {
4196 err = SETOPT_ERR_PARSE;
4197 goto err;
4201 /* Validate newoptions */
4202 if (options_validate(oldoptions, newoptions, 0, msg) < 0) {
4203 err = SETOPT_ERR_PARSE; /*XXX make this a separate return value.*/
4204 goto err;
4207 if (options_transition_allowed(oldoptions, newoptions, msg) < 0) {
4208 err = SETOPT_ERR_TRANSITION;
4209 goto err;
4212 if (set_options(newoptions, msg)) {
4213 err = SETOPT_ERR_SETTING;
4214 goto err; /* frees and replaces old options */
4217 return SETOPT_OK;
4219 err:
4220 config_free(&options_format, newoptions);
4221 if (*msg) {
4222 int len = strlen(*msg)+256;
4223 char *newmsg = tor_malloc(len);
4225 tor_snprintf(newmsg, len, "Failed to parse/validate config: %s", *msg);
4226 tor_free(*msg);
4227 *msg = newmsg;
4229 return err;
4232 /** Return the location for our configuration file.
4234 const char *
4235 get_torrc_fname(void)
4237 if (torrc_fname)
4238 return torrc_fname;
4239 else
4240 return get_default_conf_file();
4243 /** Adjust the address map based on the MapAddress elements in the
4244 * configuration <b>options</b>
4246 static void
4247 config_register_addressmaps(or_options_t *options)
4249 smartlist_t *elts;
4250 config_line_t *opt;
4251 char *from, *to;
4253 addressmap_clear_configured();
4254 elts = smartlist_create();
4255 for (opt = options->AddressMap; opt; opt = opt->next) {
4256 smartlist_split_string(elts, opt->value, NULL,
4257 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
4258 if (smartlist_len(elts) >= 2) {
4259 from = smartlist_get(elts,0);
4260 to = smartlist_get(elts,1);
4261 if (address_is_invalid_destination(to, 1)) {
4262 log_warn(LD_CONFIG,
4263 "Skipping invalid argument '%s' to MapAddress", to);
4264 } else {
4265 addressmap_register(from, tor_strdup(to), 0, ADDRMAPSRC_TORRC);
4266 if (smartlist_len(elts)>2) {
4267 log_warn(LD_CONFIG,"Ignoring extra arguments to MapAddress.");
4270 } else {
4271 log_warn(LD_CONFIG,"MapAddress '%s' has too few arguments. Ignoring.",
4272 opt->value);
4274 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
4275 smartlist_clear(elts);
4277 smartlist_free(elts);
4281 * Initialize the logs based on the configuration file.
4283 static int
4284 options_init_logs(or_options_t *options, int validate_only)
4286 config_line_t *opt;
4287 int ok;
4288 smartlist_t *elts;
4289 int daemon =
4290 #ifdef MS_WINDOWS
4292 #else
4293 options->RunAsDaemon;
4294 #endif
4296 ok = 1;
4297 elts = smartlist_create();
4299 for (opt = options->Logs; opt; opt = opt->next) {
4300 log_severity_list_t *severity;
4301 const char *cfg = opt->value;
4302 severity = tor_malloc_zero(sizeof(log_severity_list_t));
4303 if (parse_log_severity_config(&cfg, severity) < 0) {
4304 log_warn(LD_CONFIG, "Couldn't parse log levels in Log option 'Log %s'",
4305 opt->value);
4306 ok = 0; goto cleanup;
4309 smartlist_split_string(elts, cfg, NULL,
4310 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
4312 if (smartlist_len(elts) == 0)
4313 smartlist_add(elts, tor_strdup("stdout"));
4315 if (smartlist_len(elts) == 1 &&
4316 (!strcasecmp(smartlist_get(elts,0), "stdout") ||
4317 !strcasecmp(smartlist_get(elts,0), "stderr"))) {
4318 int err = smartlist_len(elts) &&
4319 !strcasecmp(smartlist_get(elts,0), "stderr");
4320 if (!validate_only) {
4321 if (daemon) {
4322 log_warn(LD_CONFIG,
4323 "Can't log to %s with RunAsDaemon set; skipping stdout",
4324 err?"stderr":"stdout");
4325 } else {
4326 add_stream_log(severity, err?"<stderr>":"<stdout>",
4327 fileno(err?stderr:stdout));
4330 goto cleanup;
4332 if (smartlist_len(elts) == 1 &&
4333 !strcasecmp(smartlist_get(elts,0), "syslog")) {
4334 #ifdef HAVE_SYSLOG_H
4335 if (!validate_only) {
4336 add_syslog_log(severity);
4338 #else
4339 log_warn(LD_CONFIG, "Syslog is not supported on this system. Sorry.");
4340 #endif
4341 goto cleanup;
4344 if (smartlist_len(elts) == 2 &&
4345 !strcasecmp(smartlist_get(elts,0), "file")) {
4346 if (!validate_only) {
4347 if (add_file_log(severity, smartlist_get(elts, 1)) < 0) {
4348 log_warn(LD_CONFIG, "Couldn't open file for 'Log %s': %s",
4349 opt->value, strerror(errno));
4350 ok = 0;
4353 goto cleanup;
4356 log_warn(LD_CONFIG, "Bad syntax on file Log option 'Log %s'",
4357 opt->value);
4358 ok = 0; goto cleanup;
4360 cleanup:
4361 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
4362 smartlist_clear(elts);
4363 tor_free(severity);
4365 smartlist_free(elts);
4367 return ok?0:-1;
4370 /** Read the contents of a Bridge line from <b>line</b>. Return 0
4371 * if the line is well-formed, and -1 if it isn't. If
4372 * <b>validate_only</b> is 0, and the line is well-formed, then add
4373 * the bridge described in the line to our internal bridge list. */
4374 static int
4375 parse_bridge_line(const char *line, int validate_only)
4377 smartlist_t *items = NULL;
4378 int r;
4379 char *addrport=NULL, *fingerprint=NULL;
4380 tor_addr_t addr;
4381 uint16_t port = 0;
4382 char digest[DIGEST_LEN];
4384 items = smartlist_create();
4385 smartlist_split_string(items, line, NULL,
4386 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4387 if (smartlist_len(items) < 1) {
4388 log_warn(LD_CONFIG, "Too few arguments to Bridge line.");
4389 goto err;
4391 addrport = smartlist_get(items, 0);
4392 smartlist_del_keeporder(items, 0);
4393 if (tor_addr_port_parse(addrport, &addr, &port)<0) {
4394 log_warn(LD_CONFIG, "Error parsing Bridge address '%s'", addrport);
4395 goto err;
4397 if (!port) {
4398 log_info(LD_CONFIG,
4399 "Bridge address '%s' has no port; using default port 443.",
4400 addrport);
4401 port = 443;
4404 if (smartlist_len(items)) {
4405 fingerprint = smartlist_join_strings(items, "", 0, NULL);
4406 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
4407 log_warn(LD_CONFIG, "Key digest for Bridge is wrong length.");
4408 goto err;
4410 if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
4411 log_warn(LD_CONFIG, "Unable to decode Bridge key digest.");
4412 goto err;
4416 if (!validate_only) {
4417 log_debug(LD_DIR, "Bridge at %s:%d (%s)", fmt_addr(&addr),
4418 (int)port,
4419 fingerprint ? fingerprint : "no key listed");
4420 bridge_add_from_config(&addr, port, fingerprint ? digest : NULL);
4423 r = 0;
4424 goto done;
4426 err:
4427 r = -1;
4429 done:
4430 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4431 smartlist_free(items);
4432 tor_free(addrport);
4433 tor_free(fingerprint);
4434 return r;
4437 /** Read the contents of a DirServer line from <b>line</b>. If
4438 * <b>validate_only</b> is 0, and the line is well-formed, and it
4439 * shares any bits with <b>required_type</b> or <b>required_type</b>
4440 * is 0, then add the dirserver described in the line (minus whatever
4441 * bits it's missing) as a valid authority. Return 0 on success,
4442 * or -1 if the line isn't well-formed or if we can't add it. */
4443 static int
4444 parse_dir_server_line(const char *line, authority_type_t required_type,
4445 int validate_only)
4447 smartlist_t *items = NULL;
4448 int r;
4449 char *addrport=NULL, *address=NULL, *nickname=NULL, *fingerprint=NULL;
4450 uint16_t dir_port = 0, or_port = 0;
4451 char digest[DIGEST_LEN];
4452 char v3_digest[DIGEST_LEN];
4453 authority_type_t type = V2_AUTHORITY;
4454 int is_not_hidserv_authority = 0, is_not_v2_authority = 0;
4456 items = smartlist_create();
4457 smartlist_split_string(items, line, NULL,
4458 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4459 if (smartlist_len(items) < 1) {
4460 log_warn(LD_CONFIG, "No arguments on DirServer line.");
4461 goto err;
4464 if (is_legal_nickname(smartlist_get(items, 0))) {
4465 nickname = smartlist_get(items, 0);
4466 smartlist_del_keeporder(items, 0);
4469 while (smartlist_len(items)) {
4470 char *flag = smartlist_get(items, 0);
4471 if (TOR_ISDIGIT(flag[0]))
4472 break;
4473 if (!strcasecmp(flag, "v1")) {
4474 type |= (V1_AUTHORITY | HIDSERV_AUTHORITY);
4475 } else if (!strcasecmp(flag, "hs")) {
4476 type |= HIDSERV_AUTHORITY;
4477 } else if (!strcasecmp(flag, "no-hs")) {
4478 is_not_hidserv_authority = 1;
4479 } else if (!strcasecmp(flag, "bridge")) {
4480 type |= BRIDGE_AUTHORITY;
4481 } else if (!strcasecmp(flag, "no-v2")) {
4482 is_not_v2_authority = 1;
4483 } else if (!strcasecmpstart(flag, "orport=")) {
4484 int ok;
4485 char *portstring = flag + strlen("orport=");
4486 or_port = (uint16_t) tor_parse_long(portstring, 10, 1, 65535, &ok, NULL);
4487 if (!ok)
4488 log_warn(LD_CONFIG, "Invalid orport '%s' on DirServer line.",
4489 portstring);
4490 } else if (!strcasecmpstart(flag, "v3ident=")) {
4491 char *idstr = flag + strlen("v3ident=");
4492 if (strlen(idstr) != HEX_DIGEST_LEN ||
4493 base16_decode(v3_digest, DIGEST_LEN, idstr, HEX_DIGEST_LEN)<0) {
4494 log_warn(LD_CONFIG, "Bad v3 identity digest '%s' on DirServer line",
4495 flag);
4496 } else {
4497 type |= V3_AUTHORITY;
4499 } else {
4500 log_warn(LD_CONFIG, "Unrecognized flag '%s' on DirServer line",
4501 flag);
4503 tor_free(flag);
4504 smartlist_del_keeporder(items, 0);
4506 if (is_not_hidserv_authority)
4507 type &= ~HIDSERV_AUTHORITY;
4508 if (is_not_v2_authority)
4509 type &= ~V2_AUTHORITY;
4511 if (smartlist_len(items) < 2) {
4512 log_warn(LD_CONFIG, "Too few arguments to DirServer line.");
4513 goto err;
4515 addrport = smartlist_get(items, 0);
4516 smartlist_del_keeporder(items, 0);
4517 if (parse_addr_port(LOG_WARN, addrport, &address, NULL, &dir_port)<0) {
4518 log_warn(LD_CONFIG, "Error parsing DirServer address '%s'", addrport);
4519 goto err;
4521 if (!dir_port) {
4522 log_warn(LD_CONFIG, "Missing port in DirServer address '%s'",addrport);
4523 goto err;
4526 fingerprint = smartlist_join_strings(items, "", 0, NULL);
4527 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
4528 log_warn(LD_CONFIG, "Key digest for DirServer is wrong length %d.",
4529 (int)strlen(fingerprint));
4530 goto err;
4532 if (!strcmp(fingerprint, "E623F7625FBE0C87820F11EC5F6D5377ED816294")) {
4533 /* a known bad fingerprint. refuse to use it. We can remove this
4534 * clause once Tor 0.1.2.17 is obsolete. */
4535 log_warn(LD_CONFIG, "Dangerous dirserver line. To correct, erase your "
4536 "torrc file (%s), or reinstall Tor and use the default torrc.",
4537 get_torrc_fname());
4538 goto err;
4540 if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
4541 log_warn(LD_CONFIG, "Unable to decode DirServer key digest.");
4542 goto err;
4545 if (!validate_only && (!required_type || required_type & type)) {
4546 if (required_type)
4547 type &= required_type; /* pare down what we think of them as an
4548 * authority for. */
4549 log_debug(LD_DIR, "Trusted %d dirserver at %s:%d (%s)", (int)type,
4550 address, (int)dir_port, (char*)smartlist_get(items,0));
4551 if (!add_trusted_dir_server(nickname, address, dir_port, or_port,
4552 digest, v3_digest, type))
4553 goto err;
4556 r = 0;
4557 goto done;
4559 err:
4560 r = -1;
4562 done:
4563 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4564 smartlist_free(items);
4565 tor_free(addrport);
4566 tor_free(address);
4567 tor_free(nickname);
4568 tor_free(fingerprint);
4569 return r;
4572 /** Adjust the value of options->DataDirectory, or fill it in if it's
4573 * absent. Return 0 on success, -1 on failure. */
4574 static int
4575 normalize_data_directory(or_options_t *options)
4577 #ifdef MS_WINDOWS
4578 char *p;
4579 if (options->DataDirectory)
4580 return 0; /* all set */
4581 p = tor_malloc(MAX_PATH);
4582 strlcpy(p,get_windows_conf_root(),MAX_PATH);
4583 options->DataDirectory = p;
4584 return 0;
4585 #else
4586 const char *d = options->DataDirectory;
4587 if (!d)
4588 d = "~/.tor";
4590 if (strncmp(d,"~/",2) == 0) {
4591 char *fn = expand_filename(d);
4592 if (!fn) {
4593 log_warn(LD_CONFIG,"Failed to expand filename \"%s\".", d);
4594 return -1;
4596 if (!options->DataDirectory && !strcmp(fn,"/.tor")) {
4597 /* If our homedir is /, we probably don't want to use it. */
4598 /* Default to LOCALSTATEDIR/tor which is probably closer to what we
4599 * want. */
4600 log_warn(LD_CONFIG,
4601 "Default DataDirectory is \"~/.tor\". This expands to "
4602 "\"%s\", which is probably not what you want. Using "
4603 "\"%s"PATH_SEPARATOR"tor\" instead", fn, LOCALSTATEDIR);
4604 tor_free(fn);
4605 fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor");
4607 tor_free(options->DataDirectory);
4608 options->DataDirectory = fn;
4610 return 0;
4611 #endif
4614 /** Check and normalize the value of options->DataDirectory; return 0 if it
4615 * sane, -1 otherwise. */
4616 static int
4617 validate_data_directory(or_options_t *options)
4619 if (normalize_data_directory(options) < 0)
4620 return -1;
4621 tor_assert(options->DataDirectory);
4622 if (strlen(options->DataDirectory) > (512-128)) {
4623 log_warn(LD_CONFIG, "DataDirectory is too long.");
4624 return -1;
4626 return 0;
4629 /** This string must remain the same forevermore. It is how we
4630 * recognize that the torrc file doesn't need to be backed up. */
4631 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
4632 "if you edit it, comments will not be preserved"
4633 /** This string can change; it tries to give the reader an idea
4634 * that editing this file by hand is not a good plan. */
4635 #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
4636 "to torrc.orig.1 or similar, and Tor will ignore it"
4638 /** Save a configuration file for the configuration in <b>options</b>
4639 * into the file <b>fname</b>. If the file already exists, and
4640 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
4641 * replace it. Return 0 on success, -1 on failure. */
4642 static int
4643 write_configuration_file(const char *fname, or_options_t *options)
4645 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
4646 int rename_old = 0, r;
4647 size_t len;
4649 tor_assert(fname);
4651 switch (file_status(fname)) {
4652 case FN_FILE:
4653 old_val = read_file_to_str(fname, 0, NULL);
4654 if (strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
4655 rename_old = 1;
4657 tor_free(old_val);
4658 break;
4659 case FN_NOENT:
4660 break;
4661 case FN_ERROR:
4662 case FN_DIR:
4663 default:
4664 log_warn(LD_CONFIG,
4665 "Config file \"%s\" is not a file? Failing.", fname);
4666 return -1;
4669 if (!(new_conf = options_dump(options, 1))) {
4670 log_warn(LD_BUG, "Couldn't get configuration string");
4671 goto err;
4674 len = strlen(new_conf)+256;
4675 new_val = tor_malloc(len);
4676 tor_snprintf(new_val, len, "%s\n%s\n\n%s",
4677 GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
4679 if (rename_old) {
4680 int i = 1;
4681 size_t fn_tmp_len = strlen(fname)+32;
4682 char *fn_tmp;
4683 tor_assert(fn_tmp_len > strlen(fname)); /*check for overflow*/
4684 fn_tmp = tor_malloc(fn_tmp_len);
4685 while (1) {
4686 if (tor_snprintf(fn_tmp, fn_tmp_len, "%s.orig.%d", fname, i)<0) {
4687 log_warn(LD_BUG, "tor_snprintf failed inexplicably");
4688 tor_free(fn_tmp);
4689 goto err;
4691 if (file_status(fn_tmp) == FN_NOENT)
4692 break;
4693 ++i;
4695 log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
4696 if (rename(fname, fn_tmp) < 0) {
4697 log_warn(LD_FS,
4698 "Couldn't rename configuration file \"%s\" to \"%s\": %s",
4699 fname, fn_tmp, strerror(errno));
4700 tor_free(fn_tmp);
4701 goto err;
4703 tor_free(fn_tmp);
4706 if (write_str_to_file(fname, new_val, 0) < 0)
4707 goto err;
4709 r = 0;
4710 goto done;
4711 err:
4712 r = -1;
4713 done:
4714 tor_free(new_val);
4715 tor_free(new_conf);
4716 return r;
4720 * Save the current configuration file value to disk. Return 0 on
4721 * success, -1 on failure.
4724 options_save_current(void)
4726 if (torrc_fname) {
4727 /* This fails if we can't write to our configuration file.
4729 * If we try falling back to datadirectory or something, we have a better
4730 * chance of saving the configuration, but a better chance of doing
4731 * something the user never expected. Let's just warn instead. */
4732 return write_configuration_file(torrc_fname, get_options());
4734 return write_configuration_file(get_default_conf_file(), get_options());
4737 /** Mapping from a unit name to a multiplier for converting that unit into a
4738 * base unit. */
4739 struct unit_table_t {
4740 const char *unit;
4741 uint64_t multiplier;
4744 /** Table to map the names of memory units to the number of bytes they
4745 * contain. */
4746 static struct unit_table_t memory_units[] = {
4747 { "", 1 },
4748 { "b", 1<< 0 },
4749 { "byte", 1<< 0 },
4750 { "bytes", 1<< 0 },
4751 { "kb", 1<<10 },
4752 { "kbyte", 1<<10 },
4753 { "kbytes", 1<<10 },
4754 { "kilobyte", 1<<10 },
4755 { "kilobytes", 1<<10 },
4756 { "m", 1<<20 },
4757 { "mb", 1<<20 },
4758 { "mbyte", 1<<20 },
4759 { "mbytes", 1<<20 },
4760 { "megabyte", 1<<20 },
4761 { "megabytes", 1<<20 },
4762 { "gb", 1<<30 },
4763 { "gbyte", 1<<30 },
4764 { "gbytes", 1<<30 },
4765 { "gigabyte", 1<<30 },
4766 { "gigabytes", 1<<30 },
4767 { "tb", U64_LITERAL(1)<<40 },
4768 { "terabyte", U64_LITERAL(1)<<40 },
4769 { "terabytes", U64_LITERAL(1)<<40 },
4770 { NULL, 0 },
4773 /** Table to map the names of time units to the number of seconds they
4774 * contain. */
4775 static struct unit_table_t time_units[] = {
4776 { "", 1 },
4777 { "second", 1 },
4778 { "seconds", 1 },
4779 { "minute", 60 },
4780 { "minutes", 60 },
4781 { "hour", 60*60 },
4782 { "hours", 60*60 },
4783 { "day", 24*60*60 },
4784 { "days", 24*60*60 },
4785 { "week", 7*24*60*60 },
4786 { "weeks", 7*24*60*60 },
4787 { NULL, 0 },
4790 /** Parse a string <b>val</b> containing a number, zero or more
4791 * spaces, and an optional unit string. If the unit appears in the
4792 * table <b>u</b>, then multiply the number by the unit multiplier.
4793 * On success, set *<b>ok</b> to 1 and return this product.
4794 * Otherwise, set *<b>ok</b> to 0.
4796 static uint64_t
4797 config_parse_units(const char *val, struct unit_table_t *u, int *ok)
4799 uint64_t v;
4800 char *cp;
4802 tor_assert(ok);
4804 v = tor_parse_uint64(val, 10, 0, UINT64_MAX, ok, &cp);
4805 if (!*ok)
4806 return 0;
4807 if (!cp) {
4808 *ok = 1;
4809 return v;
4811 while (TOR_ISSPACE(*cp))
4812 ++cp;
4813 for ( ;u->unit;++u) {
4814 if (!strcasecmp(u->unit, cp)) {
4815 v *= u->multiplier;
4816 *ok = 1;
4817 return v;
4820 log_warn(LD_CONFIG, "Unknown unit '%s'.", cp);
4821 *ok = 0;
4822 return 0;
4825 /** Parse a string in the format "number unit", where unit is a unit of
4826 * information (byte, KB, M, etc). On success, set *<b>ok</b> to true
4827 * and return the number of bytes specified. Otherwise, set
4828 * *<b>ok</b> to false and return 0. */
4829 static uint64_t
4830 config_parse_memunit(const char *s, int *ok)
4832 return config_parse_units(s, memory_units, ok);
4835 /** Parse a string in the format "number unit", where unit is a unit of time.
4836 * On success, set *<b>ok</b> to true and return the number of seconds in
4837 * the provided interval. Otherwise, set *<b>ok</b> to 0 and return -1.
4839 static int
4840 config_parse_interval(const char *s, int *ok)
4842 uint64_t r;
4843 r = config_parse_units(s, time_units, ok);
4844 if (!ok)
4845 return -1;
4846 if (r > INT_MAX) {
4847 log_warn(LD_CONFIG, "Interval '%s' is too long", s);
4848 *ok = 0;
4849 return -1;
4851 return (int)r;
4855 * Initialize the libevent library.
4857 static void
4858 init_libevent(void)
4860 const char *badness=NULL;
4862 configure_libevent_logging();
4863 /* If the kernel complains that some method (say, epoll) doesn't
4864 * exist, we don't care about it, since libevent will cope.
4866 suppress_libevent_log_msg("Function not implemented");
4868 tor_check_libevent_header_compatibility();
4870 tor_libevent_initialize();
4872 suppress_libevent_log_msg(NULL);
4874 tor_check_libevent_version(tor_libevent_get_method(),
4875 get_options()->ORPort != 0,
4876 &badness);
4877 if (badness) {
4878 const char *v = tor_libevent_get_version_str();
4879 const char *m = tor_libevent_get_method();
4880 control_event_general_status(LOG_WARN,
4881 "BAD_LIBEVENT VERSION=%s METHOD=%s BADNESS=%s RECOVERED=NO",
4882 v, m, badness);
4886 /** Return the persistent state struct for this Tor. */
4887 or_state_t *
4888 get_or_state(void)
4890 tor_assert(global_state);
4891 return global_state;
4894 /** Return a newly allocated string holding a filename relative to the data
4895 * directory. If <b>sub1</b> is present, it is the first path component after
4896 * the data directory. If <b>sub2</b> is also present, it is the second path
4897 * component after the data directory. If <b>suffix</b> is present, it
4898 * is appended to the filename.
4900 * Examples:
4901 * get_datadir_fname2_suffix("a", NULL, NULL) -> $DATADIR/a
4902 * get_datadir_fname2_suffix("a", NULL, ".tmp") -> $DATADIR/a.tmp
4903 * get_datadir_fname2_suffix("a", "b", ".tmp") -> $DATADIR/a/b/.tmp
4904 * get_datadir_fname2_suffix("a", "b", NULL) -> $DATADIR/a/b
4906 * Note: Consider using the get_datadir_fname* macros in or.h.
4908 char *
4909 options_get_datadir_fname2_suffix(or_options_t *options,
4910 const char *sub1, const char *sub2,
4911 const char *suffix)
4913 char *fname = NULL;
4914 size_t len;
4915 tor_assert(options);
4916 tor_assert(options->DataDirectory);
4917 tor_assert(sub1 || !sub2); /* If sub2 is present, sub1 must be present. */
4918 len = strlen(options->DataDirectory);
4919 if (sub1) {
4920 len += strlen(sub1)+1;
4921 if (sub2)
4922 len += strlen(sub2)+1;
4924 if (suffix)
4925 len += strlen(suffix);
4926 len++;
4927 fname = tor_malloc(len);
4928 if (sub1) {
4929 if (sub2) {
4930 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s",
4931 options->DataDirectory, sub1, sub2);
4932 } else {
4933 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s",
4934 options->DataDirectory, sub1);
4936 } else {
4937 strlcpy(fname, options->DataDirectory, len);
4939 if (suffix)
4940 strlcat(fname, suffix, len);
4941 return fname;
4944 /** Return 0 if every setting in <b>state</b> is reasonable, and a
4945 * permissible transition from <b>old_state</b>. Else warn and return -1.
4946 * Should have no side effects, except for normalizing the contents of
4947 * <b>state</b>.
4949 /* XXX from_setconf is here because of bug 238 */
4950 static int
4951 or_state_validate(or_state_t *old_state, or_state_t *state,
4952 int from_setconf, char **msg)
4954 /* We don't use these; only options do. Still, we need to match that
4955 * signature. */
4956 (void) from_setconf;
4957 (void) old_state;
4959 if (entry_guards_parse_state(state, 0, msg)<0)
4960 return -1;
4962 return 0;
4965 /** Replace the current persistent state with <b>new_state</b> */
4966 static void
4967 or_state_set(or_state_t *new_state)
4969 char *err = NULL;
4970 tor_assert(new_state);
4971 if (global_state)
4972 config_free(&state_format, global_state);
4973 global_state = new_state;
4974 if (entry_guards_parse_state(global_state, 1, &err)<0) {
4975 log_warn(LD_GENERAL,"%s",err);
4976 tor_free(err);
4978 if (rep_hist_load_state(global_state, &err)<0) {
4979 log_warn(LD_GENERAL,"Unparseable bandwidth history state: %s",err);
4980 tor_free(err);
4984 /** Reload the persistent state from disk, generating a new state as needed.
4985 * Return 0 on success, less than 0 on failure.
4987 static int
4988 or_state_load(void)
4990 or_state_t *new_state = NULL;
4991 char *contents = NULL, *fname;
4992 char *errmsg = NULL;
4993 int r = -1, badstate = 0;
4995 fname = get_datadir_fname("state");
4996 switch (file_status(fname)) {
4997 case FN_FILE:
4998 if (!(contents = read_file_to_str(fname, 0, NULL))) {
4999 log_warn(LD_FS, "Unable to read state file \"%s\"", fname);
5000 goto done;
5002 break;
5003 case FN_NOENT:
5004 break;
5005 case FN_ERROR:
5006 case FN_DIR:
5007 default:
5008 log_warn(LD_GENERAL,"State file \"%s\" is not a file? Failing.", fname);
5009 goto done;
5011 new_state = tor_malloc_zero(sizeof(or_state_t));
5012 new_state->_magic = OR_STATE_MAGIC;
5013 config_init(&state_format, new_state);
5014 if (contents) {
5015 config_line_t *lines=NULL;
5016 int assign_retval;
5017 if (config_get_lines(contents, &lines)<0)
5018 goto done;
5019 assign_retval = config_assign(&state_format, new_state,
5020 lines, 0, 0, &errmsg);
5021 config_free_lines(lines);
5022 if (assign_retval<0)
5023 badstate = 1;
5024 if (errmsg) {
5025 log_warn(LD_GENERAL, "%s", errmsg);
5026 tor_free(errmsg);
5030 if (!badstate && or_state_validate(NULL, new_state, 1, &errmsg) < 0)
5031 badstate = 1;
5033 if (errmsg) {
5034 log_warn(LD_GENERAL, "%s", errmsg);
5035 tor_free(errmsg);
5038 if (badstate && !contents) {
5039 log_warn(LD_BUG, "Uh oh. We couldn't even validate our own default state."
5040 " This is a bug in Tor.");
5041 goto done;
5042 } else if (badstate && contents) {
5043 int i;
5044 file_status_t status;
5045 size_t len = strlen(fname)+16;
5046 char *fname2 = tor_malloc(len);
5047 for (i = 0; i < 100; ++i) {
5048 tor_snprintf(fname2, len, "%s.%d", fname, i);
5049 status = file_status(fname2);
5050 if (status == FN_NOENT)
5051 break;
5053 if (i == 100) {
5054 log_warn(LD_BUG, "Unable to parse state in \"%s\"; too many saved bad "
5055 "state files to move aside. Discarding the old state file.",
5056 fname);
5057 unlink(fname);
5058 } else {
5059 log_warn(LD_BUG, "Unable to parse state in \"%s\". Moving it aside "
5060 "to \"%s\". This could be a bug in Tor; please tell "
5061 "the developers.", fname, fname2);
5062 if (rename(fname, fname2) < 0) {
5063 log_warn(LD_BUG, "Weirdly, I couldn't even move the state aside. The "
5064 "OS gave an error of %s", strerror(errno));
5067 tor_free(fname2);
5068 tor_free(contents);
5069 config_free(&state_format, new_state);
5071 new_state = tor_malloc_zero(sizeof(or_state_t));
5072 new_state->_magic = OR_STATE_MAGIC;
5073 config_init(&state_format, new_state);
5074 } else if (contents) {
5075 log_info(LD_GENERAL, "Loaded state from \"%s\"", fname);
5076 } else {
5077 log_info(LD_GENERAL, "Initialized state");
5079 or_state_set(new_state);
5080 new_state = NULL;
5081 if (!contents) {
5082 global_state->next_write = 0;
5083 or_state_save(time(NULL));
5085 r = 0;
5087 done:
5088 tor_free(fname);
5089 tor_free(contents);
5090 if (new_state)
5091 config_free(&state_format, new_state);
5093 return r;
5096 /** Write the persistent state to disk. Return 0 for success, <0 on failure. */
5098 or_state_save(time_t now)
5100 char *state, *contents;
5101 char tbuf[ISO_TIME_LEN+1];
5102 size_t len;
5103 char *fname;
5105 tor_assert(global_state);
5107 if (global_state->next_write > now)
5108 return 0;
5110 /* Call everything else that might dirty the state even more, in order
5111 * to avoid redundant writes. */
5112 entry_guards_update_state(global_state);
5113 rep_hist_update_state(global_state);
5114 if (accounting_is_enabled(get_options()))
5115 accounting_run_housekeeping(now);
5117 global_state->LastWritten = time(NULL);
5118 tor_free(global_state->TorVersion);
5119 len = strlen(get_version())+8;
5120 global_state->TorVersion = tor_malloc(len);
5121 tor_snprintf(global_state->TorVersion, len, "Tor %s", get_version());
5123 state = config_dump(&state_format, global_state, 1, 0);
5124 len = strlen(state)+256;
5125 contents = tor_malloc(len);
5126 format_local_iso_time(tbuf, time(NULL));
5127 tor_snprintf(contents, len,
5128 "# Tor state file last generated on %s local time\n"
5129 "# Other times below are in GMT\n"
5130 "# You *do not* need to edit this file.\n\n%s",
5131 tbuf, state);
5132 tor_free(state);
5133 fname = get_datadir_fname("state");
5134 if (write_str_to_file(fname, contents, 0)<0) {
5135 log_warn(LD_FS, "Unable to write state to file \"%s\"", fname);
5136 tor_free(fname);
5137 tor_free(contents);
5138 return -1;
5140 log_info(LD_GENERAL, "Saved state to \"%s\"", fname);
5141 tor_free(fname);
5142 tor_free(contents);
5144 global_state->next_write = TIME_MAX;
5145 return 0;
5148 /** Given a file name check to see whether the file exists but has not been
5149 * modified for a very long time. If so, remove it. */
5150 void
5151 remove_file_if_very_old(const char *fname, time_t now)
5153 #define VERY_OLD_FILE_AGE (28*24*60*60)
5154 struct stat st;
5156 if (stat(fname, &st)==0 && st.st_mtime < now-VERY_OLD_FILE_AGE) {
5157 char buf[ISO_TIME_LEN+1];
5158 format_local_iso_time(buf, st.st_mtime);
5159 log_notice(LD_GENERAL, "Obsolete file %s hasn't been modified since %s. "
5160 "Removing it.", fname, buf);
5161 unlink(fname);
5165 /** Helper to implement GETINFO functions about configuration variables (not
5166 * their values). Given a "config/names" question, set *<b>answer</b> to a
5167 * new string describing the supported configuration variables and their
5168 * types. */
5170 getinfo_helper_config(control_connection_t *conn,
5171 const char *question, char **answer)
5173 (void) conn;
5174 if (!strcmp(question, "config/names")) {
5175 smartlist_t *sl = smartlist_create();
5176 int i;
5177 for (i = 0; _option_vars[i].name; ++i) {
5178 config_var_t *var = &_option_vars[i];
5179 const char *type, *desc;
5180 char *line;
5181 size_t len;
5182 desc = config_find_description(&options_format, var->name);
5183 switch (var->type) {
5184 case CONFIG_TYPE_STRING: type = "String"; break;
5185 case CONFIG_TYPE_FILENAME: type = "Filename"; break;
5186 case CONFIG_TYPE_UINT: type = "Integer"; break;
5187 case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
5188 case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
5189 case CONFIG_TYPE_DOUBLE: type = "Float"; break;
5190 case CONFIG_TYPE_BOOL: type = "Boolean"; break;
5191 case CONFIG_TYPE_ISOTIME: type = "Time"; break;
5192 case CONFIG_TYPE_ROUTERSET: type = "RouterList"; break;
5193 case CONFIG_TYPE_CSV: type = "CommaList"; break;
5194 case CONFIG_TYPE_LINELIST: type = "LineList"; break;
5195 case CONFIG_TYPE_LINELIST_S: type = "Dependant"; break;
5196 case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
5197 default:
5198 case CONFIG_TYPE_OBSOLETE:
5199 type = NULL; break;
5201 if (!type)
5202 continue;
5203 len = strlen(var->name)+strlen(type)+16;
5204 if (desc)
5205 len += strlen(desc);
5206 line = tor_malloc(len);
5207 if (desc)
5208 tor_snprintf(line, len, "%s %s %s\n",var->name,type,desc);
5209 else
5210 tor_snprintf(line, len, "%s %s\n",var->name,type);
5211 smartlist_add(sl, line);
5213 *answer = smartlist_join_strings(sl, "", 0, NULL);
5214 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
5215 smartlist_free(sl);
5217 return 0;