Remove ./configure option for entry and dir request statistics.
[tor/rransom.git] / src / or / config.c
blob0fc3af47e1ea6af9631d986de9c39f84a6a791fa
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(AllowDotExit, BOOL, "0"),
138 V(AllowInvalidNodes, CSV, "middle,rendezvous"),
139 V(AllowNonRFC953Hostnames, BOOL, "0"),
140 V(AllowSingleHopCircuits, BOOL, "0"),
141 V(AllowSingleHopExits, BOOL, "0"),
142 V(AlternateBridgeAuthority, LINELIST, NULL),
143 V(AlternateDirAuthority, LINELIST, NULL),
144 V(AlternateHSAuthority, LINELIST, NULL),
145 V(AssumeReachable, BOOL, "0"),
146 V(AuthDirBadDir, LINELIST, NULL),
147 V(AuthDirBadExit, LINELIST, NULL),
148 V(AuthDirInvalid, LINELIST, NULL),
149 V(AuthDirReject, LINELIST, NULL),
150 V(AuthDirRejectUnlisted, BOOL, "0"),
151 V(AuthDirListBadDirs, BOOL, "0"),
152 V(AuthDirListBadExits, BOOL, "0"),
153 V(AuthDirMaxServersPerAddr, UINT, "2"),
154 V(AuthDirMaxServersPerAuthAddr,UINT, "5"),
155 VAR("AuthoritativeDirectory", BOOL, AuthoritativeDir, "0"),
156 V(AutomapHostsOnResolve, BOOL, "0"),
157 V(AutomapHostsSuffixes, CSV, ".onion,.exit"),
158 V(AvoidDiskWrites, BOOL, "0"),
159 V(BandwidthBurst, MEMUNIT, "10 MB"),
160 V(BandwidthRate, MEMUNIT, "5 MB"),
161 V(BridgeAuthoritativeDir, BOOL, "0"),
162 VAR("Bridge", LINELIST, Bridges, NULL),
163 V(BridgePassword, STRING, NULL),
164 V(BridgeRecordUsageByCountry, BOOL, "1"),
165 V(BridgeRelay, BOOL, "0"),
166 V(CellStatistics, BOOL, "0"),
167 V(CircuitBuildTimeout, INTERVAL, "1 minute"),
168 V(CircuitIdleTimeout, INTERVAL, "1 hour"),
169 V(ClientDNSRejectInternalAddresses, BOOL,"1"),
170 V(ClientOnly, BOOL, "0"),
171 V(ConnLimit, UINT, "1000"),
172 V(ConstrainedSockets, BOOL, "0"),
173 V(ConstrainedSockSize, MEMUNIT, "8192"),
174 V(ContactInfo, STRING, NULL),
175 V(ControlListenAddress, LINELIST, NULL),
176 V(ControlPort, UINT, "0"),
177 V(ControlSocket, LINELIST, NULL),
178 V(CookieAuthentication, BOOL, "0"),
179 V(CookieAuthFileGroupReadable, BOOL, "0"),
180 V(CookieAuthFile, STRING, NULL),
181 V(DataDirectory, FILENAME, NULL),
182 OBSOLETE("DebugLogFile"),
183 V(DirAllowPrivateAddresses, BOOL, NULL),
184 V(TestingAuthDirTimeToLearnReachability, INTERVAL, "30 minutes"),
185 V(DirListenAddress, LINELIST, NULL),
186 OBSOLETE("DirFetchPeriod"),
187 V(DirPolicy, LINELIST, NULL),
188 V(DirPort, UINT, "0"),
189 V(DirPortFrontPage, FILENAME, NULL),
190 OBSOLETE("DirPostPeriod"),
191 OBSOLETE("DirRecordUsageByCountry"),
192 OBSOLETE("DirRecordUsageGranularity"),
193 OBSOLETE("DirRecordUsageRetainIPs"),
194 OBSOLETE("DirRecordUsageSaveInterval"),
195 V(DirReqStatistics, BOOL, "0"),
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 "urras orport=80 no-v2 v3ident=80550987E1D626E3EBA5E5E75A458DE0626D088C "
921 "208.83.223.34:443 0AD3 FA88 4D18 F89E EA2D 89C0 1937 9E0E 7FD9 4417",
922 NULL
924 for (i=0; dirservers[i]; i++) {
925 if (parse_dir_server_line(dirservers[i], type, 0)<0) {
926 log_err(LD_BUG, "Couldn't parse internal dirserver line %s",
927 dirservers[i]);
932 /** Look at all the config options for using alternate directory
933 * authorities, and make sure none of them are broken. Also, warn the
934 * user if we changed any dangerous ones.
936 static int
937 validate_dir_authorities(or_options_t *options, or_options_t *old_options)
939 config_line_t *cl;
941 if (options->DirServers &&
942 (options->AlternateDirAuthority || options->AlternateBridgeAuthority ||
943 options->AlternateHSAuthority)) {
944 log_warn(LD_CONFIG,
945 "You cannot set both DirServers and Alternate*Authority.");
946 return -1;
949 /* do we want to complain to the user about being partitionable? */
950 if ((options->DirServers &&
951 (!old_options ||
952 !config_lines_eq(options->DirServers, old_options->DirServers))) ||
953 (options->AlternateDirAuthority &&
954 (!old_options ||
955 !config_lines_eq(options->AlternateDirAuthority,
956 old_options->AlternateDirAuthority)))) {
957 log_warn(LD_CONFIG,
958 "You have used DirServer or AlternateDirAuthority to "
959 "specify alternate directory authorities in "
960 "your configuration. This is potentially dangerous: it can "
961 "make you look different from all other Tor users, and hurt "
962 "your anonymity. Even if you've specified the same "
963 "authorities as Tor uses by default, the defaults could "
964 "change in the future. Be sure you know what you're doing.");
967 /* Now go through the four ways you can configure an alternate
968 * set of directory authorities, and make sure none are broken. */
969 for (cl = options->DirServers; cl; cl = cl->next)
970 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
971 return -1;
972 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
973 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
974 return -1;
975 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
976 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
977 return -1;
978 for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
979 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
980 return -1;
981 return 0;
984 /** Look at all the config options and assign new dir authorities
985 * as appropriate.
987 static int
988 consider_adding_dir_authorities(or_options_t *options,
989 or_options_t *old_options)
991 config_line_t *cl;
992 int need_to_update =
993 !smartlist_len(router_get_trusted_dir_servers()) || !old_options ||
994 !config_lines_eq(options->DirServers, old_options->DirServers) ||
995 !config_lines_eq(options->AlternateBridgeAuthority,
996 old_options->AlternateBridgeAuthority) ||
997 !config_lines_eq(options->AlternateDirAuthority,
998 old_options->AlternateDirAuthority) ||
999 !config_lines_eq(options->AlternateHSAuthority,
1000 old_options->AlternateHSAuthority);
1002 if (!need_to_update)
1003 return 0; /* all done */
1005 /* Start from a clean slate. */
1006 clear_trusted_dir_servers();
1008 if (!options->DirServers) {
1009 /* then we may want some of the defaults */
1010 authority_type_t type = NO_AUTHORITY;
1011 if (!options->AlternateBridgeAuthority)
1012 type |= BRIDGE_AUTHORITY;
1013 if (!options->AlternateDirAuthority)
1014 type |= V1_AUTHORITY | V2_AUTHORITY | V3_AUTHORITY;
1015 if (!options->AlternateHSAuthority)
1016 type |= HIDSERV_AUTHORITY;
1017 add_default_trusted_dir_authorities(type);
1020 for (cl = options->DirServers; cl; cl = cl->next)
1021 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1022 return -1;
1023 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
1024 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1025 return -1;
1026 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
1027 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1028 return -1;
1029 for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
1030 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
1031 return -1;
1032 return 0;
1035 /** Fetch the active option list, and take actions based on it. All of the
1036 * things we do should survive being done repeatedly. If present,
1037 * <b>old_options</b> contains the previous value of the options.
1039 * Return 0 if all goes well, return -1 if things went badly.
1041 static int
1042 options_act_reversible(or_options_t *old_options, char **msg)
1044 smartlist_t *new_listeners = smartlist_create();
1045 smartlist_t *replaced_listeners = smartlist_create();
1046 static int libevent_initialized = 0;
1047 or_options_t *options = get_options();
1048 int running_tor = options->command == CMD_RUN_TOR;
1049 int set_conn_limit = 0;
1050 int r = -1;
1051 int logs_marked = 0;
1053 /* Daemonize _first_, since we only want to open most of this stuff in
1054 * the subprocess. Libevent bases can't be reliably inherited across
1055 * processes. */
1056 if (running_tor && options->RunAsDaemon) {
1057 /* No need to roll back, since you can't change the value. */
1058 start_daemon();
1061 #ifndef HAVE_SYS_UN_H
1062 if (options->ControlSocket) {
1063 *msg = tor_strdup("Unix domain sockets (ControlSocket) not supported"
1064 " on this OS/with this build.");
1065 goto rollback;
1067 #endif
1069 if (running_tor) {
1070 /* We need to set the connection limit before we can open the listeners. */
1071 if (set_max_file_descriptors((unsigned)options->ConnLimit,
1072 &options->_ConnLimit) < 0) {
1073 *msg = tor_strdup("Problem with ConnLimit value. See logs for details.");
1074 goto rollback;
1076 set_conn_limit = 1;
1078 /* Set up libevent. (We need to do this before we can register the
1079 * listeners as listeners.) */
1080 if (running_tor && !libevent_initialized) {
1081 init_libevent();
1082 libevent_initialized = 1;
1085 /* Launch the listeners. (We do this before we setuid, so we can bind to
1086 * ports under 1024.) */
1087 if (retry_all_listeners(replaced_listeners, new_listeners) < 0) {
1088 *msg = tor_strdup("Failed to bind one of the listener ports.");
1089 goto rollback;
1093 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
1094 /* Open /dev/pf before dropping privileges. */
1095 if (options->TransPort) {
1096 if (get_pf_socket() < 0) {
1097 *msg = tor_strdup("Unable to open /dev/pf for transparent proxy.");
1098 goto rollback;
1101 #endif
1103 /* Setuid/setgid as appropriate */
1104 if (options->User) {
1105 if (switch_id(options->User) != 0) {
1106 /* No need to roll back, since you can't change the value. */
1107 *msg = tor_strdup("Problem with User value. See logs for details.");
1108 goto done;
1112 /* Ensure data directory is private; create if possible. */
1113 if (check_private_dir(options->DataDirectory,
1114 running_tor ? CPD_CREATE : CPD_CHECK)<0) {
1115 char buf[1024];
1116 int tmp = tor_snprintf(buf, sizeof(buf),
1117 "Couldn't access/create private data directory \"%s\"",
1118 options->DataDirectory);
1119 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1120 goto done;
1121 /* No need to roll back, since you can't change the value. */
1124 if (directory_caches_v2_dir_info(options)) {
1125 size_t len = strlen(options->DataDirectory)+32;
1126 char *fn = tor_malloc(len);
1127 tor_snprintf(fn, len, "%s"PATH_SEPARATOR"cached-status",
1128 options->DataDirectory);
1129 if (check_private_dir(fn, running_tor ? CPD_CREATE : CPD_CHECK) < 0) {
1130 char buf[1024];
1131 int tmp = tor_snprintf(buf, sizeof(buf),
1132 "Couldn't access/create private data directory \"%s\"", fn);
1133 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1134 tor_free(fn);
1135 goto done;
1137 tor_free(fn);
1140 /* Bail out at this point if we're not going to be a client or server:
1141 * we don't run Tor itself. */
1142 if (!running_tor)
1143 goto commit;
1145 mark_logs_temp(); /* Close current logs once new logs are open. */
1146 logs_marked = 1;
1147 if (options_init_logs(options, 0)<0) { /* Configure the log(s) */
1148 *msg = tor_strdup("Failed to init Log options. See logs for details.");
1149 goto rollback;
1152 commit:
1153 r = 0;
1154 if (logs_marked) {
1155 log_severity_list_t *severity =
1156 tor_malloc_zero(sizeof(log_severity_list_t));
1157 close_temp_logs();
1158 add_callback_log(severity, control_event_logmsg);
1159 control_adjust_event_log_severity();
1160 tor_free(severity);
1162 SMARTLIST_FOREACH(replaced_listeners, connection_t *, conn,
1164 log_notice(LD_NET, "Closing old %s on %s:%d",
1165 conn_type_to_string(conn->type), conn->address, conn->port);
1166 connection_close_immediate(conn);
1167 connection_mark_for_close(conn);
1169 goto done;
1171 rollback:
1172 r = -1;
1173 tor_assert(*msg);
1175 if (logs_marked) {
1176 rollback_log_changes();
1177 control_adjust_event_log_severity();
1180 if (set_conn_limit && old_options)
1181 set_max_file_descriptors((unsigned)old_options->ConnLimit,
1182 &options->_ConnLimit);
1184 SMARTLIST_FOREACH(new_listeners, connection_t *, conn,
1186 log_notice(LD_NET, "Closing partially-constructed listener %s on %s:%d",
1187 conn_type_to_string(conn->type), conn->address, conn->port);
1188 connection_close_immediate(conn);
1189 connection_mark_for_close(conn);
1192 done:
1193 smartlist_free(new_listeners);
1194 smartlist_free(replaced_listeners);
1195 return r;
1198 /** If we need to have a GEOIP ip-to-country map to run with our configured
1199 * options, return 1 and set *<b>reason_out</b> to a description of why. */
1201 options_need_geoip_info(or_options_t *options, const char **reason_out)
1203 int bridge_usage =
1204 options->BridgeRelay && options->BridgeRecordUsageByCountry;
1205 int routerset_usage =
1206 routerset_needs_geoip(options->EntryNodes) ||
1207 routerset_needs_geoip(options->ExitNodes) ||
1208 routerset_needs_geoip(options->ExcludeExitNodes) ||
1209 routerset_needs_geoip(options->ExcludeNodes);
1211 if (routerset_usage && reason_out) {
1212 *reason_out = "We've been configured to use (or avoid) nodes in certain "
1213 "countries, and we need GEOIP information to figure out which ones they "
1214 "are.";
1215 } else if (bridge_usage && reason_out) {
1216 *reason_out = "We've been configured to see which countries can access "
1217 "us as a bridge, and we need GEOIP information to tell which countries "
1218 "clients are in.";
1220 return bridge_usage || routerset_usage;
1223 /** Return the bandwidthrate that we are going to report to the authorities
1224 * based on the config options. */
1225 uint32_t
1226 get_effective_bwrate(or_options_t *options)
1228 uint64_t bw = options->BandwidthRate;
1229 if (bw > options->MaxAdvertisedBandwidth)
1230 bw = options->MaxAdvertisedBandwidth;
1231 if (options->RelayBandwidthRate > 0 && bw > options->RelayBandwidthRate)
1232 bw = options->RelayBandwidthRate;
1233 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1234 return (uint32_t)bw;
1237 /** Return the bandwidthburst that we are going to report to the authorities
1238 * based on the config options. */
1239 uint32_t
1240 get_effective_bwburst(or_options_t *options)
1242 uint64_t bw = options->BandwidthBurst;
1243 if (options->RelayBandwidthBurst > 0 && bw > options->RelayBandwidthBurst)
1244 bw = options->RelayBandwidthBurst;
1245 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1246 return (uint32_t)bw;
1249 /** Fetch the active option list, and take actions based on it. All of the
1250 * things we do should survive being done repeatedly. If present,
1251 * <b>old_options</b> contains the previous value of the options.
1253 * Return 0 if all goes well, return -1 if it's time to die.
1255 * Note: We haven't moved all the "act on new configuration" logic
1256 * here yet. Some is still in do_hup() and other places.
1258 static int
1259 options_act(or_options_t *old_options)
1261 config_line_t *cl;
1262 or_options_t *options = get_options();
1263 int running_tor = options->command == CMD_RUN_TOR;
1264 char *msg;
1266 if (running_tor && !have_lockfile()) {
1267 if (try_locking(options, 1) < 0)
1268 return -1;
1271 if (consider_adding_dir_authorities(options, old_options) < 0)
1272 return -1;
1274 if (options->Bridges) {
1275 clear_bridge_list();
1276 for (cl = options->Bridges; cl; cl = cl->next) {
1277 if (parse_bridge_line(cl->value, 0)<0) {
1278 log_warn(LD_BUG,
1279 "Previously validated Bridge line could not be added!");
1280 return -1;
1285 if (running_tor && rend_config_services(options, 0)<0) {
1286 log_warn(LD_BUG,
1287 "Previously validated hidden services line could not be added!");
1288 return -1;
1291 if (running_tor && rend_parse_service_authorization(options, 0) < 0) {
1292 log_warn(LD_BUG, "Previously validated client authorization for "
1293 "hidden services could not be added!");
1294 return -1;
1297 /* Load state */
1298 if (! global_state && running_tor) {
1299 if (or_state_load())
1300 return -1;
1301 rep_hist_load_mtbf_data(time(NULL));
1304 /* Bail out at this point if we're not going to be a client or server:
1305 * we want to not fork, and to log stuff to stderr. */
1306 if (!running_tor)
1307 return 0;
1309 /* Finish backgrounding the process */
1310 if (options->RunAsDaemon) {
1311 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
1312 finish_daemon(options->DataDirectory);
1315 /* Write our PID to the PID file. If we do not have write permissions we
1316 * will log a warning */
1317 if (options->PidFile)
1318 write_pidfile(options->PidFile);
1320 /* Register addressmap directives */
1321 config_register_addressmaps(options);
1322 parse_virtual_addr_network(options->VirtualAddrNetwork, 0, &msg);
1324 /* Update address policies. */
1325 if (policies_parse_from_options(options) < 0) {
1326 /* This should be impossible, but let's be sure. */
1327 log_warn(LD_BUG,"Error parsing already-validated policy options.");
1328 return -1;
1331 if (init_cookie_authentication(options->CookieAuthentication) < 0) {
1332 log_warn(LD_CONFIG,"Error creating cookie authentication file.");
1333 return -1;
1336 /* reload keys as needed for rendezvous services. */
1337 if (rend_service_load_keys()<0) {
1338 log_warn(LD_GENERAL,"Error loading rendezvous service keys");
1339 return -1;
1342 /* Set up accounting */
1343 if (accounting_parse_options(options, 0)<0) {
1344 log_warn(LD_CONFIG,"Error in accounting options");
1345 return -1;
1347 if (accounting_is_enabled(options))
1348 configure_accounting(time(NULL));
1350 /* Check for transitions that need action. */
1351 if (old_options) {
1352 if (options->UseEntryGuards && !old_options->UseEntryGuards) {
1353 log_info(LD_CIRC,
1354 "Switching to entry guards; abandoning previous circuits");
1355 circuit_mark_all_unused_circs();
1356 circuit_expire_all_dirty_circs();
1359 if (! bool_eq(options->BridgeRelay, old_options->BridgeRelay)) {
1360 log_info(LD_GENERAL, "Bridge status changed. Forgetting GeoIP stats.");
1361 geoip_remove_old_clients(time(NULL)+(2*60*60));
1364 if (options_transition_affects_workers(old_options, options)) {
1365 log_info(LD_GENERAL,
1366 "Worker-related options changed. Rotating workers.");
1367 if (server_mode(options) && !server_mode(old_options)) {
1368 if (init_keys() < 0) {
1369 log_warn(LD_BUG,"Error initializing keys; exiting");
1370 return -1;
1372 ip_address_changed(0);
1373 if (has_completed_circuit || !any_predicted_circuits(time(NULL)))
1374 inform_testing_reachability();
1376 cpuworkers_rotate();
1377 if (dns_reset())
1378 return -1;
1379 } else {
1380 if (dns_reset())
1381 return -1;
1384 if (options->V3AuthoritativeDir && !old_options->V3AuthoritativeDir)
1385 init_keys();
1388 /* Maybe load geoip file */
1389 if (options->GeoIPFile &&
1390 ((!old_options || !opt_streq(old_options->GeoIPFile, options->GeoIPFile))
1391 || !geoip_is_loaded())) {
1392 /* XXXX Don't use this "<default>" junk; make our filename options
1393 * understand prefixes somehow. -NM */
1394 /* XXXX021 Reload GeoIPFile on SIGHUP. -NM */
1395 char *actual_fname = tor_strdup(options->GeoIPFile);
1396 #ifdef WIN32
1397 if (!strcmp(actual_fname, "<default>")) {
1398 const char *conf_root = get_windows_conf_root();
1399 size_t len = strlen(conf_root)+16;
1400 tor_free(actual_fname);
1401 actual_fname = tor_malloc(len+1);
1402 tor_snprintf(actual_fname, len, "%s\\geoip", conf_root);
1404 #endif
1405 geoip_load_file(actual_fname, options);
1406 tor_free(actual_fname);
1409 if (options->DirReqStatistics) {
1410 /* Check if GeoIP database could be loaded. */
1411 if (!geoip_is_loaded()) {
1412 log_warn(LD_CONFIG, "Configured to measure directory request "
1413 "statistics, but no GeoIP database found!");
1414 return -1;
1416 log_notice(LD_CONFIG, "Configured to count directory requests by "
1417 "country and write aggregate statistics to disk. Check the "
1418 "dirreq-stats file in your data directory that will first "
1419 "be written in 24 hours from now.");
1422 if (options->ExitPortStatistics)
1423 log_notice(LD_CONFIG, "Configured to measure exit port statistics. "
1424 "Look for the exit-stats file that will first be written to "
1425 "the data directory in 24 hours from now.");
1427 #ifdef ENABLE_BUFFER_STATS
1428 if (options->CellStatistics)
1429 log_notice(LD_CONFIG, "Configured to measure cell statistics. Look "
1430 "for the buffer-stats file that will first be written to "
1431 "the data directory in 24 hours from now.");
1432 #else
1433 if (options->CellStatistics)
1434 log_warn(LD_CONFIG, "CellStatistics enabled, but Tor was built "
1435 "without cell statistics support.");
1436 #endif
1438 if (options->EntryStatistics) {
1439 if (should_record_bridge_info(options)) {
1440 /* Don't allow measuring statistics on entry guards when configured
1441 * as bridge. */
1442 log_warn(LD_CONFIG, "Bridges cannot be configured to measure "
1443 "additional GeoIP statistics as entry guards.");
1444 return -1;
1445 } else if (!geoip_is_loaded()) {
1446 /* Check if GeoIP database could be loaded. */
1447 log_warn(LD_CONFIG, "Configured to measure entry node statistics, "
1448 "but no GeoIP database found!");
1449 return -1;
1450 } else
1451 log_notice(LD_CONFIG, "Configured to measure entry node "
1452 "statistics. Look for the entry-stats file that will "
1453 "first be written to the data directory in 24 hours "
1454 "from now.");
1457 /* Check if we need to parse and add the EntryNodes config option. */
1458 if (options->EntryNodes &&
1459 (!old_options ||
1460 (!routerset_equal(old_options->EntryNodes,options->EntryNodes))))
1461 entry_nodes_should_be_added();
1463 /* Since our options changed, we might need to regenerate and upload our
1464 * server descriptor.
1466 if (!old_options ||
1467 options_transition_affects_descriptor(old_options, options))
1468 mark_my_descriptor_dirty();
1470 /* We may need to reschedule some directory stuff if our status changed. */
1471 if (old_options) {
1472 if (authdir_mode_v3(options) && !authdir_mode_v3(old_options))
1473 dirvote_recalculate_timing(options, time(NULL));
1474 if (!bool_eq(directory_fetches_dir_info_early(options),
1475 directory_fetches_dir_info_early(old_options)) ||
1476 !bool_eq(directory_fetches_dir_info_later(options),
1477 directory_fetches_dir_info_later(old_options))) {
1478 /* Make sure update_router_have_min_dir_info gets called. */
1479 router_dir_info_changed();
1480 /* We might need to download a new consensus status later or sooner than
1481 * we had expected. */
1482 update_consensus_networkstatus_fetch_time(time(NULL));
1486 /* Load the webpage we're going to serve every time someone asks for '/' on
1487 our DirPort. */
1488 tor_free(global_dirfrontpagecontents);
1489 if (options->DirPortFrontPage) {
1490 global_dirfrontpagecontents =
1491 read_file_to_str(options->DirPortFrontPage, 0, NULL);
1492 if (!global_dirfrontpagecontents) {
1493 log_warn(LD_CONFIG,
1494 "DirPortFrontPage file '%s' not found. Continuing anyway.",
1495 options->DirPortFrontPage);
1499 return 0;
1503 * Functions to parse config options
1506 /** If <b>option</b> is an official abbreviation for a longer option,
1507 * return the longer option. Otherwise return <b>option</b>.
1508 * If <b>command_line</b> is set, apply all abbreviations. Otherwise, only
1509 * apply abbreviations that work for the config file and the command line.
1510 * If <b>warn_obsolete</b> is set, warn about deprecated names. */
1511 static const char *
1512 expand_abbrev(config_format_t *fmt, const char *option, int command_line,
1513 int warn_obsolete)
1515 int i;
1516 if (! fmt->abbrevs)
1517 return option;
1518 for (i=0; fmt->abbrevs[i].abbreviated; ++i) {
1519 /* Abbreviations are case insensitive. */
1520 if (!strcasecmp(option,fmt->abbrevs[i].abbreviated) &&
1521 (command_line || !fmt->abbrevs[i].commandline_only)) {
1522 if (warn_obsolete && fmt->abbrevs[i].warn) {
1523 log_warn(LD_CONFIG,
1524 "The configuration option '%s' is deprecated; "
1525 "use '%s' instead.",
1526 fmt->abbrevs[i].abbreviated,
1527 fmt->abbrevs[i].full);
1529 return fmt->abbrevs[i].full;
1532 return option;
1535 /** Helper: Read a list of configuration options from the command line.
1536 * If successful, put them in *<b>result</b> and return 0, and return
1537 * -1 and leave *<b>result</b> alone. */
1538 static int
1539 config_get_commandlines(int argc, char **argv, config_line_t **result)
1541 config_line_t *front = NULL;
1542 config_line_t **new = &front;
1543 char *s;
1544 int i = 1;
1546 while (i < argc) {
1547 if (!strcmp(argv[i],"-f") ||
1548 !strcmp(argv[i],"--hash-password")) {
1549 i += 2; /* command-line option with argument. ignore them. */
1550 continue;
1551 } else if (!strcmp(argv[i],"--list-fingerprint") ||
1552 !strcmp(argv[i],"--verify-config") ||
1553 !strcmp(argv[i],"--ignore-missing-torrc") ||
1554 !strcmp(argv[i],"--quiet") ||
1555 !strcmp(argv[i],"--hush")) {
1556 i += 1; /* command-line option. ignore it. */
1557 continue;
1558 } else if (!strcmp(argv[i],"--nt-service") ||
1559 !strcmp(argv[i],"-nt-service")) {
1560 i += 1;
1561 continue;
1564 if (i == argc-1) {
1565 log_warn(LD_CONFIG,"Command-line option '%s' with no value. Failing.",
1566 argv[i]);
1567 config_free_lines(front);
1568 return -1;
1571 *new = tor_malloc_zero(sizeof(config_line_t));
1572 s = argv[i];
1574 while (*s == '-')
1575 s++;
1577 (*new)->key = tor_strdup(expand_abbrev(&options_format, s, 1, 1));
1578 (*new)->value = tor_strdup(argv[i+1]);
1579 (*new)->next = NULL;
1580 log(LOG_DEBUG, LD_CONFIG, "command line: parsed keyword '%s', value '%s'",
1581 (*new)->key, (*new)->value);
1583 new = &((*new)->next);
1584 i += 2;
1586 *result = front;
1587 return 0;
1590 /** Helper: allocate a new configuration option mapping 'key' to 'val',
1591 * append it to *<b>lst</b>. */
1592 static void
1593 config_line_append(config_line_t **lst,
1594 const char *key,
1595 const char *val)
1597 config_line_t *newline;
1599 newline = tor_malloc(sizeof(config_line_t));
1600 newline->key = tor_strdup(key);
1601 newline->value = tor_strdup(val);
1602 newline->next = NULL;
1603 while (*lst)
1604 lst = &((*lst)->next);
1606 (*lst) = newline;
1609 /** Helper: parse the config string and strdup into key/value
1610 * strings. Set *result to the list, or NULL if parsing the string
1611 * failed. Return 0 on success, -1 on failure. Warn and ignore any
1612 * misformatted lines. */
1614 config_get_lines(const char *string, config_line_t **result)
1616 config_line_t *list = NULL, **next;
1617 char *k, *v;
1619 next = &list;
1620 do {
1621 k = v = NULL;
1622 string = parse_config_line_from_str(string, &k, &v);
1623 if (!string) {
1624 config_free_lines(list);
1625 tor_free(k);
1626 tor_free(v);
1627 return -1;
1629 if (k && v) {
1630 /* This list can get long, so we keep a pointer to the end of it
1631 * rather than using config_line_append over and over and getting
1632 * n^2 performance. */
1633 *next = tor_malloc(sizeof(config_line_t));
1634 (*next)->key = k;
1635 (*next)->value = v;
1636 (*next)->next = NULL;
1637 next = &((*next)->next);
1638 } else {
1639 tor_free(k);
1640 tor_free(v);
1642 } while (*string);
1644 *result = list;
1645 return 0;
1649 * Free all the configuration lines on the linked list <b>front</b>.
1651 void
1652 config_free_lines(config_line_t *front)
1654 config_line_t *tmp;
1656 while (front) {
1657 tmp = front;
1658 front = tmp->next;
1660 tor_free(tmp->key);
1661 tor_free(tmp->value);
1662 tor_free(tmp);
1666 /** Return the description for a given configuration variable, or NULL if no
1667 * description exists. */
1668 static const char *
1669 config_find_description(config_format_t *fmt, const char *name)
1671 int i;
1672 for (i=0; fmt->descriptions[i].name; ++i) {
1673 if (!strcasecmp(name, fmt->descriptions[i].name))
1674 return fmt->descriptions[i].description;
1676 return NULL;
1679 /** If <b>key</b> is a configuration option, return the corresponding
1680 * config_var_t. Otherwise, if <b>key</b> is a non-standard abbreviation,
1681 * warn, and return the corresponding config_var_t. Otherwise return NULL.
1683 static config_var_t *
1684 config_find_option(config_format_t *fmt, const char *key)
1686 int i;
1687 size_t keylen = strlen(key);
1688 if (!keylen)
1689 return NULL; /* if they say "--" on the command line, it's not an option */
1690 /* First, check for an exact (case-insensitive) match */
1691 for (i=0; fmt->vars[i].name; ++i) {
1692 if (!strcasecmp(key, fmt->vars[i].name)) {
1693 return &fmt->vars[i];
1696 /* If none, check for an abbreviated match */
1697 for (i=0; fmt->vars[i].name; ++i) {
1698 if (!strncasecmp(key, fmt->vars[i].name, keylen)) {
1699 log_warn(LD_CONFIG, "The abbreviation '%s' is deprecated. "
1700 "Please use '%s' instead",
1701 key, fmt->vars[i].name);
1702 return &fmt->vars[i];
1705 /* Okay, unrecognized option */
1706 return NULL;
1710 * Functions to assign config options.
1713 /** <b>c</b>-\>key is known to be a real key. Update <b>options</b>
1714 * with <b>c</b>-\>value and return 0, or return -1 if bad value.
1716 * Called from config_assign_line() and option_reset().
1718 static int
1719 config_assign_value(config_format_t *fmt, or_options_t *options,
1720 config_line_t *c, char **msg)
1722 int i, r, ok;
1723 char buf[1024];
1724 config_var_t *var;
1725 void *lvalue;
1727 CHECK(fmt, options);
1729 var = config_find_option(fmt, c->key);
1730 tor_assert(var);
1732 lvalue = STRUCT_VAR_P(options, var->var_offset);
1734 switch (var->type) {
1736 case CONFIG_TYPE_UINT:
1737 i = (int)tor_parse_long(c->value, 10, 0, INT_MAX, &ok, NULL);
1738 if (!ok) {
1739 r = tor_snprintf(buf, sizeof(buf),
1740 "Int keyword '%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 *(int *)lvalue = i;
1746 break;
1748 case CONFIG_TYPE_INTERVAL: {
1749 i = config_parse_interval(c->value, &ok);
1750 if (!ok) {
1751 r = tor_snprintf(buf, sizeof(buf),
1752 "Interval '%s %s' is malformed or out of bounds.",
1753 c->key, c->value);
1754 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1755 return -1;
1757 *(int *)lvalue = i;
1758 break;
1761 case CONFIG_TYPE_MEMUNIT: {
1762 uint64_t u64 = config_parse_memunit(c->value, &ok);
1763 if (!ok) {
1764 r = tor_snprintf(buf, sizeof(buf),
1765 "Value '%s %s' is malformed or out of bounds.",
1766 c->key, c->value);
1767 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1768 return -1;
1770 *(uint64_t *)lvalue = u64;
1771 break;
1774 case CONFIG_TYPE_BOOL:
1775 i = (int)tor_parse_long(c->value, 10, 0, 1, &ok, NULL);
1776 if (!ok) {
1777 r = tor_snprintf(buf, sizeof(buf),
1778 "Boolean '%s %s' expects 0 or 1.",
1779 c->key, c->value);
1780 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1781 return -1;
1783 *(int *)lvalue = i;
1784 break;
1786 case CONFIG_TYPE_STRING:
1787 case CONFIG_TYPE_FILENAME:
1788 tor_free(*(char **)lvalue);
1789 *(char **)lvalue = tor_strdup(c->value);
1790 break;
1792 case CONFIG_TYPE_DOUBLE:
1793 *(double *)lvalue = atof(c->value);
1794 break;
1796 case CONFIG_TYPE_ISOTIME:
1797 if (parse_iso_time(c->value, (time_t *)lvalue)) {
1798 r = tor_snprintf(buf, sizeof(buf),
1799 "Invalid time '%s' for keyword '%s'", c->value, c->key);
1800 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1801 return -1;
1803 break;
1805 case CONFIG_TYPE_ROUTERSET:
1806 if (*(routerset_t**)lvalue) {
1807 routerset_free(*(routerset_t**)lvalue);
1809 *(routerset_t**)lvalue = routerset_new();
1810 if (routerset_parse(*(routerset_t**)lvalue, c->value, c->key)<0) {
1811 tor_snprintf(buf, sizeof(buf), "Invalid exit list '%s' for option '%s'",
1812 c->value, c->key);
1813 *msg = tor_strdup(buf);
1814 return -1;
1816 break;
1818 case CONFIG_TYPE_CSV:
1819 if (*(smartlist_t**)lvalue) {
1820 SMARTLIST_FOREACH(*(smartlist_t**)lvalue, char *, cp, tor_free(cp));
1821 smartlist_clear(*(smartlist_t**)lvalue);
1822 } else {
1823 *(smartlist_t**)lvalue = smartlist_create();
1826 smartlist_split_string(*(smartlist_t**)lvalue, c->value, ",",
1827 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1828 break;
1830 case CONFIG_TYPE_LINELIST:
1831 case CONFIG_TYPE_LINELIST_S:
1832 config_line_append((config_line_t**)lvalue, c->key, c->value);
1833 break;
1834 case CONFIG_TYPE_OBSOLETE:
1835 log_warn(LD_CONFIG, "Skipping obsolete configuration option '%s'", c->key);
1836 break;
1837 case CONFIG_TYPE_LINELIST_V:
1838 r = tor_snprintf(buf, sizeof(buf),
1839 "You may not provide a value for virtual option '%s'", c->key);
1840 *msg = tor_strdup(r >= 0 ? buf : "internal error");
1841 return -1;
1842 default:
1843 tor_assert(0);
1844 break;
1846 return 0;
1849 /** If <b>c</b> is a syntactically valid configuration line, update
1850 * <b>options</b> with its value and return 0. Otherwise return -1 for bad
1851 * key, -2 for bad value.
1853 * If <b>clear_first</b> is set, clear the value first. Then if
1854 * <b>use_defaults</b> is set, set the value to the default.
1856 * Called from config_assign().
1858 static int
1859 config_assign_line(config_format_t *fmt, or_options_t *options,
1860 config_line_t *c, int use_defaults,
1861 int clear_first, char **msg)
1863 config_var_t *var;
1865 CHECK(fmt, options);
1867 var = config_find_option(fmt, c->key);
1868 if (!var) {
1869 if (fmt->extra) {
1870 void *lvalue = STRUCT_VAR_P(options, fmt->extra->var_offset);
1871 log_info(LD_CONFIG,
1872 "Found unrecognized option '%s'; saving it.", c->key);
1873 config_line_append((config_line_t**)lvalue, c->key, c->value);
1874 return 0;
1875 } else {
1876 char buf[1024];
1877 int tmp = tor_snprintf(buf, sizeof(buf),
1878 "Unknown option '%s'. Failing.", c->key);
1879 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
1880 return -1;
1883 /* Put keyword into canonical case. */
1884 if (strcmp(var->name, c->key)) {
1885 tor_free(c->key);
1886 c->key = tor_strdup(var->name);
1889 if (!strlen(c->value)) {
1890 /* reset or clear it, then return */
1891 if (!clear_first) {
1892 if (var->type == CONFIG_TYPE_LINELIST ||
1893 var->type == CONFIG_TYPE_LINELIST_S) {
1894 /* We got an empty linelist from the torrc or command line.
1895 As a special case, call this an error. Warn and ignore. */
1896 log_warn(LD_CONFIG,
1897 "Linelist option '%s' has no value. Skipping.", c->key);
1898 } else { /* not already cleared */
1899 option_reset(fmt, options, var, use_defaults);
1902 return 0;
1905 if (config_assign_value(fmt, options, c, msg) < 0)
1906 return -2;
1907 return 0;
1910 /** Restore the option named <b>key</b> in options to its default value.
1911 * Called from config_assign(). */
1912 static void
1913 config_reset_line(config_format_t *fmt, or_options_t *options,
1914 const char *key, int use_defaults)
1916 config_var_t *var;
1918 CHECK(fmt, options);
1920 var = config_find_option(fmt, key);
1921 if (!var)
1922 return; /* give error on next pass. */
1924 option_reset(fmt, options, var, use_defaults);
1927 /** Return true iff key is a valid configuration option. */
1929 option_is_recognized(const char *key)
1931 config_var_t *var = config_find_option(&options_format, key);
1932 return (var != NULL);
1935 /** Return the canonical name of a configuration option, or NULL
1936 * if no such option exists. */
1937 const char *
1938 option_get_canonical_name(const char *key)
1940 config_var_t *var = config_find_option(&options_format, key);
1941 return var ? var->name : NULL;
1944 /** Return a canonical list of the options assigned for key.
1946 config_line_t *
1947 option_get_assignment(or_options_t *options, const char *key)
1949 return get_assigned_option(&options_format, options, key, 1);
1952 /** Return true iff value needs to be quoted and escaped to be used in
1953 * a configuration file. */
1954 static int
1955 config_value_needs_escape(const char *value)
1957 if (*value == '\"')
1958 return 1;
1959 while (*value) {
1960 switch (*value)
1962 case '\r':
1963 case '\n':
1964 case '#':
1965 /* Note: quotes and backspaces need special handling when we are using
1966 * quotes, not otherwise, so they don't trigger escaping on their
1967 * own. */
1968 return 1;
1969 default:
1970 if (!TOR_ISPRINT(*value))
1971 return 1;
1973 ++value;
1975 return 0;
1978 /** Return a newly allocated deep copy of the lines in <b>inp</b>. */
1979 static config_line_t *
1980 config_lines_dup(const config_line_t *inp)
1982 config_line_t *result = NULL;
1983 config_line_t **next_out = &result;
1984 while (inp) {
1985 *next_out = tor_malloc(sizeof(config_line_t));
1986 (*next_out)->key = tor_strdup(inp->key);
1987 (*next_out)->value = tor_strdup(inp->value);
1988 inp = inp->next;
1989 next_out = &((*next_out)->next);
1991 (*next_out) = NULL;
1992 return result;
1995 /** Return newly allocated line or lines corresponding to <b>key</b> in the
1996 * configuration <b>options</b>. If <b>escape_val</b> is true and a
1997 * value needs to be quoted before it's put in a config file, quote and
1998 * escape that value. Return NULL if no such key exists. */
1999 static config_line_t *
2000 get_assigned_option(config_format_t *fmt, void *options,
2001 const char *key, int escape_val)
2003 config_var_t *var;
2004 const void *value;
2005 char buf[32];
2006 config_line_t *result;
2007 tor_assert(options && key);
2009 CHECK(fmt, options);
2011 var = config_find_option(fmt, key);
2012 if (!var) {
2013 log_warn(LD_CONFIG, "Unknown option '%s'. Failing.", key);
2014 return NULL;
2016 value = STRUCT_VAR_P(options, var->var_offset);
2018 result = tor_malloc_zero(sizeof(config_line_t));
2019 result->key = tor_strdup(var->name);
2020 switch (var->type)
2022 case CONFIG_TYPE_STRING:
2023 case CONFIG_TYPE_FILENAME:
2024 if (*(char**)value) {
2025 result->value = tor_strdup(*(char**)value);
2026 } else {
2027 tor_free(result->key);
2028 tor_free(result);
2029 return NULL;
2031 break;
2032 case CONFIG_TYPE_ISOTIME:
2033 if (*(time_t*)value) {
2034 result->value = tor_malloc(ISO_TIME_LEN+1);
2035 format_iso_time(result->value, *(time_t*)value);
2036 } else {
2037 tor_free(result->key);
2038 tor_free(result);
2040 escape_val = 0; /* Can't need escape. */
2041 break;
2042 case CONFIG_TYPE_INTERVAL:
2043 case CONFIG_TYPE_UINT:
2044 /* This means every or_options_t uint or bool element
2045 * needs to be an int. Not, say, a uint16_t or char. */
2046 tor_snprintf(buf, sizeof(buf), "%d", *(int*)value);
2047 result->value = tor_strdup(buf);
2048 escape_val = 0; /* Can't need escape. */
2049 break;
2050 case CONFIG_TYPE_MEMUNIT:
2051 tor_snprintf(buf, sizeof(buf), U64_FORMAT,
2052 U64_PRINTF_ARG(*(uint64_t*)value));
2053 result->value = tor_strdup(buf);
2054 escape_val = 0; /* Can't need escape. */
2055 break;
2056 case CONFIG_TYPE_DOUBLE:
2057 tor_snprintf(buf, sizeof(buf), "%f", *(double*)value);
2058 result->value = tor_strdup(buf);
2059 escape_val = 0; /* Can't need escape. */
2060 break;
2061 case CONFIG_TYPE_BOOL:
2062 result->value = tor_strdup(*(int*)value ? "1" : "0");
2063 escape_val = 0; /* Can't need escape. */
2064 break;
2065 case CONFIG_TYPE_ROUTERSET:
2066 result->value = routerset_to_string(*(routerset_t**)value);
2067 break;
2068 case CONFIG_TYPE_CSV:
2069 if (*(smartlist_t**)value)
2070 result->value =
2071 smartlist_join_strings(*(smartlist_t**)value, ",", 0, NULL);
2072 else
2073 result->value = tor_strdup("");
2074 break;
2075 case CONFIG_TYPE_OBSOLETE:
2076 log_fn(LOG_PROTOCOL_WARN, LD_CONFIG,
2077 "You asked me for the value of an obsolete config option '%s'.",
2078 key);
2079 tor_free(result->key);
2080 tor_free(result);
2081 return NULL;
2082 case CONFIG_TYPE_LINELIST_S:
2083 log_warn(LD_CONFIG,
2084 "Can't return context-sensitive '%s' on its own", key);
2085 tor_free(result->key);
2086 tor_free(result);
2087 return NULL;
2088 case CONFIG_TYPE_LINELIST:
2089 case CONFIG_TYPE_LINELIST_V:
2090 tor_free(result->key);
2091 tor_free(result);
2092 result = config_lines_dup(*(const config_line_t**)value);
2093 break;
2094 default:
2095 tor_free(result->key);
2096 tor_free(result);
2097 log_warn(LD_BUG,"Unknown type %d for known key '%s'",
2098 var->type, key);
2099 return NULL;
2102 if (escape_val) {
2103 config_line_t *line;
2104 for (line = result; line; line = line->next) {
2105 if (line->value && config_value_needs_escape(line->value)) {
2106 char *newval = esc_for_log(line->value);
2107 tor_free(line->value);
2108 line->value = newval;
2113 return result;
2116 /** Iterate through the linked list of requested options <b>list</b>.
2117 * For each item, convert as appropriate and assign to <b>options</b>.
2118 * If an item is unrecognized, set *msg and return -1 immediately,
2119 * else return 0 for success.
2121 * If <b>clear_first</b>, interpret config options as replacing (not
2122 * extending) their previous values. If <b>clear_first</b> is set,
2123 * then <b>use_defaults</b> to decide if you set to defaults after
2124 * clearing, or make the value 0 or NULL.
2126 * Here are the use cases:
2127 * 1. A non-empty AllowInvalid line in your torrc. Appends to current
2128 * if linelist, replaces current if csv.
2129 * 2. An empty AllowInvalid line in your torrc. Should clear it.
2130 * 3. "RESETCONF AllowInvalid" sets it to default.
2131 * 4. "SETCONF AllowInvalid" makes it NULL.
2132 * 5. "SETCONF AllowInvalid=foo" clears it and sets it to "foo".
2134 * Use_defaults Clear_first
2135 * 0 0 "append"
2136 * 1 0 undefined, don't use
2137 * 0 1 "set to null first"
2138 * 1 1 "set to defaults first"
2139 * Return 0 on success, -1 on bad key, -2 on bad value.
2141 * As an additional special case, if a LINELIST config option has
2142 * no value and clear_first is 0, then warn and ignore it.
2146 There are three call cases for config_assign() currently.
2148 Case one: Torrc entry
2149 options_init_from_torrc() calls config_assign(0, 0)
2150 calls config_assign_line(0, 0).
2151 if value is empty, calls option_reset(0) and returns.
2152 calls config_assign_value(), appends.
2154 Case two: setconf
2155 options_trial_assign() calls config_assign(0, 1)
2156 calls config_reset_line(0)
2157 calls option_reset(0)
2158 calls option_clear().
2159 calls config_assign_line(0, 1).
2160 if value is empty, returns.
2161 calls config_assign_value(), appends.
2163 Case three: resetconf
2164 options_trial_assign() calls config_assign(1, 1)
2165 calls config_reset_line(1)
2166 calls option_reset(1)
2167 calls option_clear().
2168 calls config_assign_value(default)
2169 calls config_assign_line(1, 1).
2170 returns.
2172 static int
2173 config_assign(config_format_t *fmt, void *options, config_line_t *list,
2174 int use_defaults, int clear_first, char **msg)
2176 config_line_t *p;
2178 CHECK(fmt, options);
2180 /* pass 1: normalize keys */
2181 for (p = list; p; p = p->next) {
2182 const char *full = expand_abbrev(fmt, p->key, 0, 1);
2183 if (strcmp(full,p->key)) {
2184 tor_free(p->key);
2185 p->key = tor_strdup(full);
2189 /* pass 2: if we're reading from a resetting source, clear all
2190 * mentioned config options, and maybe set to their defaults. */
2191 if (clear_first) {
2192 for (p = list; p; p = p->next)
2193 config_reset_line(fmt, options, p->key, use_defaults);
2196 /* pass 3: assign. */
2197 while (list) {
2198 int r;
2199 if ((r=config_assign_line(fmt, options, list, use_defaults,
2200 clear_first, msg)))
2201 return r;
2202 list = list->next;
2204 return 0;
2207 /** Try assigning <b>list</b> to the global options. You do this by duping
2208 * options, assigning list to the new one, then validating it. If it's
2209 * ok, then throw out the old one and stick with the new one. Else,
2210 * revert to old and return failure. Return SETOPT_OK on success, or
2211 * a setopt_err_t on failure.
2213 * If not success, point *<b>msg</b> to a newly allocated string describing
2214 * what went wrong.
2216 setopt_err_t
2217 options_trial_assign(config_line_t *list, int use_defaults,
2218 int clear_first, char **msg)
2220 int r;
2221 or_options_t *trial_options = options_dup(&options_format, get_options());
2223 if ((r=config_assign(&options_format, trial_options,
2224 list, use_defaults, clear_first, msg)) < 0) {
2225 config_free(&options_format, trial_options);
2226 return r;
2229 if (options_validate(get_options(), trial_options, 1, msg) < 0) {
2230 config_free(&options_format, trial_options);
2231 return SETOPT_ERR_PARSE; /*XXX make this a separate return value. */
2234 if (options_transition_allowed(get_options(), trial_options, msg) < 0) {
2235 config_free(&options_format, trial_options);
2236 return SETOPT_ERR_TRANSITION;
2239 if (set_options(trial_options, msg)<0) {
2240 config_free(&options_format, trial_options);
2241 return SETOPT_ERR_SETTING;
2244 /* we liked it. put it in place. */
2245 return SETOPT_OK;
2248 /** Reset config option <b>var</b> to 0, 0.0, NULL, or the equivalent.
2249 * Called from option_reset() and config_free(). */
2250 static void
2251 option_clear(config_format_t *fmt, or_options_t *options, config_var_t *var)
2253 void *lvalue = STRUCT_VAR_P(options, var->var_offset);
2254 (void)fmt; /* unused */
2255 switch (var->type) {
2256 case CONFIG_TYPE_STRING:
2257 case CONFIG_TYPE_FILENAME:
2258 tor_free(*(char**)lvalue);
2259 break;
2260 case CONFIG_TYPE_DOUBLE:
2261 *(double*)lvalue = 0.0;
2262 break;
2263 case CONFIG_TYPE_ISOTIME:
2264 *(time_t*)lvalue = 0;
2265 case CONFIG_TYPE_INTERVAL:
2266 case CONFIG_TYPE_UINT:
2267 case CONFIG_TYPE_BOOL:
2268 *(int*)lvalue = 0;
2269 break;
2270 case CONFIG_TYPE_MEMUNIT:
2271 *(uint64_t*)lvalue = 0;
2272 break;
2273 case CONFIG_TYPE_ROUTERSET:
2274 if (*(routerset_t**)lvalue) {
2275 routerset_free(*(routerset_t**)lvalue);
2276 *(routerset_t**)lvalue = NULL;
2278 case CONFIG_TYPE_CSV:
2279 if (*(smartlist_t**)lvalue) {
2280 SMARTLIST_FOREACH(*(smartlist_t **)lvalue, char *, cp, tor_free(cp));
2281 smartlist_free(*(smartlist_t **)lvalue);
2282 *(smartlist_t **)lvalue = NULL;
2284 break;
2285 case CONFIG_TYPE_LINELIST:
2286 case CONFIG_TYPE_LINELIST_S:
2287 config_free_lines(*(config_line_t **)lvalue);
2288 *(config_line_t **)lvalue = NULL;
2289 break;
2290 case CONFIG_TYPE_LINELIST_V:
2291 /* handled by linelist_s. */
2292 break;
2293 case CONFIG_TYPE_OBSOLETE:
2294 break;
2298 /** Clear the option indexed by <b>var</b> in <b>options</b>. Then if
2299 * <b>use_defaults</b>, set it to its default value.
2300 * Called by config_init() and option_reset_line() and option_assign_line(). */
2301 static void
2302 option_reset(config_format_t *fmt, or_options_t *options,
2303 config_var_t *var, int use_defaults)
2305 config_line_t *c;
2306 char *msg = NULL;
2307 CHECK(fmt, options);
2308 option_clear(fmt, options, var); /* clear it first */
2309 if (!use_defaults)
2310 return; /* all done */
2311 if (var->initvalue) {
2312 c = tor_malloc_zero(sizeof(config_line_t));
2313 c->key = tor_strdup(var->name);
2314 c->value = tor_strdup(var->initvalue);
2315 if (config_assign_value(fmt, options, c, &msg) < 0) {
2316 log_warn(LD_BUG, "Failed to assign default: %s", msg);
2317 tor_free(msg); /* if this happens it's a bug */
2319 config_free_lines(c);
2323 /** Print a usage message for tor. */
2324 static void
2325 print_usage(void)
2327 printf(
2328 "Copyright (c) 2001-2004, Roger Dingledine\n"
2329 "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
2330 "Copyright (c) 2007-2009, The Tor Project, Inc.\n\n"
2331 "tor -f <torrc> [args]\n"
2332 "See man page for options, or https://www.torproject.org/ for "
2333 "documentation.\n");
2336 /** Print all non-obsolete torrc options. */
2337 static void
2338 list_torrc_options(void)
2340 int i;
2341 smartlist_t *lines = smartlist_create();
2342 for (i = 0; _option_vars[i].name; ++i) {
2343 config_var_t *var = &_option_vars[i];
2344 const char *desc;
2345 if (var->type == CONFIG_TYPE_OBSOLETE ||
2346 var->type == CONFIG_TYPE_LINELIST_V)
2347 continue;
2348 desc = config_find_description(&options_format, var->name);
2349 printf("%s\n", var->name);
2350 if (desc) {
2351 wrap_string(lines, desc, 76, " ", " ");
2352 SMARTLIST_FOREACH(lines, char *, cp, {
2353 printf("%s", cp);
2354 tor_free(cp);
2356 smartlist_clear(lines);
2359 smartlist_free(lines);
2362 /** Last value actually set by resolve_my_address. */
2363 static uint32_t last_resolved_addr = 0;
2365 * Based on <b>options-\>Address</b>, guess our public IP address and put it
2366 * (in host order) into *<b>addr_out</b>. If <b>hostname_out</b> is provided,
2367 * set *<b>hostname_out</b> to a new string holding the hostname we used to
2368 * get the address. Return 0 if all is well, or -1 if we can't find a suitable
2369 * public IP address.
2372 resolve_my_address(int warn_severity, or_options_t *options,
2373 uint32_t *addr_out, char **hostname_out)
2375 struct in_addr in;
2376 struct hostent *rent;
2377 char hostname[256];
2378 int explicit_ip=1;
2379 int explicit_hostname=1;
2380 int from_interface=0;
2381 char tmpbuf[INET_NTOA_BUF_LEN];
2382 const char *address = options->Address;
2383 int notice_severity = warn_severity <= LOG_NOTICE ?
2384 LOG_NOTICE : warn_severity;
2386 tor_assert(addr_out);
2388 if (address && *address) {
2389 strlcpy(hostname, address, sizeof(hostname));
2390 } else { /* then we need to guess our address */
2391 explicit_ip = 0; /* it's implicit */
2392 explicit_hostname = 0; /* it's implicit */
2394 if (gethostname(hostname, sizeof(hostname)) < 0) {
2395 log_fn(warn_severity, LD_NET,"Error obtaining local hostname");
2396 return -1;
2398 log_debug(LD_CONFIG,"Guessed local host name as '%s'",hostname);
2401 /* now we know hostname. resolve it and keep only the IP address */
2403 if (tor_inet_aton(hostname, &in) == 0) {
2404 /* then we have to resolve it */
2405 explicit_ip = 0;
2406 rent = (struct hostent *)gethostbyname(hostname);
2407 if (!rent) {
2408 uint32_t interface_ip;
2410 if (explicit_hostname) {
2411 log_fn(warn_severity, LD_CONFIG,
2412 "Could not resolve local Address '%s'. Failing.", hostname);
2413 return -1;
2415 log_fn(notice_severity, LD_CONFIG,
2416 "Could not resolve guessed local hostname '%s'. "
2417 "Trying something else.", hostname);
2418 if (get_interface_address(warn_severity, &interface_ip)) {
2419 log_fn(warn_severity, LD_CONFIG,
2420 "Could not get local interface IP address. Failing.");
2421 return -1;
2423 from_interface = 1;
2424 in.s_addr = htonl(interface_ip);
2425 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2426 log_fn(notice_severity, LD_CONFIG, "Learned IP address '%s' for "
2427 "local interface. Using that.", tmpbuf);
2428 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2429 } else {
2430 tor_assert(rent->h_length == 4);
2431 memcpy(&in.s_addr, rent->h_addr, rent->h_length);
2433 if (!explicit_hostname &&
2434 is_internal_IP(ntohl(in.s_addr), 0)) {
2435 uint32_t interface_ip;
2437 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2438 log_fn(notice_severity, LD_CONFIG, "Guessed local hostname '%s' "
2439 "resolves to a private IP address (%s). Trying something "
2440 "else.", hostname, tmpbuf);
2442 if (get_interface_address(warn_severity, &interface_ip)) {
2443 log_fn(warn_severity, LD_CONFIG,
2444 "Could not get local interface IP address. Too bad.");
2445 } else if (is_internal_IP(interface_ip, 0)) {
2446 struct in_addr in2;
2447 in2.s_addr = htonl(interface_ip);
2448 tor_inet_ntoa(&in2,tmpbuf,sizeof(tmpbuf));
2449 log_fn(notice_severity, LD_CONFIG,
2450 "Interface IP address '%s' is a private address too. "
2451 "Ignoring.", tmpbuf);
2452 } else {
2453 from_interface = 1;
2454 in.s_addr = htonl(interface_ip);
2455 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2456 log_fn(notice_severity, LD_CONFIG,
2457 "Learned IP address '%s' for local interface."
2458 " Using that.", tmpbuf);
2459 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2465 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2466 if (is_internal_IP(ntohl(in.s_addr), 0) &&
2467 options->_PublishServerDescriptor) {
2468 /* make sure we're ok with publishing an internal IP */
2469 if (!options->DirServers && !options->AlternateDirAuthority) {
2470 /* if they are using the default dirservers, disallow internal IPs
2471 * always. */
2472 log_fn(warn_severity, LD_CONFIG,
2473 "Address '%s' resolves to private IP address '%s'. "
2474 "Tor servers that use the default DirServers must have public "
2475 "IP addresses.", hostname, tmpbuf);
2476 return -1;
2478 if (!explicit_ip) {
2479 /* even if they've set their own dirservers, require an explicit IP if
2480 * they're using an internal address. */
2481 log_fn(warn_severity, LD_CONFIG, "Address '%s' resolves to private "
2482 "IP address '%s'. Please set the Address config option to be "
2483 "the IP address you want to use.", hostname, tmpbuf);
2484 return -1;
2488 log_debug(LD_CONFIG, "Resolved Address to '%s'.", tmpbuf);
2489 *addr_out = ntohl(in.s_addr);
2490 if (last_resolved_addr && last_resolved_addr != *addr_out) {
2491 /* Leave this as a notice, regardless of the requested severity,
2492 * at least until dynamic IP address support becomes bulletproof. */
2493 log_notice(LD_NET,
2494 "Your IP address seems to have changed to %s. Updating.",
2495 tmpbuf);
2496 ip_address_changed(0);
2498 if (last_resolved_addr != *addr_out) {
2499 const char *method;
2500 const char *h = hostname;
2501 if (explicit_ip) {
2502 method = "CONFIGURED";
2503 h = NULL;
2504 } else if (explicit_hostname) {
2505 method = "RESOLVED";
2506 } else if (from_interface) {
2507 method = "INTERFACE";
2508 h = NULL;
2509 } else {
2510 method = "GETHOSTNAME";
2512 control_event_server_status(LOG_NOTICE,
2513 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s %s%s",
2514 tmpbuf, method, h?"HOSTNAME=":"", h);
2516 last_resolved_addr = *addr_out;
2517 if (hostname_out)
2518 *hostname_out = tor_strdup(hostname);
2519 return 0;
2522 /** Return true iff <b>addr</b> is judged to be on the same network as us, or
2523 * on a private network.
2526 is_local_addr(const tor_addr_t *addr)
2528 if (tor_addr_is_internal(addr, 0))
2529 return 1;
2530 /* Check whether ip is on the same /24 as we are. */
2531 if (get_options()->EnforceDistinctSubnets == 0)
2532 return 0;
2533 if (tor_addr_family(addr) == AF_INET) {
2534 /*XXXX022 IP6 what corresponds to an /24? */
2535 uint32_t ip = tor_addr_to_ipv4h(addr);
2537 /* It's possible that this next check will hit before the first time
2538 * resolve_my_address actually succeeds. (For clients, it is likely that
2539 * resolve_my_address will never be called at all). In those cases,
2540 * last_resolved_addr will be 0, and so checking to see whether ip is on
2541 * the same /24 as last_resolved_addr will be the same as checking whether
2542 * it was on net 0, which is already done by is_internal_IP.
2544 if ((last_resolved_addr & 0xffffff00ul) == (ip & 0xffffff00ul))
2545 return 1;
2547 return 0;
2550 /** Called when we don't have a nickname set. Try to guess a good nickname
2551 * based on the hostname, and return it in a newly allocated string. If we
2552 * can't, return NULL and let the caller warn if it wants to. */
2553 static char *
2554 get_default_nickname(void)
2556 static const char * const bad_default_nicknames[] = {
2557 "localhost",
2558 NULL,
2560 char localhostname[256];
2561 char *cp, *out, *outp;
2562 int i;
2564 if (gethostname(localhostname, sizeof(localhostname)) < 0)
2565 return NULL;
2567 /* Put it in lowercase; stop at the first dot. */
2568 if ((cp = strchr(localhostname, '.')))
2569 *cp = '\0';
2570 tor_strlower(localhostname);
2572 /* Strip invalid characters. */
2573 cp = localhostname;
2574 out = outp = tor_malloc(strlen(localhostname) + 1);
2575 while (*cp) {
2576 if (strchr(LEGAL_NICKNAME_CHARACTERS, *cp))
2577 *outp++ = *cp++;
2578 else
2579 cp++;
2581 *outp = '\0';
2583 /* Enforce length. */
2584 if (strlen(out) > MAX_NICKNAME_LEN)
2585 out[MAX_NICKNAME_LEN]='\0';
2587 /* Check for dumb names. */
2588 for (i = 0; bad_default_nicknames[i]; ++i) {
2589 if (!strcmp(out, bad_default_nicknames[i])) {
2590 tor_free(out);
2591 return NULL;
2595 return out;
2598 /** Release storage held by <b>options</b>. */
2599 static void
2600 config_free(config_format_t *fmt, void *options)
2602 int i;
2604 tor_assert(options);
2606 for (i=0; fmt->vars[i].name; ++i)
2607 option_clear(fmt, options, &(fmt->vars[i]));
2608 if (fmt->extra) {
2609 config_line_t **linep = STRUCT_VAR_P(options, fmt->extra->var_offset);
2610 config_free_lines(*linep);
2611 *linep = NULL;
2613 tor_free(options);
2616 /** Return true iff a and b contain identical keys and values in identical
2617 * order. */
2618 static int
2619 config_lines_eq(config_line_t *a, config_line_t *b)
2621 while (a && b) {
2622 if (strcasecmp(a->key, b->key) || strcmp(a->value, b->value))
2623 return 0;
2624 a = a->next;
2625 b = b->next;
2627 if (a || b)
2628 return 0;
2629 return 1;
2632 /** Return true iff the option <b>name</b> has the same value in <b>o1</b>
2633 * and <b>o2</b>. Must not be called for LINELIST_S or OBSOLETE options.
2635 static int
2636 option_is_same(config_format_t *fmt,
2637 or_options_t *o1, or_options_t *o2, const char *name)
2639 config_line_t *c1, *c2;
2640 int r = 1;
2641 CHECK(fmt, o1);
2642 CHECK(fmt, o2);
2644 c1 = get_assigned_option(fmt, o1, name, 0);
2645 c2 = get_assigned_option(fmt, o2, name, 0);
2646 r = config_lines_eq(c1, c2);
2647 config_free_lines(c1);
2648 config_free_lines(c2);
2649 return r;
2652 /** Copy storage held by <b>old</b> into a new or_options_t and return it. */
2653 static or_options_t *
2654 options_dup(config_format_t *fmt, or_options_t *old)
2656 or_options_t *newopts;
2657 int i;
2658 config_line_t *line;
2660 newopts = config_alloc(fmt);
2661 for (i=0; fmt->vars[i].name; ++i) {
2662 if (fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
2663 continue;
2664 if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE)
2665 continue;
2666 line = get_assigned_option(fmt, old, fmt->vars[i].name, 0);
2667 if (line) {
2668 char *msg = NULL;
2669 if (config_assign(fmt, newopts, line, 0, 0, &msg) < 0) {
2670 log_err(LD_BUG, "Config_get_assigned_option() generated "
2671 "something we couldn't config_assign(): %s", msg);
2672 tor_free(msg);
2673 tor_assert(0);
2676 config_free_lines(line);
2678 return newopts;
2681 /** Return a new empty or_options_t. Used for testing. */
2682 or_options_t *
2683 options_new(void)
2685 return config_alloc(&options_format);
2688 /** Set <b>options</b> to hold reasonable defaults for most options.
2689 * Each option defaults to zero. */
2690 void
2691 options_init(or_options_t *options)
2693 config_init(&options_format, options);
2696 /* Check if the port number given in <b>port_option</b> in combination with
2697 * the specified port in <b>listen_options</b> will result in Tor actually
2698 * opening a low port (meaning a port lower than 1024). Return 1 if
2699 * it is, or 0 if it isn't or the concept of a low port isn't applicable for
2700 * the platform we're on. */
2701 static int
2702 is_listening_on_low_port(uint16_t port_option,
2703 const config_line_t *listen_options)
2705 #ifdef MS_WINDOWS
2706 return 0; /* No port is too low for windows. */
2707 #else
2708 const config_line_t *l;
2709 uint16_t p;
2710 if (port_option == 0)
2711 return 0; /* We're not listening */
2712 if (listen_options == NULL)
2713 return (port_option < 1024);
2715 for (l = listen_options; l; l = l->next) {
2716 parse_addr_port(LOG_WARN, l->value, NULL, NULL, &p);
2717 if (p<1024) {
2718 return 1;
2721 return 0;
2722 #endif
2725 /** Set all vars in the configuration object <b>options</b> to their default
2726 * values. */
2727 static void
2728 config_init(config_format_t *fmt, void *options)
2730 int i;
2731 config_var_t *var;
2732 CHECK(fmt, options);
2734 for (i=0; fmt->vars[i].name; ++i) {
2735 var = &fmt->vars[i];
2736 if (!var->initvalue)
2737 continue; /* defaults to NULL or 0 */
2738 option_reset(fmt, options, var, 1);
2742 /** Allocate and return a new string holding the written-out values of the vars
2743 * in 'options'. If 'minimal', do not write out any default-valued vars.
2744 * Else, if comment_defaults, write default values as comments.
2746 static char *
2747 config_dump(config_format_t *fmt, void *options, int minimal,
2748 int comment_defaults)
2750 smartlist_t *elements;
2751 or_options_t *defaults;
2752 config_line_t *line, *assigned;
2753 char *result;
2754 int i;
2755 const char *desc;
2756 char *msg = NULL;
2758 defaults = config_alloc(fmt);
2759 config_init(fmt, defaults);
2761 /* XXX use a 1 here so we don't add a new log line while dumping */
2762 if (fmt->validate_fn(NULL,defaults, 1, &msg) < 0) {
2763 log_err(LD_BUG, "Failed to validate default config.");
2764 tor_free(msg);
2765 tor_assert(0);
2768 elements = smartlist_create();
2769 for (i=0; fmt->vars[i].name; ++i) {
2770 int comment_option = 0;
2771 if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE ||
2772 fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
2773 continue;
2774 /* Don't save 'hidden' control variables. */
2775 if (!strcmpstart(fmt->vars[i].name, "__"))
2776 continue;
2777 if (minimal && option_is_same(fmt, options, defaults, fmt->vars[i].name))
2778 continue;
2779 else if (comment_defaults &&
2780 option_is_same(fmt, options, defaults, fmt->vars[i].name))
2781 comment_option = 1;
2783 desc = config_find_description(fmt, fmt->vars[i].name);
2784 line = assigned = get_assigned_option(fmt, options, fmt->vars[i].name, 1);
2786 if (line && desc) {
2787 /* Only dump the description if there's something to describe. */
2788 wrap_string(elements, desc, 78, "# ", "# ");
2791 for (; line; line = line->next) {
2792 size_t len = strlen(line->key) + strlen(line->value) + 5;
2793 char *tmp;
2794 tmp = tor_malloc(len);
2795 if (tor_snprintf(tmp, len, "%s%s %s\n",
2796 comment_option ? "# " : "",
2797 line->key, line->value)<0) {
2798 log_err(LD_BUG,"Internal error writing option value");
2799 tor_assert(0);
2801 smartlist_add(elements, tmp);
2803 config_free_lines(assigned);
2806 if (fmt->extra) {
2807 line = *(config_line_t**)STRUCT_VAR_P(options, fmt->extra->var_offset);
2808 for (; line; line = line->next) {
2809 size_t len = strlen(line->key) + strlen(line->value) + 3;
2810 char *tmp;
2811 tmp = tor_malloc(len);
2812 if (tor_snprintf(tmp, len, "%s %s\n", line->key, line->value)<0) {
2813 log_err(LD_BUG,"Internal error writing option value");
2814 tor_assert(0);
2816 smartlist_add(elements, tmp);
2820 result = smartlist_join_strings(elements, "", 0, NULL);
2821 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
2822 smartlist_free(elements);
2823 config_free(fmt, defaults);
2824 return result;
2827 /** Return a string containing a possible configuration file that would give
2828 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
2829 * include options that are the same as Tor's defaults.
2831 static char *
2832 options_dump(or_options_t *options, int minimal)
2834 return config_dump(&options_format, options, minimal, 0);
2837 /** Return 0 if every element of sl is a string holding a decimal
2838 * representation of a port number, or if sl is NULL.
2839 * Otherwise set *msg and return -1. */
2840 static int
2841 validate_ports_csv(smartlist_t *sl, const char *name, char **msg)
2843 int i;
2844 char buf[1024];
2845 tor_assert(name);
2847 if (!sl)
2848 return 0;
2850 SMARTLIST_FOREACH(sl, const char *, cp,
2852 i = atoi(cp);
2853 if (i < 1 || i > 65535) {
2854 int r = tor_snprintf(buf, sizeof(buf),
2855 "Port '%s' out of range in %s", cp, name);
2856 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2857 return -1;
2860 return 0;
2863 /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
2864 * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
2865 * Else return 0.
2867 static int
2868 ensure_bandwidth_cap(uint64_t *value, const char *desc, char **msg)
2870 int r;
2871 char buf[1024];
2872 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2873 /* This handles an understandable special case where somebody says "2gb"
2874 * whereas our actual maximum is 2gb-1 (INT_MAX) */
2875 --*value;
2877 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2878 r = tor_snprintf(buf, sizeof(buf), "%s ("U64_FORMAT") must be at most %d",
2879 desc, U64_PRINTF_ARG(*value),
2880 ROUTER_MAX_DECLARED_BANDWIDTH);
2881 *msg = tor_strdup(r >= 0 ? buf : "internal error");
2882 return -1;
2884 return 0;
2887 /** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
2888 * and write it to <b>options</b>-\>_PublishServerDescriptor. Treat "1"
2889 * as "v2,v3" unless BridgeRelay is 1, in which case treat it as "bridge".
2890 * Treat "0" as "".
2891 * Return 0 on success or -1 if not a recognized authority type (in which
2892 * case the value of _PublishServerDescriptor is undefined). */
2893 static int
2894 compute_publishserverdescriptor(or_options_t *options)
2896 smartlist_t *list = options->PublishServerDescriptor;
2897 authority_type_t *auth = &options->_PublishServerDescriptor;
2898 *auth = NO_AUTHORITY;
2899 if (!list) /* empty list, answer is none */
2900 return 0;
2901 SMARTLIST_FOREACH(list, const char *, string, {
2902 if (!strcasecmp(string, "v1"))
2903 *auth |= V1_AUTHORITY;
2904 else if (!strcmp(string, "1"))
2905 if (options->BridgeRelay)
2906 *auth |= BRIDGE_AUTHORITY;
2907 else
2908 *auth |= V2_AUTHORITY | V3_AUTHORITY;
2909 else if (!strcasecmp(string, "v2"))
2910 *auth |= V2_AUTHORITY;
2911 else if (!strcasecmp(string, "v3"))
2912 *auth |= V3_AUTHORITY;
2913 else if (!strcasecmp(string, "bridge"))
2914 *auth |= BRIDGE_AUTHORITY;
2915 else if (!strcasecmp(string, "hidserv"))
2916 *auth |= HIDSERV_AUTHORITY;
2917 else if (!strcasecmp(string, "") || !strcmp(string, "0"))
2918 /* no authority */;
2919 else
2920 return -1;
2922 return 0;
2925 /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
2926 * services can overload the directory system. */
2927 #define MIN_REND_POST_PERIOD (10*60)
2929 /** Highest allowable value for RendPostPeriod. */
2930 #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
2932 /** Lowest allowable value for CircuitBuildTimeout; values too low will
2933 * increase network load because of failing connections being retried, and
2934 * might prevent users from connecting to the network at all. */
2935 #define MIN_CIRCUIT_BUILD_TIMEOUT 30
2937 /** Lowest allowable value for MaxCircuitDirtiness; if this is too low, Tor
2938 * will generate too many circuits and potentially overload the network. */
2939 #define MIN_MAX_CIRCUIT_DIRTINESS 10
2941 /** Return 0 if every setting in <b>options</b> is reasonable, and a
2942 * permissible transition from <b>old_options</b>. Else return -1.
2943 * Should have no side effects, except for normalizing the contents of
2944 * <b>options</b>.
2946 * On error, tor_strdup an error explanation into *<b>msg</b>.
2948 * XXX
2949 * If <b>from_setconf</b>, we were called by the controller, and our
2950 * Log line should stay empty. If it's 0, then give us a default log
2951 * if there are no logs defined.
2953 static int
2954 options_validate(or_options_t *old_options, or_options_t *options,
2955 int from_setconf, char **msg)
2957 int i, r;
2958 config_line_t *cl;
2959 const char *uname = get_uname();
2960 char buf[1024];
2961 #define REJECT(arg) \
2962 STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
2963 #define COMPLAIN(arg) STMT_BEGIN log(LOG_WARN, LD_CONFIG, arg); STMT_END
2965 tor_assert(msg);
2966 *msg = NULL;
2968 if (options->ORPort < 0 || options->ORPort > 65535)
2969 REJECT("ORPort option out of bounds.");
2971 if (server_mode(options) &&
2972 (!strcmpstart(uname, "Windows 95") ||
2973 !strcmpstart(uname, "Windows 98") ||
2974 !strcmpstart(uname, "Windows Me"))) {
2975 log(LOG_WARN, LD_CONFIG, "Tor is running as a server, but you are "
2976 "running %s; this probably won't work. See "
2977 "https://wiki.torproject.org/TheOnionRouter/TorFAQ#ServerOS "
2978 "for details.", uname);
2981 if (options->ORPort == 0 && options->ORListenAddress != NULL)
2982 REJECT("ORPort must be defined if ORListenAddress is defined.");
2984 if (options->DirPort == 0 && options->DirListenAddress != NULL)
2985 REJECT("DirPort must be defined if DirListenAddress is defined.");
2987 if (options->DNSPort == 0 && options->DNSListenAddress != NULL)
2988 REJECT("DNSPort must be defined if DNSListenAddress is defined.");
2990 if (options->ControlPort == 0 && options->ControlListenAddress != NULL)
2991 REJECT("ControlPort must be defined if ControlListenAddress is defined.");
2993 if (options->TransPort == 0 && options->TransListenAddress != NULL)
2994 REJECT("TransPort must be defined if TransListenAddress is defined.");
2996 if (options->NatdPort == 0 && options->NatdListenAddress != NULL)
2997 REJECT("NatdPort must be defined if NatdListenAddress is defined.");
2999 /* Don't gripe about SocksPort 0 with SocksListenAddress set; a standard
3000 * configuration does this. */
3002 for (i = 0; i < 3; ++i) {
3003 int is_socks = i==0;
3004 int is_trans = i==1;
3005 config_line_t *line, *opt, *old;
3006 const char *tp;
3007 if (is_socks) {
3008 opt = options->SocksListenAddress;
3009 old = old_options ? old_options->SocksListenAddress : NULL;
3010 tp = "SOCKS proxy";
3011 } else if (is_trans) {
3012 opt = options->TransListenAddress;
3013 old = old_options ? old_options->TransListenAddress : NULL;
3014 tp = "transparent proxy";
3015 } else {
3016 opt = options->NatdListenAddress;
3017 old = old_options ? old_options->NatdListenAddress : NULL;
3018 tp = "natd proxy";
3021 for (line = opt; line; line = line->next) {
3022 char *address = NULL;
3023 uint16_t port;
3024 uint32_t addr;
3025 if (parse_addr_port(LOG_WARN, line->value, &address, &addr, &port)<0)
3026 continue; /* We'll warn about this later. */
3027 if (!is_internal_IP(addr, 1) &&
3028 (!old_options || !config_lines_eq(old, opt))) {
3029 log_warn(LD_CONFIG,
3030 "You specified a public address '%s' for a %s. Other "
3031 "people on the Internet might find your computer and use it as "
3032 "an open %s. Please don't allow this unless you have "
3033 "a good reason.", address, tp, tp);
3035 tor_free(address);
3039 if (validate_data_directory(options)<0)
3040 REJECT("Invalid DataDirectory");
3042 if (options->Nickname == NULL) {
3043 if (server_mode(options)) {
3044 if (!(options->Nickname = get_default_nickname())) {
3045 log_notice(LD_CONFIG, "Couldn't pick a nickname based on "
3046 "our hostname; using %s instead.", UNNAMED_ROUTER_NICKNAME);
3047 options->Nickname = tor_strdup(UNNAMED_ROUTER_NICKNAME);
3048 } else {
3049 log_notice(LD_CONFIG, "Choosing default nickname '%s'",
3050 options->Nickname);
3053 } else {
3054 if (!is_legal_nickname(options->Nickname)) {
3055 r = tor_snprintf(buf, sizeof(buf),
3056 "Nickname '%s' is wrong length or contains illegal characters.",
3057 options->Nickname);
3058 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3059 return -1;
3063 if (server_mode(options) && !options->ContactInfo)
3064 log(LOG_NOTICE, LD_CONFIG, "Your ContactInfo config option is not set. "
3065 "Please consider setting it, so we can contact you if your server is "
3066 "misconfigured or something else goes wrong.");
3068 /* Special case on first boot if no Log options are given. */
3069 if (!options->Logs && !options->RunAsDaemon && !from_setconf)
3070 config_line_append(&options->Logs, "Log", "notice stdout");
3072 if (options_init_logs(options, 1)<0) /* Validate the log(s) */
3073 REJECT("Failed to validate Log options. See logs for details.");
3075 if (options->NoPublish) {
3076 log(LOG_WARN, LD_CONFIG,
3077 "NoPublish is obsolete. Use PublishServerDescriptor instead.");
3078 SMARTLIST_FOREACH(options->PublishServerDescriptor, char *, s,
3079 tor_free(s));
3080 smartlist_clear(options->PublishServerDescriptor);
3083 if (authdir_mode(options)) {
3084 /* confirm that our address isn't broken, so we can complain now */
3085 uint32_t tmp;
3086 if (resolve_my_address(LOG_WARN, options, &tmp, NULL) < 0)
3087 REJECT("Failed to resolve/guess local address. See logs for details.");
3090 #ifndef MS_WINDOWS
3091 if (options->RunAsDaemon && torrc_fname && path_is_relative(torrc_fname))
3092 REJECT("Can't use a relative path to torrc when RunAsDaemon is set.");
3093 #endif
3095 if (options->SocksPort < 0 || options->SocksPort > 65535)
3096 REJECT("SocksPort option out of bounds.");
3098 if (options->DNSPort < 0 || options->DNSPort > 65535)
3099 REJECT("DNSPort option out of bounds.");
3101 if (options->TransPort < 0 || options->TransPort > 65535)
3102 REJECT("TransPort option out of bounds.");
3104 if (options->NatdPort < 0 || options->NatdPort > 65535)
3105 REJECT("NatdPort option out of bounds.");
3107 if (options->SocksPort == 0 && options->TransPort == 0 &&
3108 options->NatdPort == 0 && options->ORPort == 0 &&
3109 options->DNSPort == 0 && !options->RendConfigLines)
3110 log(LOG_WARN, LD_CONFIG,
3111 "SocksPort, TransPort, NatdPort, DNSPort, and ORPort are all "
3112 "undefined, and there aren't any hidden services configured. "
3113 "Tor will still run, but probably won't do anything.");
3115 if (options->ControlPort < 0 || options->ControlPort > 65535)
3116 REJECT("ControlPort option out of bounds.");
3118 if (options->DirPort < 0 || options->DirPort > 65535)
3119 REJECT("DirPort option out of bounds.");
3121 #ifndef USE_TRANSPARENT
3122 if (options->TransPort || options->TransListenAddress)
3123 REJECT("TransPort and TransListenAddress are disabled in this build.");
3124 #endif
3126 if (options->AccountingMax &&
3127 (is_listening_on_low_port(options->ORPort, options->ORListenAddress) ||
3128 is_listening_on_low_port(options->DirPort, options->DirListenAddress)))
3130 log(LOG_WARN, LD_CONFIG,
3131 "You have set AccountingMax to use hibernation. You have also "
3132 "chosen a low DirPort or OrPort. This combination can make Tor stop "
3133 "working when it tries to re-attach the port after a period of "
3134 "hibernation. Please choose a different port or turn off "
3135 "hibernation unless you know this combination will work on your "
3136 "platform.");
3139 if (options->ExcludeExitNodes || options->ExcludeNodes) {
3140 options->_ExcludeExitNodesUnion = routerset_new();
3141 routerset_union(options->_ExcludeExitNodesUnion,options->ExcludeExitNodes);
3142 routerset_union(options->_ExcludeExitNodesUnion,options->ExcludeNodes);
3145 if (options->StrictExitNodes &&
3146 (!options->ExitNodes) &&
3147 (!old_options ||
3148 (old_options->StrictExitNodes != options->StrictExitNodes) ||
3149 (!routerset_equal(old_options->ExitNodes,options->ExitNodes))))
3150 COMPLAIN("StrictExitNodes set, but no ExitNodes listed.");
3152 if (options->StrictEntryNodes &&
3153 (!options->EntryNodes) &&
3154 (!old_options ||
3155 (old_options->StrictEntryNodes != options->StrictEntryNodes) ||
3156 (!routerset_equal(old_options->EntryNodes,options->EntryNodes))))
3157 COMPLAIN("StrictEntryNodes set, but no EntryNodes listed.");
3159 if (options->EntryNodes && !routerset_is_list(options->EntryNodes)) {
3160 /* XXXX fix this; see entry_guards_prepend_from_config(). */
3161 REJECT("IPs or countries are not yet supported in EntryNodes.");
3164 if (options->AuthoritativeDir) {
3165 if (!options->ContactInfo && !options->TestingTorNetwork)
3166 REJECT("Authoritative directory servers must set ContactInfo");
3167 if (options->V1AuthoritativeDir && !options->RecommendedVersions)
3168 REJECT("V1 authoritative dir servers must set RecommendedVersions.");
3169 if (!options->RecommendedClientVersions)
3170 options->RecommendedClientVersions =
3171 config_lines_dup(options->RecommendedVersions);
3172 if (!options->RecommendedServerVersions)
3173 options->RecommendedServerVersions =
3174 config_lines_dup(options->RecommendedVersions);
3175 if (options->VersioningAuthoritativeDir &&
3176 (!options->RecommendedClientVersions ||
3177 !options->RecommendedServerVersions))
3178 REJECT("Versioning authoritative dir servers must set "
3179 "Recommended*Versions.");
3180 if (options->UseEntryGuards) {
3181 log_info(LD_CONFIG, "Authoritative directory servers can't set "
3182 "UseEntryGuards. Disabling.");
3183 options->UseEntryGuards = 0;
3185 if (!options->DownloadExtraInfo && authdir_mode_any_main(options)) {
3186 log_info(LD_CONFIG, "Authoritative directories always try to download "
3187 "extra-info documents. Setting DownloadExtraInfo.");
3188 options->DownloadExtraInfo = 1;
3190 if (!(options->BridgeAuthoritativeDir || options->HSAuthoritativeDir ||
3191 options->V1AuthoritativeDir || options->V2AuthoritativeDir ||
3192 options->V3AuthoritativeDir))
3193 REJECT("AuthoritativeDir is set, but none of "
3194 "(Bridge/HS/V1/V2/V3)AuthoritativeDir is set.");
3197 if (options->AuthoritativeDir && !options->DirPort)
3198 REJECT("Running as authoritative directory, but no DirPort set.");
3200 if (options->AuthoritativeDir && !options->ORPort)
3201 REJECT("Running as authoritative directory, but no ORPort set.");
3203 if (options->AuthoritativeDir && options->ClientOnly)
3204 REJECT("Running as authoritative directory, but ClientOnly also set.");
3206 if (options->HSAuthorityRecordStats && !options->HSAuthoritativeDir)
3207 REJECT("HSAuthorityRecordStats is set but we're not running as "
3208 "a hidden service authority.");
3210 if (options->FetchDirInfoExtraEarly && !options->FetchDirInfoEarly)
3211 REJECT("FetchDirInfoExtraEarly requires that you also set "
3212 "FetchDirInfoEarly");
3214 if (options->ConnLimit <= 0) {
3215 r = tor_snprintf(buf, sizeof(buf),
3216 "ConnLimit must be greater than 0, but was set to %d",
3217 options->ConnLimit);
3218 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3219 return -1;
3222 if (validate_ports_csv(options->FirewallPorts, "FirewallPorts", msg) < 0)
3223 return -1;
3225 if (validate_ports_csv(options->LongLivedPorts, "LongLivedPorts", msg) < 0)
3226 return -1;
3228 if (validate_ports_csv(options->RejectPlaintextPorts,
3229 "RejectPlaintextPorts", msg) < 0)
3230 return -1;
3232 if (validate_ports_csv(options->WarnPlaintextPorts,
3233 "WarnPlaintextPorts", msg) < 0)
3234 return -1;
3236 if (options->FascistFirewall && !options->ReachableAddresses) {
3237 if (options->FirewallPorts && smartlist_len(options->FirewallPorts)) {
3238 /* We already have firewall ports set, so migrate them to
3239 * ReachableAddresses, which will set ReachableORAddresses and
3240 * ReachableDirAddresses if they aren't set explicitly. */
3241 smartlist_t *instead = smartlist_create();
3242 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3243 new_line->key = tor_strdup("ReachableAddresses");
3244 /* If we're configured with the old format, we need to prepend some
3245 * open ports. */
3246 SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
3248 int p = atoi(portno);
3249 char *s;
3250 if (p<0) continue;
3251 s = tor_malloc(16);
3252 tor_snprintf(s, 16, "*:%d", p);
3253 smartlist_add(instead, s);
3255 new_line->value = smartlist_join_strings(instead,",",0,NULL);
3256 /* These have been deprecated since 0.1.1.5-alpha-cvs */
3257 log(LOG_NOTICE, LD_CONFIG,
3258 "Converting FascistFirewall and FirewallPorts "
3259 "config options to new format: \"ReachableAddresses %s\"",
3260 new_line->value);
3261 options->ReachableAddresses = new_line;
3262 SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
3263 smartlist_free(instead);
3264 } else {
3265 /* We do not have FirewallPorts set, so add 80 to
3266 * ReachableDirAddresses, and 443 to ReachableORAddresses. */
3267 if (!options->ReachableDirAddresses) {
3268 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3269 new_line->key = tor_strdup("ReachableDirAddresses");
3270 new_line->value = tor_strdup("*:80");
3271 options->ReachableDirAddresses = new_line;
3272 log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
3273 "to new format: \"ReachableDirAddresses *:80\"");
3275 if (!options->ReachableORAddresses) {
3276 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3277 new_line->key = tor_strdup("ReachableORAddresses");
3278 new_line->value = tor_strdup("*:443");
3279 options->ReachableORAddresses = new_line;
3280 log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
3281 "to new format: \"ReachableORAddresses *:443\"");
3286 for (i=0; i<3; i++) {
3287 config_line_t **linep =
3288 (i==0) ? &options->ReachableAddresses :
3289 (i==1) ? &options->ReachableORAddresses :
3290 &options->ReachableDirAddresses;
3291 if (!*linep)
3292 continue;
3293 /* We need to end with a reject *:*, not an implicit accept *:* */
3294 for (;;) {
3295 if (!strcmp((*linep)->value, "reject *:*")) /* already there */
3296 break;
3297 linep = &((*linep)->next);
3298 if (!*linep) {
3299 *linep = tor_malloc_zero(sizeof(config_line_t));
3300 (*linep)->key = tor_strdup(
3301 (i==0) ? "ReachableAddresses" :
3302 (i==1) ? "ReachableORAddresses" :
3303 "ReachableDirAddresses");
3304 (*linep)->value = tor_strdup("reject *:*");
3305 break;
3310 if ((options->ReachableAddresses ||
3311 options->ReachableORAddresses ||
3312 options->ReachableDirAddresses) &&
3313 server_mode(options))
3314 REJECT("Servers must be able to freely connect to the rest "
3315 "of the Internet, so they must not set Reachable*Addresses "
3316 "or FascistFirewall.");
3318 if (options->UseBridges &&
3319 server_mode(options))
3320 REJECT("Servers must be able to freely connect to the rest "
3321 "of the Internet, so they must not set UseBridges.");
3323 options->_AllowInvalid = 0;
3324 if (options->AllowInvalidNodes) {
3325 SMARTLIST_FOREACH(options->AllowInvalidNodes, const char *, cp, {
3326 if (!strcasecmp(cp, "entry"))
3327 options->_AllowInvalid |= ALLOW_INVALID_ENTRY;
3328 else if (!strcasecmp(cp, "exit"))
3329 options->_AllowInvalid |= ALLOW_INVALID_EXIT;
3330 else if (!strcasecmp(cp, "middle"))
3331 options->_AllowInvalid |= ALLOW_INVALID_MIDDLE;
3332 else if (!strcasecmp(cp, "introduction"))
3333 options->_AllowInvalid |= ALLOW_INVALID_INTRODUCTION;
3334 else if (!strcasecmp(cp, "rendezvous"))
3335 options->_AllowInvalid |= ALLOW_INVALID_RENDEZVOUS;
3336 else {
3337 r = tor_snprintf(buf, sizeof(buf),
3338 "Unrecognized value '%s' in AllowInvalidNodes", cp);
3339 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3340 return -1;
3345 if (compute_publishserverdescriptor(options) < 0) {
3346 r = tor_snprintf(buf, sizeof(buf),
3347 "Unrecognized value in PublishServerDescriptor");
3348 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3349 return -1;
3352 if ((options->BridgeRelay
3353 || options->_PublishServerDescriptor & BRIDGE_AUTHORITY)
3354 && (options->_PublishServerDescriptor
3355 & (V1_AUTHORITY|V2_AUTHORITY|V3_AUTHORITY))) {
3356 REJECT("Bridges are not supposed to publish router descriptors to the "
3357 "directory authorities. Please correct your "
3358 "PublishServerDescriptor line.");
3361 if (options->MinUptimeHidServDirectoryV2 < 0) {
3362 log_warn(LD_CONFIG, "MinUptimeHidServDirectoryV2 option must be at "
3363 "least 0 seconds. Changing to 0.");
3364 options->MinUptimeHidServDirectoryV2 = 0;
3367 if (options->RendPostPeriod < MIN_REND_POST_PERIOD) {
3368 log(LOG_WARN,LD_CONFIG,"RendPostPeriod option is too short; "
3369 "raising to %d seconds.", MIN_REND_POST_PERIOD);
3370 options->RendPostPeriod = MIN_REND_POST_PERIOD;
3373 if (options->RendPostPeriod > MAX_DIR_PERIOD) {
3374 log(LOG_WARN, LD_CONFIG, "RendPostPeriod is too large; clipping to %ds.",
3375 MAX_DIR_PERIOD);
3376 options->RendPostPeriod = MAX_DIR_PERIOD;
3379 if (options->CircuitBuildTimeout < MIN_CIRCUIT_BUILD_TIMEOUT) {
3380 log(LOG_WARN, LD_CONFIG, "CircuitBuildTimeout option is too short; "
3381 "raising to %d seconds.", MIN_CIRCUIT_BUILD_TIMEOUT);
3382 options->CircuitBuildTimeout = MIN_CIRCUIT_BUILD_TIMEOUT;
3385 if (options->MaxCircuitDirtiness < MIN_MAX_CIRCUIT_DIRTINESS) {
3386 log(LOG_WARN, LD_CONFIG, "MaxCircuitDirtiness option is too short; "
3387 "raising to %d seconds.", MIN_MAX_CIRCUIT_DIRTINESS);
3388 options->MaxCircuitDirtiness = MIN_MAX_CIRCUIT_DIRTINESS;
3391 if (options->KeepalivePeriod < 1)
3392 REJECT("KeepalivePeriod option must be positive.");
3394 if (ensure_bandwidth_cap(&options->BandwidthRate,
3395 "BandwidthRate", msg) < 0)
3396 return -1;
3397 if (ensure_bandwidth_cap(&options->BandwidthBurst,
3398 "BandwidthBurst", msg) < 0)
3399 return -1;
3400 if (ensure_bandwidth_cap(&options->MaxAdvertisedBandwidth,
3401 "MaxAdvertisedBandwidth", msg) < 0)
3402 return -1;
3403 if (ensure_bandwidth_cap(&options->RelayBandwidthRate,
3404 "RelayBandwidthRate", msg) < 0)
3405 return -1;
3406 if (ensure_bandwidth_cap(&options->RelayBandwidthBurst,
3407 "RelayBandwidthBurst", msg) < 0)
3408 return -1;
3410 if (server_mode(options)) {
3411 if (options->BandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
3412 r = tor_snprintf(buf, sizeof(buf),
3413 "BandwidthRate is set to %d bytes/second. "
3414 "For servers, it must be at least %d.",
3415 (int)options->BandwidthRate,
3416 ROUTER_REQUIRED_MIN_BANDWIDTH);
3417 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3418 return -1;
3419 } else if (options->MaxAdvertisedBandwidth <
3420 ROUTER_REQUIRED_MIN_BANDWIDTH/2) {
3421 r = tor_snprintf(buf, sizeof(buf),
3422 "MaxAdvertisedBandwidth is set to %d bytes/second. "
3423 "For servers, it must be at least %d.",
3424 (int)options->MaxAdvertisedBandwidth,
3425 ROUTER_REQUIRED_MIN_BANDWIDTH/2);
3426 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3427 return -1;
3429 if (options->RelayBandwidthRate &&
3430 options->RelayBandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
3431 r = tor_snprintf(buf, sizeof(buf),
3432 "RelayBandwidthRate is set to %d bytes/second. "
3433 "For servers, it must be at least %d.",
3434 (int)options->RelayBandwidthRate,
3435 ROUTER_REQUIRED_MIN_BANDWIDTH);
3436 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3437 return -1;
3441 if (options->RelayBandwidthRate && !options->RelayBandwidthBurst)
3442 options->RelayBandwidthBurst = options->RelayBandwidthRate;
3444 if (options->RelayBandwidthRate > options->RelayBandwidthBurst)
3445 REJECT("RelayBandwidthBurst must be at least equal "
3446 "to RelayBandwidthRate.");
3448 if (options->BandwidthRate > options->BandwidthBurst)
3449 REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
3451 /* if they set relaybandwidth* really high but left bandwidth*
3452 * at the default, raise the defaults. */
3453 if (options->RelayBandwidthRate > options->BandwidthRate)
3454 options->BandwidthRate = options->RelayBandwidthRate;
3455 if (options->RelayBandwidthBurst > options->BandwidthBurst)
3456 options->BandwidthBurst = options->RelayBandwidthBurst;
3458 if (accounting_parse_options(options, 1)<0)
3459 REJECT("Failed to parse accounting options. See logs for details.");
3461 if (options->HttpProxy) { /* parse it now */
3462 if (parse_addr_port(LOG_WARN, options->HttpProxy, NULL,
3463 &options->HttpProxyAddr, &options->HttpProxyPort) < 0)
3464 REJECT("HttpProxy failed to parse or resolve. Please fix.");
3465 if (options->HttpProxyPort == 0) { /* give it a default */
3466 options->HttpProxyPort = 80;
3470 if (options->HttpProxyAuthenticator) {
3471 if (strlen(options->HttpProxyAuthenticator) >= 48)
3472 REJECT("HttpProxyAuthenticator is too long (>= 48 chars).");
3475 if (options->HttpsProxy) { /* parse it now */
3476 if (parse_addr_port(LOG_WARN, options->HttpsProxy, NULL,
3477 &options->HttpsProxyAddr, &options->HttpsProxyPort) <0)
3478 REJECT("HttpsProxy failed to parse or resolve. Please fix.");
3479 if (options->HttpsProxyPort == 0) { /* give it a default */
3480 options->HttpsProxyPort = 443;
3484 if (options->HttpsProxyAuthenticator) {
3485 if (strlen(options->HttpsProxyAuthenticator) >= 48)
3486 REJECT("HttpsProxyAuthenticator is too long (>= 48 chars).");
3489 if (options->HashedControlPassword) {
3490 smartlist_t *sl = decode_hashed_passwords(options->HashedControlPassword);
3491 if (!sl) {
3492 REJECT("Bad HashedControlPassword: wrong length or bad encoding");
3493 } else {
3494 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3495 smartlist_free(sl);
3499 if (options->HashedControlSessionPassword) {
3500 smartlist_t *sl = decode_hashed_passwords(
3501 options->HashedControlSessionPassword);
3502 if (!sl) {
3503 REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
3504 } else {
3505 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3506 smartlist_free(sl);
3510 if (options->ControlListenAddress) {
3511 int all_are_local = 1;
3512 config_line_t *ln;
3513 for (ln = options->ControlListenAddress; ln; ln = ln->next) {
3514 if (strcmpstart(ln->value, "127."))
3515 all_are_local = 0;
3517 if (!all_are_local) {
3518 if (!options->HashedControlPassword &&
3519 !options->HashedControlSessionPassword &&
3520 !options->CookieAuthentication) {
3521 log_warn(LD_CONFIG,
3522 "You have a ControlListenAddress set to accept "
3523 "unauthenticated connections from a non-local address. "
3524 "This means that programs not running on your computer "
3525 "can reconfigure your Tor, without even having to guess a "
3526 "password. That's so bad that I'm closing your ControlPort "
3527 "for you. If you need to control your Tor remotely, try "
3528 "enabling authentication and using a tool like stunnel or "
3529 "ssh to encrypt remote access.");
3530 options->ControlPort = 0;
3531 } else {
3532 log_warn(LD_CONFIG, "You have a ControlListenAddress set to accept "
3533 "connections from a non-local address. This means that "
3534 "programs not running on your computer can reconfigure your "
3535 "Tor. That's pretty bad, since the controller "
3536 "protocol isn't encrypted! Maybe you should just listen on "
3537 "127.0.0.1 and use a tool like stunnel or ssh to encrypt "
3538 "remote connections to your control port.");
3543 if (options->ControlPort && !options->HashedControlPassword &&
3544 !options->HashedControlSessionPassword &&
3545 !options->CookieAuthentication) {
3546 log_warn(LD_CONFIG, "ControlPort is open, but no authentication method "
3547 "has been configured. This means that any program on your "
3548 "computer can reconfigure your Tor. That's bad! You should "
3549 "upgrade your Tor controller as soon as possible.");
3552 if (options->UseEntryGuards && ! options->NumEntryGuards)
3553 REJECT("Cannot enable UseEntryGuards with NumEntryGuards set to 0");
3555 if (check_nickname_list(options->MyFamily, "MyFamily", msg))
3556 return -1;
3557 for (cl = options->NodeFamilies; cl; cl = cl->next) {
3558 if (check_nickname_list(cl->value, "NodeFamily", msg))
3559 return -1;
3562 if (validate_addr_policies(options, msg) < 0)
3563 return -1;
3565 if (validate_dir_authorities(options, old_options) < 0)
3566 REJECT("Directory authority line did not parse. See logs for details.");
3568 if (options->UseBridges && !options->Bridges)
3569 REJECT("If you set UseBridges, you must specify at least one bridge.");
3570 if (options->UseBridges && !options->TunnelDirConns)
3571 REJECT("If you set UseBridges, you must set TunnelDirConns.");
3572 if (options->Bridges) {
3573 for (cl = options->Bridges; cl; cl = cl->next) {
3574 if (parse_bridge_line(cl->value, 1)<0)
3575 REJECT("Bridge line did not parse. See logs for details.");
3579 if (options->ConstrainedSockets) {
3580 /* If the user wants to constrain socket buffer use, make sure the desired
3581 * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
3582 if (options->ConstrainedSockSize < MIN_CONSTRAINED_TCP_BUFFER ||
3583 options->ConstrainedSockSize > MAX_CONSTRAINED_TCP_BUFFER ||
3584 options->ConstrainedSockSize % 1024) {
3585 r = tor_snprintf(buf, sizeof(buf),
3586 "ConstrainedSockSize is invalid. Must be a value between %d and %d "
3587 "in 1024 byte increments.",
3588 MIN_CONSTRAINED_TCP_BUFFER, MAX_CONSTRAINED_TCP_BUFFER);
3589 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3590 return -1;
3592 if (options->DirPort) {
3593 /* Providing cached directory entries while system TCP buffers are scarce
3594 * will exacerbate the socket errors. Suggest that this be disabled. */
3595 COMPLAIN("You have requested constrained socket buffers while also "
3596 "serving directory entries via DirPort. It is strongly "
3597 "suggested that you disable serving directory requests when "
3598 "system TCP buffer resources are scarce.");
3602 if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
3603 options->V3AuthVotingInterval/2) {
3604 REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
3605 "V3AuthVotingInterval");
3607 if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS)
3608 REJECT("V3AuthVoteDelay is way too low.");
3609 if (options->V3AuthDistDelay < MIN_DIST_SECONDS)
3610 REJECT("V3AuthDistDelay is way too low.");
3612 if (options->V3AuthNIntervalsValid < 2)
3613 REJECT("V3AuthNIntervalsValid must be at least 2.");
3615 if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL) {
3616 REJECT("V3AuthVotingInterval is insanely low.");
3617 } else if (options->V3AuthVotingInterval > 24*60*60) {
3618 REJECT("V3AuthVotingInterval is insanely high.");
3619 } else if (((24*60*60) % options->V3AuthVotingInterval) != 0) {
3620 COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
3623 if (rend_config_services(options, 1) < 0)
3624 REJECT("Failed to configure rendezvous options. See logs for details.");
3626 /* Parse client-side authorization for hidden services. */
3627 if (rend_parse_service_authorization(options, 1) < 0)
3628 REJECT("Failed to configure client authorization for hidden services. "
3629 "See logs for details.");
3631 if (parse_virtual_addr_network(options->VirtualAddrNetwork, 1, NULL)<0)
3632 return -1;
3634 if (options->PreferTunneledDirConns && !options->TunnelDirConns)
3635 REJECT("Must set TunnelDirConns if PreferTunneledDirConns is set.");
3637 if (options->AutomapHostsSuffixes) {
3638 SMARTLIST_FOREACH(options->AutomapHostsSuffixes, char *, suf,
3640 size_t len = strlen(suf);
3641 if (len && suf[len-1] == '.')
3642 suf[len-1] = '\0';
3646 if (options->TestingTorNetwork && !options->DirServers) {
3647 REJECT("TestingTorNetwork may only be configured in combination with "
3648 "a non-default set of DirServers.");
3651 /*XXXX022 checking for defaults manually like this is a bit fragile.*/
3653 /* Keep changes to hard-coded values synchronous to man page and default
3654 * values table. */
3655 if (options->TestingV3AuthInitialVotingInterval != 30*60 &&
3656 !options->TestingTorNetwork) {
3657 REJECT("TestingV3AuthInitialVotingInterval may only be changed in testing "
3658 "Tor networks!");
3659 } else if (options->TestingV3AuthInitialVotingInterval < MIN_VOTE_INTERVAL) {
3660 REJECT("TestingV3AuthInitialVotingInterval is insanely low.");
3661 } else if (((30*60) % options->TestingV3AuthInitialVotingInterval) != 0) {
3662 REJECT("TestingV3AuthInitialVotingInterval does not divide evenly into "
3663 "30 minutes.");
3666 if (options->TestingV3AuthInitialVoteDelay != 5*60 &&
3667 !options->TestingTorNetwork) {
3668 REJECT("TestingV3AuthInitialVoteDelay may only be changed in testing "
3669 "Tor networks!");
3670 } else if (options->TestingV3AuthInitialVoteDelay < MIN_VOTE_SECONDS) {
3671 REJECT("TestingV3AuthInitialVoteDelay is way too low.");
3674 if (options->TestingV3AuthInitialDistDelay != 5*60 &&
3675 !options->TestingTorNetwork) {
3676 REJECT("TestingV3AuthInitialDistDelay may only be changed in testing "
3677 "Tor networks!");
3678 } else if (options->TestingV3AuthInitialDistDelay < MIN_DIST_SECONDS) {
3679 REJECT("TestingV3AuthInitialDistDelay is way too low.");
3682 if (options->TestingV3AuthInitialVoteDelay +
3683 options->TestingV3AuthInitialDistDelay >=
3684 options->TestingV3AuthInitialVotingInterval/2) {
3685 REJECT("TestingV3AuthInitialVoteDelay plus TestingV3AuthInitialDistDelay "
3686 "must be less than half TestingV3AuthInitialVotingInterval");
3689 if (options->TestingAuthDirTimeToLearnReachability != 30*60 &&
3690 !options->TestingTorNetwork) {
3691 REJECT("TestingAuthDirTimeToLearnReachability may only be changed in "
3692 "testing Tor networks!");
3693 } else if (options->TestingAuthDirTimeToLearnReachability < 0) {
3694 REJECT("TestingAuthDirTimeToLearnReachability must be non-negative.");
3695 } else if (options->TestingAuthDirTimeToLearnReachability > 2*60*60) {
3696 COMPLAIN("TestingAuthDirTimeToLearnReachability is insanely high.");
3699 if (options->TestingEstimatedDescriptorPropagationTime != 10*60 &&
3700 !options->TestingTorNetwork) {
3701 REJECT("TestingEstimatedDescriptorPropagationTime may only be changed in "
3702 "testing Tor networks!");
3703 } else if (options->TestingEstimatedDescriptorPropagationTime < 0) {
3704 REJECT("TestingEstimatedDescriptorPropagationTime must be non-negative.");
3705 } else if (options->TestingEstimatedDescriptorPropagationTime > 60*60) {
3706 COMPLAIN("TestingEstimatedDescriptorPropagationTime is insanely high.");
3709 if (options->TestingTorNetwork) {
3710 log_warn(LD_CONFIG, "TestingTorNetwork is set. This will make your node "
3711 "almost unusable in the public Tor network, and is "
3712 "therefore only advised if you are building a "
3713 "testing Tor network!");
3716 if (options->AccelName && !options->HardwareAccel)
3717 options->HardwareAccel = 1;
3718 if (options->AccelDir && !options->AccelName)
3719 REJECT("Can't use hardware crypto accelerator dir without engine name.");
3721 return 0;
3722 #undef REJECT
3723 #undef COMPLAIN
3726 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
3727 * equal strings. */
3728 static int
3729 opt_streq(const char *s1, const char *s2)
3731 if (!s1 && !s2)
3732 return 1;
3733 else if (s1 && s2 && !strcmp(s1,s2))
3734 return 1;
3735 else
3736 return 0;
3739 /** Check if any of the previous options have changed but aren't allowed to. */
3740 static int
3741 options_transition_allowed(or_options_t *old, or_options_t *new_val,
3742 char **msg)
3744 if (!old)
3745 return 0;
3747 if (!opt_streq(old->PidFile, new_val->PidFile)) {
3748 *msg = tor_strdup("PidFile is not allowed to change.");
3749 return -1;
3752 if (old->RunAsDaemon != new_val->RunAsDaemon) {
3753 *msg = tor_strdup("While Tor is running, changing RunAsDaemon "
3754 "is not allowed.");
3755 return -1;
3758 if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
3759 char buf[1024];
3760 int r = tor_snprintf(buf, sizeof(buf),
3761 "While Tor is running, changing DataDirectory "
3762 "(\"%s\"->\"%s\") is not allowed.",
3763 old->DataDirectory, new_val->DataDirectory);
3764 *msg = tor_strdup(r >= 0 ? buf : "internal error");
3765 return -1;
3768 if (!opt_streq(old->User, new_val->User)) {
3769 *msg = tor_strdup("While Tor is running, changing User is not allowed.");
3770 return -1;
3773 if (!opt_streq(old->Group, new_val->Group)) {
3774 *msg = tor_strdup("While Tor is running, changing Group is not allowed.");
3775 return -1;
3778 if ((old->HardwareAccel != new_val->HardwareAccel)
3779 || !opt_streq(old->AccelName, new_val->AccelName)
3780 || !opt_streq(old->AccelDir, new_val->AccelDir)) {
3781 *msg = tor_strdup("While Tor is running, changing OpenSSL hardware "
3782 "acceleration engine is not allowed.");
3783 return -1;
3786 if (old->TestingTorNetwork != new_val->TestingTorNetwork) {
3787 *msg = tor_strdup("While Tor is running, changing TestingTorNetwork "
3788 "is not allowed.");
3789 return -1;
3792 return 0;
3795 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3796 * will require us to rotate the CPU and DNS workers; else return 0. */
3797 static int
3798 options_transition_affects_workers(or_options_t *old_options,
3799 or_options_t *new_options)
3801 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
3802 old_options->NumCpus != new_options->NumCpus ||
3803 old_options->ORPort != new_options->ORPort ||
3804 old_options->ServerDNSSearchDomains !=
3805 new_options->ServerDNSSearchDomains ||
3806 old_options->SafeLogging != new_options->SafeLogging ||
3807 old_options->ClientOnly != new_options->ClientOnly ||
3808 !config_lines_eq(old_options->Logs, new_options->Logs))
3809 return 1;
3811 /* Check whether log options match. */
3813 /* Nothing that changed matters. */
3814 return 0;
3817 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3818 * will require us to generate a new descriptor; else return 0. */
3819 static int
3820 options_transition_affects_descriptor(or_options_t *old_options,
3821 or_options_t *new_options)
3823 /* XXX We can be smarter here. If your DirPort isn't being
3824 * published and you just turned it off, no need to republish. Etc. */
3825 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
3826 !opt_streq(old_options->Nickname,new_options->Nickname) ||
3827 !opt_streq(old_options->Address,new_options->Address) ||
3828 !config_lines_eq(old_options->ExitPolicy,new_options->ExitPolicy) ||
3829 old_options->ExitPolicyRejectPrivate !=
3830 new_options->ExitPolicyRejectPrivate ||
3831 old_options->ORPort != new_options->ORPort ||
3832 old_options->DirPort != new_options->DirPort ||
3833 old_options->ClientOnly != new_options->ClientOnly ||
3834 old_options->NoPublish != new_options->NoPublish ||
3835 old_options->_PublishServerDescriptor !=
3836 new_options->_PublishServerDescriptor ||
3837 get_effective_bwrate(old_options) != get_effective_bwrate(new_options) ||
3838 get_effective_bwburst(old_options) !=
3839 get_effective_bwburst(new_options) ||
3840 !opt_streq(old_options->ContactInfo, new_options->ContactInfo) ||
3841 !opt_streq(old_options->MyFamily, new_options->MyFamily) ||
3842 !opt_streq(old_options->AccountingStart, new_options->AccountingStart) ||
3843 old_options->AccountingMax != new_options->AccountingMax)
3844 return 1;
3846 return 0;
3849 #ifdef MS_WINDOWS
3850 /** Return the directory on windows where we expect to find our application
3851 * data. */
3852 static char *
3853 get_windows_conf_root(void)
3855 static int is_set = 0;
3856 static char path[MAX_PATH+1];
3858 LPITEMIDLIST idl;
3859 IMalloc *m;
3860 HRESULT result;
3862 if (is_set)
3863 return path;
3865 /* Find X:\documents and settings\username\application data\ .
3866 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
3868 #ifdef ENABLE_LOCAL_APPDATA
3869 #define APPDATA_PATH CSIDL_LOCAL_APPDATA
3870 #else
3871 #define APPDATA_PATH CSIDL_APPDATA
3872 #endif
3873 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, APPDATA_PATH, &idl))) {
3874 GetCurrentDirectory(MAX_PATH, path);
3875 is_set = 1;
3876 log_warn(LD_CONFIG,
3877 "I couldn't find your application data folder: are you "
3878 "running an ancient version of Windows 95? Defaulting to \"%s\"",
3879 path);
3880 return path;
3882 /* Convert the path from an "ID List" (whatever that is!) to a path. */
3883 result = SHGetPathFromIDList(idl, path);
3884 /* Now we need to free the */
3885 SHGetMalloc(&m);
3886 if (m) {
3887 m->lpVtbl->Free(m, idl);
3888 m->lpVtbl->Release(m);
3890 if (!SUCCEEDED(result)) {
3891 return NULL;
3893 strlcat(path,"\\tor",MAX_PATH);
3894 is_set = 1;
3895 return path;
3897 #endif
3899 /** Return the default location for our torrc file. */
3900 static const char *
3901 get_default_conf_file(void)
3903 #ifdef MS_WINDOWS
3904 static char path[MAX_PATH+1];
3905 strlcpy(path, get_windows_conf_root(), MAX_PATH);
3906 strlcat(path,"\\torrc",MAX_PATH);
3907 return path;
3908 #else
3909 return (CONFDIR "/torrc");
3910 #endif
3913 /** Verify whether lst is a string containing valid-looking comma-separated
3914 * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
3916 static int
3917 check_nickname_list(const char *lst, const char *name, char **msg)
3919 int r = 0;
3920 smartlist_t *sl;
3922 if (!lst)
3923 return 0;
3924 sl = smartlist_create();
3926 smartlist_split_string(sl, lst, ",",
3927 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK|SPLIT_STRIP_SPACE, 0);
3929 SMARTLIST_FOREACH(sl, const char *, s,
3931 if (!is_legal_nickname_or_hexdigest(s)) {
3932 char buf[1024];
3933 int tmp = tor_snprintf(buf, sizeof(buf),
3934 "Invalid nickname '%s' in %s line", s, name);
3935 *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
3936 r = -1;
3937 break;
3940 SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
3941 smartlist_free(sl);
3942 return r;
3945 /** Learn config file name from command line arguments, or use the default */
3946 static char *
3947 find_torrc_filename(int argc, char **argv,
3948 int *using_default_torrc, int *ignore_missing_torrc)
3950 char *fname=NULL;
3951 int i;
3953 for (i = 1; i < argc; ++i) {
3954 if (i < argc-1 && !strcmp(argv[i],"-f")) {
3955 if (fname) {
3956 log(LOG_WARN, LD_CONFIG, "Duplicate -f options on command line.");
3957 tor_free(fname);
3959 #ifdef MS_WINDOWS
3960 /* XXX one day we might want to extend expand_filename to work
3961 * under Windows as well. */
3962 fname = tor_strdup(argv[i+1]);
3963 #else
3964 fname = expand_filename(argv[i+1]);
3965 #endif
3966 *using_default_torrc = 0;
3967 ++i;
3968 } else if (!strcmp(argv[i],"--ignore-missing-torrc")) {
3969 *ignore_missing_torrc = 1;
3973 if (*using_default_torrc) {
3974 /* didn't find one, try CONFDIR */
3975 const char *dflt = get_default_conf_file();
3976 if (dflt && file_status(dflt) == FN_FILE) {
3977 fname = tor_strdup(dflt);
3978 } else {
3979 #ifndef MS_WINDOWS
3980 char *fn;
3981 fn = expand_filename("~/.torrc");
3982 if (fn && file_status(fn) == FN_FILE) {
3983 fname = fn;
3984 } else {
3985 tor_free(fn);
3986 fname = tor_strdup(dflt);
3988 #else
3989 fname = tor_strdup(dflt);
3990 #endif
3993 return fname;
3996 /** Load torrc from disk, setting torrc_fname if successful */
3997 static char *
3998 load_torrc_from_disk(int argc, char **argv)
4000 char *fname=NULL;
4001 char *cf = NULL;
4002 int using_default_torrc = 1;
4003 int ignore_missing_torrc = 0;
4005 fname = find_torrc_filename(argc, argv,
4006 &using_default_torrc, &ignore_missing_torrc);
4007 tor_assert(fname);
4008 log(LOG_DEBUG, LD_CONFIG, "Opening config file \"%s\"", fname);
4010 tor_free(torrc_fname);
4011 torrc_fname = fname;
4013 /* Open config file */
4014 if (file_status(fname) != FN_FILE ||
4015 !(cf = read_file_to_str(fname,0,NULL))) {
4016 if (using_default_torrc == 1 || ignore_missing_torrc ) {
4017 log(LOG_NOTICE, LD_CONFIG, "Configuration file \"%s\" not present, "
4018 "using reasonable defaults.", fname);
4019 tor_free(fname); /* sets fname to NULL */
4020 torrc_fname = NULL;
4021 cf = tor_strdup("");
4022 } else {
4023 log(LOG_WARN, LD_CONFIG,
4024 "Unable to open configuration file \"%s\".", fname);
4025 goto err;
4029 return cf;
4030 err:
4031 tor_free(fname);
4032 torrc_fname = NULL;
4033 return NULL;
4036 /** Read a configuration file into <b>options</b>, finding the configuration
4037 * file location based on the command line. After loading the file
4038 * call options_init_from_string() to load the config.
4039 * Return 0 if success, -1 if failure. */
4041 options_init_from_torrc(int argc, char **argv)
4043 char *cf=NULL;
4044 int i, retval, command;
4045 static char **backup_argv;
4046 static int backup_argc;
4047 char *command_arg = NULL;
4048 char *errmsg=NULL;
4050 if (argv) { /* first time we're called. save command line args */
4051 backup_argv = argv;
4052 backup_argc = argc;
4053 } else { /* we're reloading. need to clean up old options first. */
4054 argv = backup_argv;
4055 argc = backup_argc;
4057 if (argc > 1 && (!strcmp(argv[1], "-h") || !strcmp(argv[1],"--help"))) {
4058 print_usage();
4059 exit(0);
4061 if (argc > 1 && !strcmp(argv[1], "--list-torrc-options")) {
4062 /* For documenting validating whether we've documented everything. */
4063 list_torrc_options();
4064 exit(0);
4067 if (argc > 1 && (!strcmp(argv[1],"--version"))) {
4068 printf("Tor version %s.\n",get_version());
4069 exit(0);
4071 if (argc > 1 && (!strcmp(argv[1],"--digests"))) {
4072 printf("Tor version %s.\n",get_version());
4073 printf("%s", libor_get_digests());
4074 printf("%s", tor_get_digests());
4075 exit(0);
4078 /* Go through command-line variables */
4079 if (!global_cmdline_options) {
4080 /* Or we could redo the list every time we pass this place.
4081 * It does not really matter */
4082 if (config_get_commandlines(argc, argv, &global_cmdline_options) < 0) {
4083 goto err;
4087 command = CMD_RUN_TOR;
4088 for (i = 1; i < argc; ++i) {
4089 if (!strcmp(argv[i],"--list-fingerprint")) {
4090 command = CMD_LIST_FINGERPRINT;
4091 } else if (!strcmp(argv[i],"--hash-password")) {
4092 command = CMD_HASH_PASSWORD;
4093 command_arg = tor_strdup( (i < argc-1) ? argv[i+1] : "");
4094 ++i;
4095 } else if (!strcmp(argv[i],"--verify-config")) {
4096 command = CMD_VERIFY_CONFIG;
4100 if (command == CMD_HASH_PASSWORD) {
4101 cf = tor_strdup("");
4102 } else {
4103 cf = load_torrc_from_disk(argc, argv);
4104 if (!cf)
4105 goto err;
4108 retval = options_init_from_string(cf, command, command_arg, &errmsg);
4109 tor_free(cf);
4110 if (retval < 0)
4111 goto err;
4113 return 0;
4115 err:
4116 if (errmsg) {
4117 log(LOG_WARN,LD_CONFIG,"%s", errmsg);
4118 tor_free(errmsg);
4120 return -1;
4123 /** Load the options from the configuration in <b>cf</b>, validate
4124 * them for consistency and take actions based on them.
4126 * Return 0 if success, negative on error:
4127 * * -1 for general errors.
4128 * * -2 for failure to parse/validate,
4129 * * -3 for transition not allowed
4130 * * -4 for error while setting the new options
4132 setopt_err_t
4133 options_init_from_string(const char *cf,
4134 int command, const char *command_arg,
4135 char **msg)
4137 or_options_t *oldoptions, *newoptions;
4138 config_line_t *cl;
4139 int retval;
4140 setopt_err_t err = SETOPT_ERR_MISC;
4141 tor_assert(msg);
4143 oldoptions = global_options; /* get_options unfortunately asserts if
4144 this is the first time we run*/
4146 newoptions = tor_malloc_zero(sizeof(or_options_t));
4147 newoptions->_magic = OR_OPTIONS_MAGIC;
4148 options_init(newoptions);
4149 newoptions->command = command;
4150 newoptions->command_arg = command_arg;
4152 /* get config lines, assign them */
4153 retval = config_get_lines(cf, &cl);
4154 if (retval < 0) {
4155 err = SETOPT_ERR_PARSE;
4156 goto err;
4158 retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
4159 config_free_lines(cl);
4160 if (retval < 0) {
4161 err = SETOPT_ERR_PARSE;
4162 goto err;
4165 /* Go through command-line variables too */
4166 retval = config_assign(&options_format, newoptions,
4167 global_cmdline_options, 0, 0, msg);
4168 if (retval < 0) {
4169 err = SETOPT_ERR_PARSE;
4170 goto err;
4173 /* If this is a testing network configuration, change defaults
4174 * for a list of dependent config options, re-initialize newoptions
4175 * with the new defaults, and assign all options to it second time. */
4176 if (newoptions->TestingTorNetwork) {
4177 /* XXXX this is a bit of a kludge. perhaps there's a better way to do
4178 * this? We could, for example, make the parsing algorithm do two passes
4179 * over the configuration. If it finds any "suite" options like
4180 * TestingTorNetwork, it could change the defaults before its second pass.
4181 * Not urgent so long as this seems to work, but at any sign of trouble,
4182 * let's clean it up. -NM */
4184 /* Change defaults. */
4185 int i;
4186 for (i = 0; testing_tor_network_defaults[i].name; ++i) {
4187 config_var_t *new_var = &testing_tor_network_defaults[i];
4188 config_var_t *old_var =
4189 config_find_option(&options_format, new_var->name);
4190 tor_assert(new_var);
4191 tor_assert(old_var);
4192 old_var->initvalue = new_var->initvalue;
4195 /* Clear newoptions and re-initialize them with new defaults. */
4196 config_free(&options_format, newoptions);
4197 newoptions = tor_malloc_zero(sizeof(or_options_t));
4198 newoptions->_magic = OR_OPTIONS_MAGIC;
4199 options_init(newoptions);
4200 newoptions->command = command;
4201 newoptions->command_arg = command_arg;
4203 /* Assign all options a second time. */
4204 retval = config_get_lines(cf, &cl);
4205 if (retval < 0) {
4206 err = SETOPT_ERR_PARSE;
4207 goto err;
4209 retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
4210 config_free_lines(cl);
4211 if (retval < 0) {
4212 err = SETOPT_ERR_PARSE;
4213 goto err;
4215 retval = config_assign(&options_format, newoptions,
4216 global_cmdline_options, 0, 0, msg);
4217 if (retval < 0) {
4218 err = SETOPT_ERR_PARSE;
4219 goto err;
4223 /* Validate newoptions */
4224 if (options_validate(oldoptions, newoptions, 0, msg) < 0) {
4225 err = SETOPT_ERR_PARSE; /*XXX make this a separate return value.*/
4226 goto err;
4229 if (options_transition_allowed(oldoptions, newoptions, msg) < 0) {
4230 err = SETOPT_ERR_TRANSITION;
4231 goto err;
4234 if (set_options(newoptions, msg)) {
4235 err = SETOPT_ERR_SETTING;
4236 goto err; /* frees and replaces old options */
4239 return SETOPT_OK;
4241 err:
4242 config_free(&options_format, newoptions);
4243 if (*msg) {
4244 int len = strlen(*msg)+256;
4245 char *newmsg = tor_malloc(len);
4247 tor_snprintf(newmsg, len, "Failed to parse/validate config: %s", *msg);
4248 tor_free(*msg);
4249 *msg = newmsg;
4251 return err;
4254 /** Return the location for our configuration file.
4256 const char *
4257 get_torrc_fname(void)
4259 if (torrc_fname)
4260 return torrc_fname;
4261 else
4262 return get_default_conf_file();
4265 /** Adjust the address map based on the MapAddress elements in the
4266 * configuration <b>options</b>
4268 static void
4269 config_register_addressmaps(or_options_t *options)
4271 smartlist_t *elts;
4272 config_line_t *opt;
4273 char *from, *to;
4275 addressmap_clear_configured();
4276 elts = smartlist_create();
4277 for (opt = options->AddressMap; opt; opt = opt->next) {
4278 smartlist_split_string(elts, opt->value, NULL,
4279 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
4280 if (smartlist_len(elts) >= 2) {
4281 from = smartlist_get(elts,0);
4282 to = smartlist_get(elts,1);
4283 if (address_is_invalid_destination(to, 1)) {
4284 log_warn(LD_CONFIG,
4285 "Skipping invalid argument '%s' to MapAddress", to);
4286 } else {
4287 addressmap_register(from, tor_strdup(to), 0, ADDRMAPSRC_TORRC);
4288 if (smartlist_len(elts)>2) {
4289 log_warn(LD_CONFIG,"Ignoring extra arguments to MapAddress.");
4292 } else {
4293 log_warn(LD_CONFIG,"MapAddress '%s' has too few arguments. Ignoring.",
4294 opt->value);
4296 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
4297 smartlist_clear(elts);
4299 smartlist_free(elts);
4303 * Initialize the logs based on the configuration file.
4305 static int
4306 options_init_logs(or_options_t *options, int validate_only)
4308 config_line_t *opt;
4309 int ok;
4310 smartlist_t *elts;
4311 int daemon =
4312 #ifdef MS_WINDOWS
4314 #else
4315 options->RunAsDaemon;
4316 #endif
4318 ok = 1;
4319 elts = smartlist_create();
4321 for (opt = options->Logs; opt; opt = opt->next) {
4322 log_severity_list_t *severity;
4323 const char *cfg = opt->value;
4324 severity = tor_malloc_zero(sizeof(log_severity_list_t));
4325 if (parse_log_severity_config(&cfg, severity) < 0) {
4326 log_warn(LD_CONFIG, "Couldn't parse log levels in Log option 'Log %s'",
4327 opt->value);
4328 ok = 0; goto cleanup;
4331 smartlist_split_string(elts, cfg, NULL,
4332 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
4334 if (smartlist_len(elts) == 0)
4335 smartlist_add(elts, tor_strdup("stdout"));
4337 if (smartlist_len(elts) == 1 &&
4338 (!strcasecmp(smartlist_get(elts,0), "stdout") ||
4339 !strcasecmp(smartlist_get(elts,0), "stderr"))) {
4340 int err = smartlist_len(elts) &&
4341 !strcasecmp(smartlist_get(elts,0), "stderr");
4342 if (!validate_only) {
4343 if (daemon) {
4344 log_warn(LD_CONFIG,
4345 "Can't log to %s with RunAsDaemon set; skipping stdout",
4346 err?"stderr":"stdout");
4347 } else {
4348 add_stream_log(severity, err?"<stderr>":"<stdout>",
4349 fileno(err?stderr:stdout));
4352 goto cleanup;
4354 if (smartlist_len(elts) == 1 &&
4355 !strcasecmp(smartlist_get(elts,0), "syslog")) {
4356 #ifdef HAVE_SYSLOG_H
4357 if (!validate_only) {
4358 add_syslog_log(severity);
4360 #else
4361 log_warn(LD_CONFIG, "Syslog is not supported on this system. Sorry.");
4362 #endif
4363 goto cleanup;
4366 if (smartlist_len(elts) == 2 &&
4367 !strcasecmp(smartlist_get(elts,0), "file")) {
4368 if (!validate_only) {
4369 if (add_file_log(severity, smartlist_get(elts, 1)) < 0) {
4370 log_warn(LD_CONFIG, "Couldn't open file for 'Log %s': %s",
4371 opt->value, strerror(errno));
4372 ok = 0;
4375 goto cleanup;
4378 log_warn(LD_CONFIG, "Bad syntax on file Log option 'Log %s'",
4379 opt->value);
4380 ok = 0; goto cleanup;
4382 cleanup:
4383 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
4384 smartlist_clear(elts);
4385 tor_free(severity);
4387 smartlist_free(elts);
4389 return ok?0:-1;
4392 /** Read the contents of a Bridge line from <b>line</b>. Return 0
4393 * if the line is well-formed, and -1 if it isn't. If
4394 * <b>validate_only</b> is 0, and the line is well-formed, then add
4395 * the bridge described in the line to our internal bridge list. */
4396 static int
4397 parse_bridge_line(const char *line, int validate_only)
4399 smartlist_t *items = NULL;
4400 int r;
4401 char *addrport=NULL, *fingerprint=NULL;
4402 tor_addr_t addr;
4403 uint16_t port = 0;
4404 char digest[DIGEST_LEN];
4406 items = smartlist_create();
4407 smartlist_split_string(items, line, NULL,
4408 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4409 if (smartlist_len(items) < 1) {
4410 log_warn(LD_CONFIG, "Too few arguments to Bridge line.");
4411 goto err;
4413 addrport = smartlist_get(items, 0);
4414 smartlist_del_keeporder(items, 0);
4415 if (tor_addr_port_parse(addrport, &addr, &port)<0) {
4416 log_warn(LD_CONFIG, "Error parsing Bridge address '%s'", addrport);
4417 goto err;
4419 if (!port) {
4420 log_info(LD_CONFIG,
4421 "Bridge address '%s' has no port; using default port 443.",
4422 addrport);
4423 port = 443;
4426 if (smartlist_len(items)) {
4427 fingerprint = smartlist_join_strings(items, "", 0, NULL);
4428 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
4429 log_warn(LD_CONFIG, "Key digest for Bridge is wrong length.");
4430 goto err;
4432 if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
4433 log_warn(LD_CONFIG, "Unable to decode Bridge key digest.");
4434 goto err;
4438 if (!validate_only) {
4439 log_debug(LD_DIR, "Bridge at %s:%d (%s)", fmt_addr(&addr),
4440 (int)port,
4441 fingerprint ? fingerprint : "no key listed");
4442 bridge_add_from_config(&addr, port, fingerprint ? digest : NULL);
4445 r = 0;
4446 goto done;
4448 err:
4449 r = -1;
4451 done:
4452 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4453 smartlist_free(items);
4454 tor_free(addrport);
4455 tor_free(fingerprint);
4456 return r;
4459 /** Read the contents of a DirServer line from <b>line</b>. If
4460 * <b>validate_only</b> is 0, and the line is well-formed, and it
4461 * shares any bits with <b>required_type</b> or <b>required_type</b>
4462 * is 0, then add the dirserver described in the line (minus whatever
4463 * bits it's missing) as a valid authority. Return 0 on success,
4464 * or -1 if the line isn't well-formed or if we can't add it. */
4465 static int
4466 parse_dir_server_line(const char *line, authority_type_t required_type,
4467 int validate_only)
4469 smartlist_t *items = NULL;
4470 int r;
4471 char *addrport=NULL, *address=NULL, *nickname=NULL, *fingerprint=NULL;
4472 uint16_t dir_port = 0, or_port = 0;
4473 char digest[DIGEST_LEN];
4474 char v3_digest[DIGEST_LEN];
4475 authority_type_t type = V2_AUTHORITY;
4476 int is_not_hidserv_authority = 0, is_not_v2_authority = 0;
4478 items = smartlist_create();
4479 smartlist_split_string(items, line, NULL,
4480 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
4481 if (smartlist_len(items) < 1) {
4482 log_warn(LD_CONFIG, "No arguments on DirServer line.");
4483 goto err;
4486 if (is_legal_nickname(smartlist_get(items, 0))) {
4487 nickname = smartlist_get(items, 0);
4488 smartlist_del_keeporder(items, 0);
4491 while (smartlist_len(items)) {
4492 char *flag = smartlist_get(items, 0);
4493 if (TOR_ISDIGIT(flag[0]))
4494 break;
4495 if (!strcasecmp(flag, "v1")) {
4496 type |= (V1_AUTHORITY | HIDSERV_AUTHORITY);
4497 } else if (!strcasecmp(flag, "hs")) {
4498 type |= HIDSERV_AUTHORITY;
4499 } else if (!strcasecmp(flag, "no-hs")) {
4500 is_not_hidserv_authority = 1;
4501 } else if (!strcasecmp(flag, "bridge")) {
4502 type |= BRIDGE_AUTHORITY;
4503 } else if (!strcasecmp(flag, "no-v2")) {
4504 is_not_v2_authority = 1;
4505 } else if (!strcasecmpstart(flag, "orport=")) {
4506 int ok;
4507 char *portstring = flag + strlen("orport=");
4508 or_port = (uint16_t) tor_parse_long(portstring, 10, 1, 65535, &ok, NULL);
4509 if (!ok)
4510 log_warn(LD_CONFIG, "Invalid orport '%s' on DirServer line.",
4511 portstring);
4512 } else if (!strcasecmpstart(flag, "v3ident=")) {
4513 char *idstr = flag + strlen("v3ident=");
4514 if (strlen(idstr) != HEX_DIGEST_LEN ||
4515 base16_decode(v3_digest, DIGEST_LEN, idstr, HEX_DIGEST_LEN)<0) {
4516 log_warn(LD_CONFIG, "Bad v3 identity digest '%s' on DirServer line",
4517 flag);
4518 } else {
4519 type |= V3_AUTHORITY;
4521 } else {
4522 log_warn(LD_CONFIG, "Unrecognized flag '%s' on DirServer line",
4523 flag);
4525 tor_free(flag);
4526 smartlist_del_keeporder(items, 0);
4528 if (is_not_hidserv_authority)
4529 type &= ~HIDSERV_AUTHORITY;
4530 if (is_not_v2_authority)
4531 type &= ~V2_AUTHORITY;
4533 if (smartlist_len(items) < 2) {
4534 log_warn(LD_CONFIG, "Too few arguments to DirServer line.");
4535 goto err;
4537 addrport = smartlist_get(items, 0);
4538 smartlist_del_keeporder(items, 0);
4539 if (parse_addr_port(LOG_WARN, addrport, &address, NULL, &dir_port)<0) {
4540 log_warn(LD_CONFIG, "Error parsing DirServer address '%s'", addrport);
4541 goto err;
4543 if (!dir_port) {
4544 log_warn(LD_CONFIG, "Missing port in DirServer address '%s'",addrport);
4545 goto err;
4548 fingerprint = smartlist_join_strings(items, "", 0, NULL);
4549 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
4550 log_warn(LD_CONFIG, "Key digest for DirServer is wrong length %d.",
4551 (int)strlen(fingerprint));
4552 goto err;
4554 if (!strcmp(fingerprint, "E623F7625FBE0C87820F11EC5F6D5377ED816294")) {
4555 /* a known bad fingerprint. refuse to use it. We can remove this
4556 * clause once Tor 0.1.2.17 is obsolete. */
4557 log_warn(LD_CONFIG, "Dangerous dirserver line. To correct, erase your "
4558 "torrc file (%s), or reinstall Tor and use the default torrc.",
4559 get_torrc_fname());
4560 goto err;
4562 if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
4563 log_warn(LD_CONFIG, "Unable to decode DirServer key digest.");
4564 goto err;
4567 if (!validate_only && (!required_type || required_type & type)) {
4568 if (required_type)
4569 type &= required_type; /* pare down what we think of them as an
4570 * authority for. */
4571 log_debug(LD_DIR, "Trusted %d dirserver at %s:%d (%s)", (int)type,
4572 address, (int)dir_port, (char*)smartlist_get(items,0));
4573 if (!add_trusted_dir_server(nickname, address, dir_port, or_port,
4574 digest, v3_digest, type))
4575 goto err;
4578 r = 0;
4579 goto done;
4581 err:
4582 r = -1;
4584 done:
4585 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
4586 smartlist_free(items);
4587 tor_free(addrport);
4588 tor_free(address);
4589 tor_free(nickname);
4590 tor_free(fingerprint);
4591 return r;
4594 /** Adjust the value of options->DataDirectory, or fill it in if it's
4595 * absent. Return 0 on success, -1 on failure. */
4596 static int
4597 normalize_data_directory(or_options_t *options)
4599 #ifdef MS_WINDOWS
4600 char *p;
4601 if (options->DataDirectory)
4602 return 0; /* all set */
4603 p = tor_malloc(MAX_PATH);
4604 strlcpy(p,get_windows_conf_root(),MAX_PATH);
4605 options->DataDirectory = p;
4606 return 0;
4607 #else
4608 const char *d = options->DataDirectory;
4609 if (!d)
4610 d = "~/.tor";
4612 if (strncmp(d,"~/",2) == 0) {
4613 char *fn = expand_filename(d);
4614 if (!fn) {
4615 log_warn(LD_CONFIG,"Failed to expand filename \"%s\".", d);
4616 return -1;
4618 if (!options->DataDirectory && !strcmp(fn,"/.tor")) {
4619 /* If our homedir is /, we probably don't want to use it. */
4620 /* Default to LOCALSTATEDIR/tor which is probably closer to what we
4621 * want. */
4622 log_warn(LD_CONFIG,
4623 "Default DataDirectory is \"~/.tor\". This expands to "
4624 "\"%s\", which is probably not what you want. Using "
4625 "\"%s"PATH_SEPARATOR"tor\" instead", fn, LOCALSTATEDIR);
4626 tor_free(fn);
4627 fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor");
4629 tor_free(options->DataDirectory);
4630 options->DataDirectory = fn;
4632 return 0;
4633 #endif
4636 /** Check and normalize the value of options->DataDirectory; return 0 if it
4637 * sane, -1 otherwise. */
4638 static int
4639 validate_data_directory(or_options_t *options)
4641 if (normalize_data_directory(options) < 0)
4642 return -1;
4643 tor_assert(options->DataDirectory);
4644 if (strlen(options->DataDirectory) > (512-128)) {
4645 log_warn(LD_CONFIG, "DataDirectory is too long.");
4646 return -1;
4648 return 0;
4651 /** This string must remain the same forevermore. It is how we
4652 * recognize that the torrc file doesn't need to be backed up. */
4653 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
4654 "if you edit it, comments will not be preserved"
4655 /** This string can change; it tries to give the reader an idea
4656 * that editing this file by hand is not a good plan. */
4657 #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
4658 "to torrc.orig.1 or similar, and Tor will ignore it"
4660 /** Save a configuration file for the configuration in <b>options</b>
4661 * into the file <b>fname</b>. If the file already exists, and
4662 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
4663 * replace it. Return 0 on success, -1 on failure. */
4664 static int
4665 write_configuration_file(const char *fname, or_options_t *options)
4667 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
4668 int rename_old = 0, r;
4669 size_t len;
4671 tor_assert(fname);
4673 switch (file_status(fname)) {
4674 case FN_FILE:
4675 old_val = read_file_to_str(fname, 0, NULL);
4676 if (strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
4677 rename_old = 1;
4679 tor_free(old_val);
4680 break;
4681 case FN_NOENT:
4682 break;
4683 case FN_ERROR:
4684 case FN_DIR:
4685 default:
4686 log_warn(LD_CONFIG,
4687 "Config file \"%s\" is not a file? Failing.", fname);
4688 return -1;
4691 if (!(new_conf = options_dump(options, 1))) {
4692 log_warn(LD_BUG, "Couldn't get configuration string");
4693 goto err;
4696 len = strlen(new_conf)+256;
4697 new_val = tor_malloc(len);
4698 tor_snprintf(new_val, len, "%s\n%s\n\n%s",
4699 GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
4701 if (rename_old) {
4702 int i = 1;
4703 size_t fn_tmp_len = strlen(fname)+32;
4704 char *fn_tmp;
4705 tor_assert(fn_tmp_len > strlen(fname)); /*check for overflow*/
4706 fn_tmp = tor_malloc(fn_tmp_len);
4707 while (1) {
4708 if (tor_snprintf(fn_tmp, fn_tmp_len, "%s.orig.%d", fname, i)<0) {
4709 log_warn(LD_BUG, "tor_snprintf failed inexplicably");
4710 tor_free(fn_tmp);
4711 goto err;
4713 if (file_status(fn_tmp) == FN_NOENT)
4714 break;
4715 ++i;
4717 log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
4718 if (rename(fname, fn_tmp) < 0) {
4719 log_warn(LD_FS,
4720 "Couldn't rename configuration file \"%s\" to \"%s\": %s",
4721 fname, fn_tmp, strerror(errno));
4722 tor_free(fn_tmp);
4723 goto err;
4725 tor_free(fn_tmp);
4728 if (write_str_to_file(fname, new_val, 0) < 0)
4729 goto err;
4731 r = 0;
4732 goto done;
4733 err:
4734 r = -1;
4735 done:
4736 tor_free(new_val);
4737 tor_free(new_conf);
4738 return r;
4742 * Save the current configuration file value to disk. Return 0 on
4743 * success, -1 on failure.
4746 options_save_current(void)
4748 if (torrc_fname) {
4749 /* This fails if we can't write to our configuration file.
4751 * If we try falling back to datadirectory or something, we have a better
4752 * chance of saving the configuration, but a better chance of doing
4753 * something the user never expected. Let's just warn instead. */
4754 return write_configuration_file(torrc_fname, get_options());
4756 return write_configuration_file(get_default_conf_file(), get_options());
4759 /** Mapping from a unit name to a multiplier for converting that unit into a
4760 * base unit. */
4761 struct unit_table_t {
4762 const char *unit;
4763 uint64_t multiplier;
4766 /** Table to map the names of memory units to the number of bytes they
4767 * contain. */
4768 static struct unit_table_t memory_units[] = {
4769 { "", 1 },
4770 { "b", 1<< 0 },
4771 { "byte", 1<< 0 },
4772 { "bytes", 1<< 0 },
4773 { "kb", 1<<10 },
4774 { "kbyte", 1<<10 },
4775 { "kbytes", 1<<10 },
4776 { "kilobyte", 1<<10 },
4777 { "kilobytes", 1<<10 },
4778 { "m", 1<<20 },
4779 { "mb", 1<<20 },
4780 { "mbyte", 1<<20 },
4781 { "mbytes", 1<<20 },
4782 { "megabyte", 1<<20 },
4783 { "megabytes", 1<<20 },
4784 { "gb", 1<<30 },
4785 { "gbyte", 1<<30 },
4786 { "gbytes", 1<<30 },
4787 { "gigabyte", 1<<30 },
4788 { "gigabytes", 1<<30 },
4789 { "tb", U64_LITERAL(1)<<40 },
4790 { "terabyte", U64_LITERAL(1)<<40 },
4791 { "terabytes", U64_LITERAL(1)<<40 },
4792 { NULL, 0 },
4795 /** Table to map the names of time units to the number of seconds they
4796 * contain. */
4797 static struct unit_table_t time_units[] = {
4798 { "", 1 },
4799 { "second", 1 },
4800 { "seconds", 1 },
4801 { "minute", 60 },
4802 { "minutes", 60 },
4803 { "hour", 60*60 },
4804 { "hours", 60*60 },
4805 { "day", 24*60*60 },
4806 { "days", 24*60*60 },
4807 { "week", 7*24*60*60 },
4808 { "weeks", 7*24*60*60 },
4809 { NULL, 0 },
4812 /** Parse a string <b>val</b> containing a number, zero or more
4813 * spaces, and an optional unit string. If the unit appears in the
4814 * table <b>u</b>, then multiply the number by the unit multiplier.
4815 * On success, set *<b>ok</b> to 1 and return this product.
4816 * Otherwise, set *<b>ok</b> to 0.
4818 static uint64_t
4819 config_parse_units(const char *val, struct unit_table_t *u, int *ok)
4821 uint64_t v = 0;
4822 double d = 0;
4823 int use_float = 0;
4825 smartlist_t *sl;
4827 tor_assert(ok);
4828 sl = smartlist_create();
4829 smartlist_split_string(sl, val, NULL,
4830 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 3);
4832 if (smartlist_len(sl) < 1 || smartlist_len(sl) > 2) {
4833 *ok = 0;
4834 goto done;
4837 v = tor_parse_uint64(smartlist_get(sl,0), 10, 0, UINT64_MAX, ok, NULL);
4838 if (!*ok) {
4839 int r = sscanf(smartlist_get(sl,0), "%lf", &d);
4840 if (r == 0 || d < 0)
4841 goto done;
4842 use_float = 1;
4845 if (smartlist_len(sl) == 1) {
4846 *ok = 1;
4847 v = use_float ? DBL_TO_U64(d) : v;
4848 goto done;
4851 for ( ;u->unit;++u) {
4852 if (!strcasecmp(u->unit, smartlist_get(sl,1))) {
4853 if (use_float)
4854 v = u->multiplier * d;
4855 else
4856 v *= u->multiplier;
4857 *ok = 1;
4858 goto done;
4861 log_warn(LD_CONFIG, "Unknown unit '%s'.", (char*)smartlist_get(sl,1));
4862 *ok = 0;
4863 done:
4864 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
4865 smartlist_free(sl);
4867 if (*ok)
4868 return v;
4869 else
4870 return 0;
4873 /** Parse a string in the format "number unit", where unit is a unit of
4874 * information (byte, KB, M, etc). On success, set *<b>ok</b> to true
4875 * and return the number of bytes specified. Otherwise, set
4876 * *<b>ok</b> to false and return 0. */
4877 static uint64_t
4878 config_parse_memunit(const char *s, int *ok)
4880 return config_parse_units(s, memory_units, ok);
4883 /** Parse a string in the format "number unit", where unit is a unit of time.
4884 * On success, set *<b>ok</b> to true and return the number of seconds in
4885 * the provided interval. Otherwise, set *<b>ok</b> to 0 and return -1.
4887 static int
4888 config_parse_interval(const char *s, int *ok)
4890 uint64_t r;
4891 r = config_parse_units(s, time_units, ok);
4892 if (!ok)
4893 return -1;
4894 if (r > INT_MAX) {
4895 log_warn(LD_CONFIG, "Interval '%s' is too long", s);
4896 *ok = 0;
4897 return -1;
4899 return (int)r;
4903 * Initialize the libevent library.
4905 static void
4906 init_libevent(void)
4908 const char *badness=NULL;
4910 configure_libevent_logging();
4911 /* If the kernel complains that some method (say, epoll) doesn't
4912 * exist, we don't care about it, since libevent will cope.
4914 suppress_libevent_log_msg("Function not implemented");
4916 tor_check_libevent_header_compatibility();
4918 tor_libevent_initialize();
4920 suppress_libevent_log_msg(NULL);
4922 tor_check_libevent_version(tor_libevent_get_method(),
4923 get_options()->ORPort != 0,
4924 &badness);
4925 if (badness) {
4926 const char *v = tor_libevent_get_version_str();
4927 const char *m = tor_libevent_get_method();
4928 control_event_general_status(LOG_WARN,
4929 "BAD_LIBEVENT VERSION=%s METHOD=%s BADNESS=%s RECOVERED=NO",
4930 v, m, badness);
4934 /** Return the persistent state struct for this Tor. */
4935 or_state_t *
4936 get_or_state(void)
4938 tor_assert(global_state);
4939 return global_state;
4942 /** Return a newly allocated string holding a filename relative to the data
4943 * directory. If <b>sub1</b> is present, it is the first path component after
4944 * the data directory. If <b>sub2</b> is also present, it is the second path
4945 * component after the data directory. If <b>suffix</b> is present, it
4946 * is appended to the filename.
4948 * Examples:
4949 * get_datadir_fname2_suffix("a", NULL, NULL) -> $DATADIR/a
4950 * get_datadir_fname2_suffix("a", NULL, ".tmp") -> $DATADIR/a.tmp
4951 * get_datadir_fname2_suffix("a", "b", ".tmp") -> $DATADIR/a/b/.tmp
4952 * get_datadir_fname2_suffix("a", "b", NULL) -> $DATADIR/a/b
4954 * Note: Consider using the get_datadir_fname* macros in or.h.
4956 char *
4957 options_get_datadir_fname2_suffix(or_options_t *options,
4958 const char *sub1, const char *sub2,
4959 const char *suffix)
4961 char *fname = NULL;
4962 size_t len;
4963 tor_assert(options);
4964 tor_assert(options->DataDirectory);
4965 tor_assert(sub1 || !sub2); /* If sub2 is present, sub1 must be present. */
4966 len = strlen(options->DataDirectory);
4967 if (sub1) {
4968 len += strlen(sub1)+1;
4969 if (sub2)
4970 len += strlen(sub2)+1;
4972 if (suffix)
4973 len += strlen(suffix);
4974 len++;
4975 fname = tor_malloc(len);
4976 if (sub1) {
4977 if (sub2) {
4978 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s",
4979 options->DataDirectory, sub1, sub2);
4980 } else {
4981 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s",
4982 options->DataDirectory, sub1);
4984 } else {
4985 strlcpy(fname, options->DataDirectory, len);
4987 if (suffix)
4988 strlcat(fname, suffix, len);
4989 return fname;
4992 /** Return 0 if every setting in <b>state</b> is reasonable, and a
4993 * permissible transition from <b>old_state</b>. Else warn and return -1.
4994 * Should have no side effects, except for normalizing the contents of
4995 * <b>state</b>.
4997 /* XXX from_setconf is here because of bug 238 */
4998 static int
4999 or_state_validate(or_state_t *old_state, or_state_t *state,
5000 int from_setconf, char **msg)
5002 /* We don't use these; only options do. Still, we need to match that
5003 * signature. */
5004 (void) from_setconf;
5005 (void) old_state;
5007 if (entry_guards_parse_state(state, 0, msg)<0)
5008 return -1;
5010 return 0;
5013 /** Replace the current persistent state with <b>new_state</b> */
5014 static void
5015 or_state_set(or_state_t *new_state)
5017 char *err = NULL;
5018 tor_assert(new_state);
5019 if (global_state)
5020 config_free(&state_format, global_state);
5021 global_state = new_state;
5022 if (entry_guards_parse_state(global_state, 1, &err)<0) {
5023 log_warn(LD_GENERAL,"%s",err);
5024 tor_free(err);
5026 if (rep_hist_load_state(global_state, &err)<0) {
5027 log_warn(LD_GENERAL,"Unparseable bandwidth history state: %s",err);
5028 tor_free(err);
5032 /** Reload the persistent state from disk, generating a new state as needed.
5033 * Return 0 on success, less than 0 on failure.
5035 static int
5036 or_state_load(void)
5038 or_state_t *new_state = NULL;
5039 char *contents = NULL, *fname;
5040 char *errmsg = NULL;
5041 int r = -1, badstate = 0;
5043 fname = get_datadir_fname("state");
5044 switch (file_status(fname)) {
5045 case FN_FILE:
5046 if (!(contents = read_file_to_str(fname, 0, NULL))) {
5047 log_warn(LD_FS, "Unable to read state file \"%s\"", fname);
5048 goto done;
5050 break;
5051 case FN_NOENT:
5052 break;
5053 case FN_ERROR:
5054 case FN_DIR:
5055 default:
5056 log_warn(LD_GENERAL,"State file \"%s\" is not a file? Failing.", fname);
5057 goto done;
5059 new_state = tor_malloc_zero(sizeof(or_state_t));
5060 new_state->_magic = OR_STATE_MAGIC;
5061 config_init(&state_format, new_state);
5062 if (contents) {
5063 config_line_t *lines=NULL;
5064 int assign_retval;
5065 if (config_get_lines(contents, &lines)<0)
5066 goto done;
5067 assign_retval = config_assign(&state_format, new_state,
5068 lines, 0, 0, &errmsg);
5069 config_free_lines(lines);
5070 if (assign_retval<0)
5071 badstate = 1;
5072 if (errmsg) {
5073 log_warn(LD_GENERAL, "%s", errmsg);
5074 tor_free(errmsg);
5078 if (!badstate && or_state_validate(NULL, new_state, 1, &errmsg) < 0)
5079 badstate = 1;
5081 if (errmsg) {
5082 log_warn(LD_GENERAL, "%s", errmsg);
5083 tor_free(errmsg);
5086 if (badstate && !contents) {
5087 log_warn(LD_BUG, "Uh oh. We couldn't even validate our own default state."
5088 " This is a bug in Tor.");
5089 goto done;
5090 } else if (badstate && contents) {
5091 int i;
5092 file_status_t status;
5093 size_t len = strlen(fname)+16;
5094 char *fname2 = tor_malloc(len);
5095 for (i = 0; i < 100; ++i) {
5096 tor_snprintf(fname2, len, "%s.%d", fname, i);
5097 status = file_status(fname2);
5098 if (status == FN_NOENT)
5099 break;
5101 if (i == 100) {
5102 log_warn(LD_BUG, "Unable to parse state in \"%s\"; too many saved bad "
5103 "state files to move aside. Discarding the old state file.",
5104 fname);
5105 unlink(fname);
5106 } else {
5107 log_warn(LD_BUG, "Unable to parse state in \"%s\". Moving it aside "
5108 "to \"%s\". This could be a bug in Tor; please tell "
5109 "the developers.", fname, fname2);
5110 if (rename(fname, fname2) < 0) {
5111 log_warn(LD_BUG, "Weirdly, I couldn't even move the state aside. The "
5112 "OS gave an error of %s", strerror(errno));
5115 tor_free(fname2);
5116 tor_free(contents);
5117 config_free(&state_format, new_state);
5119 new_state = tor_malloc_zero(sizeof(or_state_t));
5120 new_state->_magic = OR_STATE_MAGIC;
5121 config_init(&state_format, new_state);
5122 } else if (contents) {
5123 log_info(LD_GENERAL, "Loaded state from \"%s\"", fname);
5124 } else {
5125 log_info(LD_GENERAL, "Initialized state");
5127 or_state_set(new_state);
5128 new_state = NULL;
5129 if (!contents) {
5130 global_state->next_write = 0;
5131 or_state_save(time(NULL));
5133 r = 0;
5135 done:
5136 tor_free(fname);
5137 tor_free(contents);
5138 if (new_state)
5139 config_free(&state_format, new_state);
5141 return r;
5144 /** Write the persistent state to disk. Return 0 for success, <0 on failure. */
5146 or_state_save(time_t now)
5148 char *state, *contents;
5149 char tbuf[ISO_TIME_LEN+1];
5150 size_t len;
5151 char *fname;
5153 tor_assert(global_state);
5155 if (global_state->next_write > now)
5156 return 0;
5158 /* Call everything else that might dirty the state even more, in order
5159 * to avoid redundant writes. */
5160 entry_guards_update_state(global_state);
5161 rep_hist_update_state(global_state);
5162 if (accounting_is_enabled(get_options()))
5163 accounting_run_housekeeping(now);
5165 global_state->LastWritten = time(NULL);
5166 tor_free(global_state->TorVersion);
5167 len = strlen(get_version())+8;
5168 global_state->TorVersion = tor_malloc(len);
5169 tor_snprintf(global_state->TorVersion, len, "Tor %s", get_version());
5171 state = config_dump(&state_format, global_state, 1, 0);
5172 len = strlen(state)+256;
5173 contents = tor_malloc(len);
5174 format_local_iso_time(tbuf, time(NULL));
5175 tor_snprintf(contents, len,
5176 "# Tor state file last generated on %s local time\n"
5177 "# Other times below are in GMT\n"
5178 "# You *do not* need to edit this file.\n\n%s",
5179 tbuf, state);
5180 tor_free(state);
5181 fname = get_datadir_fname("state");
5182 if (write_str_to_file(fname, contents, 0)<0) {
5183 log_warn(LD_FS, "Unable to write state to file \"%s\"", fname);
5184 tor_free(fname);
5185 tor_free(contents);
5186 return -1;
5188 log_info(LD_GENERAL, "Saved state to \"%s\"", fname);
5189 tor_free(fname);
5190 tor_free(contents);
5192 global_state->next_write = TIME_MAX;
5193 return 0;
5196 /** Given a file name check to see whether the file exists but has not been
5197 * modified for a very long time. If so, remove it. */
5198 void
5199 remove_file_if_very_old(const char *fname, time_t now)
5201 #define VERY_OLD_FILE_AGE (28*24*60*60)
5202 struct stat st;
5204 if (stat(fname, &st)==0 && st.st_mtime < now-VERY_OLD_FILE_AGE) {
5205 char buf[ISO_TIME_LEN+1];
5206 format_local_iso_time(buf, st.st_mtime);
5207 log_notice(LD_GENERAL, "Obsolete file %s hasn't been modified since %s. "
5208 "Removing it.", fname, buf);
5209 unlink(fname);
5213 /** Helper to implement GETINFO functions about configuration variables (not
5214 * their values). Given a "config/names" question, set *<b>answer</b> to a
5215 * new string describing the supported configuration variables and their
5216 * types. */
5218 getinfo_helper_config(control_connection_t *conn,
5219 const char *question, char **answer)
5221 (void) conn;
5222 if (!strcmp(question, "config/names")) {
5223 smartlist_t *sl = smartlist_create();
5224 int i;
5225 for (i = 0; _option_vars[i].name; ++i) {
5226 config_var_t *var = &_option_vars[i];
5227 const char *type, *desc;
5228 char *line;
5229 size_t len;
5230 desc = config_find_description(&options_format, var->name);
5231 switch (var->type) {
5232 case CONFIG_TYPE_STRING: type = "String"; break;
5233 case CONFIG_TYPE_FILENAME: type = "Filename"; break;
5234 case CONFIG_TYPE_UINT: type = "Integer"; break;
5235 case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
5236 case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
5237 case CONFIG_TYPE_DOUBLE: type = "Float"; break;
5238 case CONFIG_TYPE_BOOL: type = "Boolean"; break;
5239 case CONFIG_TYPE_ISOTIME: type = "Time"; break;
5240 case CONFIG_TYPE_ROUTERSET: type = "RouterList"; break;
5241 case CONFIG_TYPE_CSV: type = "CommaList"; break;
5242 case CONFIG_TYPE_LINELIST: type = "LineList"; break;
5243 case CONFIG_TYPE_LINELIST_S: type = "Dependant"; break;
5244 case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
5245 default:
5246 case CONFIG_TYPE_OBSOLETE:
5247 type = NULL; break;
5249 if (!type)
5250 continue;
5251 len = strlen(var->name)+strlen(type)+16;
5252 if (desc)
5253 len += strlen(desc);
5254 line = tor_malloc(len);
5255 if (desc)
5256 tor_snprintf(line, len, "%s %s %s\n",var->name,type,desc);
5257 else
5258 tor_snprintf(line, len, "%s %s\n",var->name,type);
5259 smartlist_add(sl, line);
5261 *answer = smartlist_join_strings(sl, "", 0, NULL);
5262 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
5263 smartlist_free(sl);
5265 return 0;