Merge remote branch 'origin/maint-0.2.1' into maint-0.2.2
[tor/rransom.git] / src / or / config.c
blobb124db1899b075c60b1f3d627a536704918d15ca
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-2011, 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 #include "circuitbuild.h"
16 #include "circuitlist.h"
17 #include "config.h"
18 #include "connection.h"
19 #include "connection_edge.h"
20 #include "connection_or.h"
21 #include "control.h"
22 #include "cpuworker.h"
23 #include "dirserv.h"
24 #include "dirvote.h"
25 #include "dns.h"
26 #include "geoip.h"
27 #include "hibernate.h"
28 #include "main.h"
29 #include "networkstatus.h"
30 #include "policies.h"
31 #include "relay.h"
32 #include "rendclient.h"
33 #include "rendservice.h"
34 #include "rephist.h"
35 #include "router.h"
36 #include "routerlist.h"
37 #ifdef MS_WINDOWS
38 #include <shlobj.h>
39 #endif
41 /** Enumeration of types which option values can take */
42 typedef enum config_type_t {
43 CONFIG_TYPE_STRING = 0, /**< An arbitrary string. */
44 CONFIG_TYPE_FILENAME, /**< A filename: some prefixes get expanded. */
45 CONFIG_TYPE_UINT, /**< A non-negative integer less than MAX_INT */
46 CONFIG_TYPE_INTERVAL, /**< A number of seconds, with optional units*/
47 CONFIG_TYPE_MEMUNIT, /**< A number of bytes, with optional units*/
48 CONFIG_TYPE_DOUBLE, /**< A floating-point value */
49 CONFIG_TYPE_BOOL, /**< A boolean value, expressed as 0 or 1. */
50 CONFIG_TYPE_ISOTIME, /**< An ISO-formatted time relative to GMT. */
51 CONFIG_TYPE_CSV, /**< A list of strings, separated by commas and
52 * optional whitespace. */
53 CONFIG_TYPE_LINELIST, /**< Uninterpreted config lines */
54 CONFIG_TYPE_LINELIST_S, /**< Uninterpreted, context-sensitive config lines,
55 * mixed with other keywords. */
56 CONFIG_TYPE_LINELIST_V, /**< Catch-all "virtual" option to summarize
57 * context-sensitive config lines when fetching.
59 CONFIG_TYPE_ROUTERSET, /**< A list of router names, addrs, and fps,
60 * parsed into a routerset_t. */
61 CONFIG_TYPE_OBSOLETE, /**< Obsolete (ignored) option. */
62 } config_type_t;
64 /** An abbreviation for a configuration option allowed on the command line. */
65 typedef struct config_abbrev_t {
66 const char *abbreviated;
67 const char *full;
68 int commandline_only;
69 int warn;
70 } config_abbrev_t;
72 /* Handy macro for declaring "In the config file or on the command line,
73 * you can abbreviate <b>tok</b>s as <b>tok</b>". */
74 #define PLURAL(tok) { #tok, #tok "s", 0, 0 }
76 /** A list of abbreviations and aliases to map command-line options, obsolete
77 * option names, or alternative option names, to their current values. */
78 static config_abbrev_t _option_abbrevs[] = {
79 PLURAL(ExitNode),
80 PLURAL(EntryNode),
81 PLURAL(ExcludeNode),
82 PLURAL(FirewallPort),
83 PLURAL(LongLivedPort),
84 PLURAL(HiddenServiceNode),
85 PLURAL(HiddenServiceExcludeNode),
86 PLURAL(NumCPU),
87 PLURAL(RendNode),
88 PLURAL(RendExcludeNode),
89 PLURAL(StrictEntryNode),
90 PLURAL(StrictExitNode),
91 PLURAL(StrictNode),
92 { "l", "Log", 1, 0},
93 { "AllowUnverifiedNodes", "AllowInvalidNodes", 0, 0},
94 { "AutomapHostSuffixes", "AutomapHostsSuffixes", 0, 0},
95 { "AutomapHostOnResolve", "AutomapHostsOnResolve", 0, 0},
96 { "BandwidthRateBytes", "BandwidthRate", 0, 0},
97 { "BandwidthBurstBytes", "BandwidthBurst", 0, 0},
98 { "DirFetchPostPeriod", "StatusFetchPeriod", 0, 0},
99 { "MaxConn", "ConnLimit", 0, 1},
100 { "ORBindAddress", "ORListenAddress", 0, 0},
101 { "DirBindAddress", "DirListenAddress", 0, 0},
102 { "SocksBindAddress", "SocksListenAddress", 0, 0},
103 { "UseHelperNodes", "UseEntryGuards", 0, 0},
104 { "NumHelperNodes", "NumEntryGuards", 0, 0},
105 { "UseEntryNodes", "UseEntryGuards", 0, 0},
106 { "NumEntryNodes", "NumEntryGuards", 0, 0},
107 { "ResolvConf", "ServerDNSResolvConfFile", 0, 1},
108 { "SearchDomains", "ServerDNSSearchDomains", 0, 1},
109 { "ServerDNSAllowBrokenResolvConf", "ServerDNSAllowBrokenConfig", 0, 0},
110 { "PreferTunnelledDirConns", "PreferTunneledDirConns", 0, 0},
111 { "BridgeAuthoritativeDirectory", "BridgeAuthoritativeDir", 0, 0},
112 { "HashedControlPassword", "__HashedControlSessionPassword", 1, 0},
113 { "StrictEntryNodes", "StrictNodes", 0, 1},
114 { "StrictExitNodes", "StrictNodes", 0, 1},
115 { NULL, NULL, 0, 0},
118 /** A list of state-file "abbreviations," for compatibility. */
119 static config_abbrev_t _state_abbrevs[] = {
120 { "AccountingBytesReadInterval", "AccountingBytesReadInInterval", 0, 0 },
121 { "HelperNode", "EntryGuard", 0, 0 },
122 { "HelperNodeDownSince", "EntryGuardDownSince", 0, 0 },
123 { "HelperNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
124 { "EntryNode", "EntryGuard", 0, 0 },
125 { "EntryNodeDownSince", "EntryGuardDownSince", 0, 0 },
126 { "EntryNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
127 { NULL, NULL, 0, 0},
129 #undef PLURAL
131 /** A variable allowed in the configuration file or on the command line. */
132 typedef struct config_var_t {
133 const char *name; /**< The full keyword (case insensitive). */
134 config_type_t type; /**< How to interpret the type and turn it into a
135 * value. */
136 off_t var_offset; /**< Offset of the corresponding member of or_options_t. */
137 const char *initvalue; /**< String (or null) describing initial value. */
138 } config_var_t;
140 /** An entry for config_vars: "The option <b>name</b> has type
141 * CONFIG_TYPE_<b>conftype</b>, and corresponds to
142 * or_options_t.<b>member</b>"
144 #define VAR(name,conftype,member,initvalue) \
145 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_options_t, member), \
146 initvalue }
147 /** As VAR, but the option name and member name are the same. */
148 #define V(member,conftype,initvalue) \
149 VAR(#member, conftype, member, initvalue)
150 /** An entry for config_vars: "The option <b>name</b> is obsolete." */
151 #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL }
153 /** Array of configuration options. Until we disallow nonstandard
154 * abbreviations, order is significant, since the first matching option will
155 * be chosen first.
157 static config_var_t _option_vars[] = {
158 OBSOLETE("AccountingMaxKB"),
159 V(AccountingMax, MEMUNIT, "0 bytes"),
160 V(AccountingStart, STRING, NULL),
161 V(Address, STRING, NULL),
162 V(AllowDotExit, BOOL, "0"),
163 V(AllowInvalidNodes, CSV, "middle,rendezvous"),
164 V(AllowNonRFC953Hostnames, BOOL, "0"),
165 V(AllowSingleHopCircuits, BOOL, "0"),
166 V(AllowSingleHopExits, BOOL, "0"),
167 V(AlternateBridgeAuthority, LINELIST, NULL),
168 V(AlternateDirAuthority, LINELIST, NULL),
169 V(AlternateHSAuthority, LINELIST, NULL),
170 V(AssumeReachable, BOOL, "0"),
171 V(AuthDirBadDir, LINELIST, NULL),
172 V(AuthDirBadExit, LINELIST, NULL),
173 V(AuthDirInvalid, LINELIST, NULL),
174 V(AuthDirReject, LINELIST, NULL),
175 V(AuthDirRejectUnlisted, BOOL, "0"),
176 V(AuthDirListBadDirs, BOOL, "0"),
177 V(AuthDirListBadExits, BOOL, "0"),
178 V(AuthDirMaxServersPerAddr, UINT, "2"),
179 V(AuthDirMaxServersPerAuthAddr,UINT, "5"),
180 VAR("AuthoritativeDirectory", BOOL, AuthoritativeDir, "0"),
181 V(AutomapHostsOnResolve, BOOL, "0"),
182 V(AutomapHostsSuffixes, CSV, ".onion,.exit"),
183 V(AvoidDiskWrites, BOOL, "0"),
184 V(BandwidthBurst, MEMUNIT, "10 MB"),
185 V(BandwidthRate, MEMUNIT, "5 MB"),
186 V(BridgeAuthoritativeDir, BOOL, "0"),
187 VAR("Bridge", LINELIST, Bridges, NULL),
188 V(BridgePassword, STRING, NULL),
189 V(BridgeRecordUsageByCountry, BOOL, "1"),
190 V(BridgeRelay, BOOL, "0"),
191 V(CellStatistics, BOOL, "0"),
192 V(LearnCircuitBuildTimeout, BOOL, "1"),
193 V(CircuitBuildTimeout, INTERVAL, "0"),
194 V(CircuitIdleTimeout, INTERVAL, "1 hour"),
195 V(CircuitStreamTimeout, INTERVAL, "0"),
196 V(CircuitPriorityHalflife, DOUBLE, "-100.0"), /*negative:'Use default'*/
197 V(ClientDNSRejectInternalAddresses, BOOL,"1"),
198 V(ClientOnly, BOOL, "0"),
199 V(ConsensusParams, STRING, NULL),
200 V(ConnLimit, UINT, "1000"),
201 V(ConstrainedSockets, BOOL, "0"),
202 V(ConstrainedSockSize, MEMUNIT, "8192"),
203 V(ContactInfo, STRING, NULL),
204 V(ControlListenAddress, LINELIST, NULL),
205 V(ControlPort, UINT, "0"),
206 V(ControlSocket, LINELIST, NULL),
207 V(CookieAuthentication, BOOL, "0"),
208 V(CookieAuthFileGroupReadable, BOOL, "0"),
209 V(CookieAuthFile, STRING, NULL),
210 V(DataDirectory, FILENAME, NULL),
211 OBSOLETE("DebugLogFile"),
212 V(DirAllowPrivateAddresses, BOOL, NULL),
213 V(TestingAuthDirTimeToLearnReachability, INTERVAL, "30 minutes"),
214 V(DirListenAddress, LINELIST, NULL),
215 OBSOLETE("DirFetchPeriod"),
216 V(DirPolicy, LINELIST, NULL),
217 V(DirPort, UINT, "0"),
218 V(DirPortFrontPage, FILENAME, NULL),
219 OBSOLETE("DirPostPeriod"),
220 OBSOLETE("DirRecordUsageByCountry"),
221 OBSOLETE("DirRecordUsageGranularity"),
222 OBSOLETE("DirRecordUsageRetainIPs"),
223 OBSOLETE("DirRecordUsageSaveInterval"),
224 V(DirReqStatistics, BOOL, "0"),
225 VAR("DirServer", LINELIST, DirServers, NULL),
226 V(DisableAllSwap, BOOL, "0"),
227 V(DNSPort, UINT, "0"),
228 V(DNSListenAddress, LINELIST, NULL),
229 V(DownloadExtraInfo, BOOL, "0"),
230 V(EnforceDistinctSubnets, BOOL, "1"),
231 V(EntryNodes, ROUTERSET, NULL),
232 V(EntryStatistics, BOOL, "0"),
233 V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "10 minutes"),
234 V(ExcludeNodes, ROUTERSET, NULL),
235 V(ExcludeExitNodes, ROUTERSET, NULL),
236 V(ExcludeSingleHopRelays, BOOL, "1"),
237 V(ExitNodes, ROUTERSET, NULL),
238 V(ExitPolicy, LINELIST, NULL),
239 V(ExitPolicyRejectPrivate, BOOL, "1"),
240 V(ExitPortStatistics, BOOL, "0"),
241 V(ExtraInfoStatistics, BOOL, "0"),
243 #if defined (WINCE)
244 V(FallbackNetworkstatusFile, FILENAME, "fallback-consensus"),
245 #else
246 V(FallbackNetworkstatusFile, FILENAME,
247 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "fallback-consensus"),
248 #endif
249 V(FascistFirewall, BOOL, "0"),
250 V(FirewallPorts, CSV, ""),
251 V(FastFirstHopPK, BOOL, "1"),
252 V(FetchDirInfoEarly, BOOL, "0"),
253 V(FetchDirInfoExtraEarly, BOOL, "0"),
254 V(FetchServerDescriptors, BOOL, "1"),
255 V(FetchHidServDescriptors, BOOL, "1"),
256 V(FetchUselessDescriptors, BOOL, "0"),
257 #ifdef WIN32
258 V(GeoIPFile, FILENAME, "<default>"),
259 #else
260 V(GeoIPFile, FILENAME,
261 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip"),
262 #endif
263 OBSOLETE("Group"),
264 V(HardwareAccel, BOOL, "0"),
265 V(AccelName, STRING, NULL),
266 V(AccelDir, FILENAME, NULL),
267 V(HashedControlPassword, LINELIST, NULL),
268 V(HidServDirectoryV2, BOOL, "1"),
269 VAR("HiddenServiceDir", LINELIST_S, RendConfigLines, NULL),
270 OBSOLETE("HiddenServiceExcludeNodes"),
271 OBSOLETE("HiddenServiceNodes"),
272 VAR("HiddenServiceOptions",LINELIST_V, RendConfigLines, NULL),
273 VAR("HiddenServicePort", LINELIST_S, RendConfigLines, NULL),
274 VAR("HiddenServiceVersion",LINELIST_S, RendConfigLines, NULL),
275 VAR("HiddenServiceAuthorizeClient",LINELIST_S,RendConfigLines, NULL),
276 V(HidServAuth, LINELIST, NULL),
277 V(HSAuthoritativeDir, BOOL, "0"),
278 OBSOLETE("HSAuthorityRecordStats"),
279 V(HTTPProxy, STRING, NULL),
280 V(HTTPProxyAuthenticator, STRING, NULL),
281 V(HTTPSProxy, STRING, NULL),
282 V(HTTPSProxyAuthenticator, STRING, NULL),
283 V(Socks4Proxy, STRING, NULL),
284 V(Socks5Proxy, STRING, NULL),
285 V(Socks5ProxyUsername, STRING, NULL),
286 V(Socks5ProxyPassword, STRING, NULL),
287 OBSOLETE("IgnoreVersion"),
288 V(KeepalivePeriod, INTERVAL, "5 minutes"),
289 VAR("Log", LINELIST, Logs, NULL),
290 OBSOLETE("LinkPadding"),
291 OBSOLETE("LogLevel"),
292 OBSOLETE("LogFile"),
293 V(LongLivedPorts, CSV,
294 "21,22,706,1863,5050,5190,5222,5223,6667,6697,8300"),
295 VAR("MapAddress", LINELIST, AddressMap, NULL),
296 V(MaxAdvertisedBandwidth, MEMUNIT, "1 GB"),
297 V(MaxCircuitDirtiness, INTERVAL, "10 minutes"),
298 V(MaxOnionsPending, UINT, "100"),
299 OBSOLETE("MonthlyAccountingStart"),
300 V(MyFamily, STRING, NULL),
301 V(NewCircuitPeriod, INTERVAL, "30 seconds"),
302 VAR("NamingAuthoritativeDirectory",BOOL, NamingAuthoritativeDir, "0"),
303 V(NATDListenAddress, LINELIST, NULL),
304 V(NATDPort, UINT, "0"),
305 V(Nickname, STRING, NULL),
306 V(WarnUnsafeSocks, BOOL, "1"),
307 OBSOLETE("NoPublish"),
308 VAR("NodeFamily", LINELIST, NodeFamilies, NULL),
309 V(NumCPUs, UINT, "1"),
310 V(NumEntryGuards, UINT, "3"),
311 V(ORListenAddress, LINELIST, NULL),
312 V(ORPort, UINT, "0"),
313 V(OutboundBindAddress, STRING, NULL),
314 OBSOLETE("PathlenCoinWeight"),
315 V(PerConnBWBurst, MEMUNIT, "0"),
316 V(PerConnBWRate, MEMUNIT, "0"),
317 V(PidFile, STRING, NULL),
318 V(TestingTorNetwork, BOOL, "0"),
319 V(PreferTunneledDirConns, BOOL, "1"),
320 V(ProtocolWarnings, BOOL, "0"),
321 V(PublishServerDescriptor, CSV, "1"),
322 V(PublishHidServDescriptors, BOOL, "1"),
323 V(ReachableAddresses, LINELIST, NULL),
324 V(ReachableDirAddresses, LINELIST, NULL),
325 V(ReachableORAddresses, LINELIST, NULL),
326 V(RecommendedVersions, LINELIST, NULL),
327 V(RecommendedClientVersions, LINELIST, NULL),
328 V(RecommendedServerVersions, LINELIST, NULL),
329 OBSOLETE("RedirectExit"),
330 V(RefuseUnknownExits, STRING, "auto"),
331 V(RejectPlaintextPorts, CSV, ""),
332 V(RelayBandwidthBurst, MEMUNIT, "0"),
333 V(RelayBandwidthRate, MEMUNIT, "0"),
334 OBSOLETE("RendExcludeNodes"),
335 OBSOLETE("RendNodes"),
336 V(RendPostPeriod, INTERVAL, "1 hour"),
337 V(RephistTrackTime, INTERVAL, "24 hours"),
338 OBSOLETE("RouterFile"),
339 V(RunAsDaemon, BOOL, "0"),
340 // V(RunTesting, BOOL, "0"),
341 OBSOLETE("RunTesting"), // currently unused
342 V(SafeLogging, STRING, "1"),
343 V(SafeSocks, BOOL, "0"),
344 V(ServerDNSAllowBrokenConfig, BOOL, "1"),
345 V(ServerDNSAllowNonRFC953Hostnames, BOOL,"0"),
346 V(ServerDNSDetectHijacking, BOOL, "1"),
347 V(ServerDNSRandomizeCase, BOOL, "1"),
348 V(ServerDNSResolvConfFile, STRING, NULL),
349 V(ServerDNSSearchDomains, BOOL, "0"),
350 V(ServerDNSTestAddresses, CSV,
351 "www.google.com,www.mit.edu,www.yahoo.com,www.slashdot.org"),
352 V(ShutdownWaitLength, INTERVAL, "30 seconds"),
353 V(SocksListenAddress, LINELIST, NULL),
354 V(SocksPolicy, LINELIST, NULL),
355 V(SocksPort, UINT, "9050"),
356 V(SocksTimeout, INTERVAL, "2 minutes"),
357 OBSOLETE("StatusFetchPeriod"),
358 V(StrictNodes, BOOL, "0"),
359 OBSOLETE("SysLog"),
360 V(TestSocks, BOOL, "0"),
361 OBSOLETE("TestVia"),
362 V(TrackHostExits, CSV, NULL),
363 V(TrackHostExitsExpire, INTERVAL, "30 minutes"),
364 OBSOLETE("TrafficShaping"),
365 V(TransListenAddress, LINELIST, NULL),
366 V(TransPort, UINT, "0"),
367 V(TunnelDirConns, BOOL, "1"),
368 V(UpdateBridgesFromAuthority, BOOL, "0"),
369 V(UseBridges, BOOL, "0"),
370 V(UseEntryGuards, BOOL, "1"),
371 V(User, STRING, NULL),
372 VAR("V1AuthoritativeDirectory",BOOL, V1AuthoritativeDir, "0"),
373 VAR("V2AuthoritativeDirectory",BOOL, V2AuthoritativeDir, "0"),
374 VAR("V3AuthoritativeDirectory",BOOL, V3AuthoritativeDir, "0"),
375 V(TestingV3AuthInitialVotingInterval, INTERVAL, "30 minutes"),
376 V(TestingV3AuthInitialVoteDelay, INTERVAL, "5 minutes"),
377 V(TestingV3AuthInitialDistDelay, INTERVAL, "5 minutes"),
378 V(V3AuthVotingInterval, INTERVAL, "1 hour"),
379 V(V3AuthVoteDelay, INTERVAL, "5 minutes"),
380 V(V3AuthDistDelay, INTERVAL, "5 minutes"),
381 V(V3AuthNIntervalsValid, UINT, "3"),
382 V(V3AuthUseLegacyKey, BOOL, "0"),
383 V(V3BandwidthsFile, FILENAME, NULL),
384 VAR("VersioningAuthoritativeDirectory",BOOL,VersioningAuthoritativeDir, "0"),
385 V(VirtualAddrNetwork, STRING, "127.192.0.0/10"),
386 V(WarnPlaintextPorts, CSV, "23,109,110,143"),
387 VAR("__ReloadTorrcOnSIGHUP", BOOL, ReloadTorrcOnSIGHUP, "1"),
388 VAR("__AllDirActionsPrivate", BOOL, AllDirActionsPrivate, "0"),
389 VAR("__DisablePredictedCircuits",BOOL,DisablePredictedCircuits, "0"),
390 VAR("__LeaveStreamsUnattached",BOOL, LeaveStreamsUnattached, "0"),
391 VAR("__HashedControlSessionPassword", LINELIST, HashedControlSessionPassword,
392 NULL),
393 V(MinUptimeHidServDirectoryV2, INTERVAL, "24 hours"),
395 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
398 /** Override default values with these if the user sets the TestingTorNetwork
399 * option. */
400 static config_var_t testing_tor_network_defaults[] = {
401 V(ServerDNSAllowBrokenConfig, BOOL, "1"),
402 V(DirAllowPrivateAddresses, BOOL, "1"),
403 V(EnforceDistinctSubnets, BOOL, "0"),
404 V(AssumeReachable, BOOL, "1"),
405 V(AuthDirMaxServersPerAddr, UINT, "0"),
406 V(AuthDirMaxServersPerAuthAddr,UINT, "0"),
407 V(ClientDNSRejectInternalAddresses, BOOL,"0"),
408 V(ExitPolicyRejectPrivate, BOOL, "0"),
409 V(V3AuthVotingInterval, INTERVAL, "5 minutes"),
410 V(V3AuthVoteDelay, INTERVAL, "20 seconds"),
411 V(V3AuthDistDelay, INTERVAL, "20 seconds"),
412 V(TestingV3AuthInitialVotingInterval, INTERVAL, "5 minutes"),
413 V(TestingV3AuthInitialVoteDelay, INTERVAL, "20 seconds"),
414 V(TestingV3AuthInitialDistDelay, INTERVAL, "20 seconds"),
415 V(TestingAuthDirTimeToLearnReachability, INTERVAL, "0 minutes"),
416 V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "0 minutes"),
417 V(MinUptimeHidServDirectoryV2, INTERVAL, "0 minutes"),
418 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
420 #undef VAR
422 #define VAR(name,conftype,member,initvalue) \
423 { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_state_t, member), \
424 initvalue }
426 /** Array of "state" variables saved to the ~/.tor/state file. */
427 static config_var_t _state_vars[] = {
428 V(AccountingBytesReadInInterval, MEMUNIT, NULL),
429 V(AccountingBytesWrittenInInterval, MEMUNIT, NULL),
430 V(AccountingExpectedUsage, MEMUNIT, NULL),
431 V(AccountingIntervalStart, ISOTIME, NULL),
432 V(AccountingSecondsActive, INTERVAL, NULL),
433 V(AccountingSecondsToReachSoftLimit,INTERVAL, NULL),
434 V(AccountingSoftLimitHitAt, ISOTIME, NULL),
435 V(AccountingBytesAtSoftLimit, MEMUNIT, NULL),
437 VAR("EntryGuard", LINELIST_S, EntryGuards, NULL),
438 VAR("EntryGuardDownSince", LINELIST_S, EntryGuards, NULL),
439 VAR("EntryGuardUnlistedSince", LINELIST_S, EntryGuards, NULL),
440 VAR("EntryGuardAddedBy", LINELIST_S, EntryGuards, NULL),
441 V(EntryGuards, LINELIST_V, NULL),
443 V(BWHistoryReadEnds, ISOTIME, NULL),
444 V(BWHistoryReadInterval, UINT, "900"),
445 V(BWHistoryReadValues, CSV, ""),
446 V(BWHistoryWriteEnds, ISOTIME, NULL),
447 V(BWHistoryWriteInterval, UINT, "900"),
448 V(BWHistoryWriteValues, CSV, ""),
449 V(BWHistoryDirReadEnds, ISOTIME, NULL),
450 V(BWHistoryDirReadInterval, UINT, "900"),
451 V(BWHistoryDirReadValues, CSV, ""),
452 V(BWHistoryDirWriteEnds, ISOTIME, NULL),
453 V(BWHistoryDirWriteInterval, UINT, "900"),
454 V(BWHistoryDirWriteValues, CSV, ""),
456 V(TorVersion, STRING, NULL),
458 V(LastRotatedOnionKey, ISOTIME, NULL),
459 V(LastWritten, ISOTIME, NULL),
461 V(TotalBuildTimes, UINT, NULL),
462 V(CircuitBuildAbandonedCount, UINT, "0"),
463 VAR("CircuitBuildTimeBin", LINELIST_S, BuildtimeHistogram, NULL),
464 VAR("BuildtimeHistogram", LINELIST_V, BuildtimeHistogram, NULL),
466 { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
469 #undef VAR
470 #undef V
471 #undef OBSOLETE
473 /** Represents an English description of a configuration variable; used when
474 * generating configuration file comments. */
475 typedef struct config_var_description_t {
476 const char *name;
477 const char *description;
478 } config_var_description_t;
480 /** Type of a callback to validate whether a given configuration is
481 * well-formed and consistent. See options_trial_assign() for documentation
482 * of arguments. */
483 typedef int (*validate_fn_t)(void*,void*,int,char**);
485 /** Information on the keys, value types, key-to-struct-member mappings,
486 * variable descriptions, validation functions, and abbreviations for a
487 * configuration or storage format. */
488 typedef struct {
489 size_t size; /**< Size of the struct that everything gets parsed into. */
490 uint32_t magic; /**< Required 'magic value' to make sure we have a struct
491 * of the right type. */
492 off_t magic_offset; /**< Offset of the magic value within the struct. */
493 config_abbrev_t *abbrevs; /**< List of abbreviations that we expand when
494 * parsing this format. */
495 config_var_t *vars; /**< List of variables we recognize, their default
496 * values, and where we stick them in the structure. */
497 validate_fn_t validate_fn; /**< Function to validate config. */
498 /** If present, extra is a LINELIST variable for unrecognized
499 * lines. Otherwise, unrecognized lines are an error. */
500 config_var_t *extra;
501 } config_format_t;
503 /** Macro: assert that <b>cfg</b> has the right magic field for format
504 * <b>fmt</b>. */
505 #define CHECK(fmt, cfg) STMT_BEGIN \
506 tor_assert(fmt && cfg); \
507 tor_assert((fmt)->magic == \
508 *(uint32_t*)STRUCT_VAR_P(cfg,fmt->magic_offset)); \
509 STMT_END
511 #ifdef MS_WINDOWS
512 static char *get_windows_conf_root(void);
513 #endif
514 static void config_line_append(config_line_t **lst,
515 const char *key, const char *val);
516 static void option_clear(config_format_t *fmt, or_options_t *options,
517 config_var_t *var);
518 static void option_reset(config_format_t *fmt, or_options_t *options,
519 config_var_t *var, int use_defaults);
520 static void config_free(config_format_t *fmt, void *options);
521 static int config_lines_eq(config_line_t *a, config_line_t *b);
522 static int option_is_same(config_format_t *fmt,
523 or_options_t *o1, or_options_t *o2,
524 const char *name);
525 static or_options_t *options_dup(config_format_t *fmt, or_options_t *old);
526 static int options_validate(or_options_t *old_options, or_options_t *options,
527 int from_setconf, char **msg);
528 static int options_act_reversible(or_options_t *old_options, char **msg);
529 static int options_act(or_options_t *old_options);
530 static int options_transition_allowed(or_options_t *old, or_options_t *new,
531 char **msg);
532 static int options_transition_affects_workers(or_options_t *old_options,
533 or_options_t *new_options);
534 static int options_transition_affects_descriptor(or_options_t *old_options,
535 or_options_t *new_options);
536 static int check_nickname_list(const char *lst, const char *name, char **msg);
537 static void config_register_addressmaps(or_options_t *options);
539 static int parse_bridge_line(const char *line, int validate_only);
540 static int parse_dir_server_line(const char *line,
541 authority_type_t required_type,
542 int validate_only);
543 static int validate_data_directory(or_options_t *options);
544 static int write_configuration_file(const char *fname, or_options_t *options);
545 static config_line_t *get_assigned_option(config_format_t *fmt,
546 void *options, const char *key,
547 int escape_val);
548 static void config_init(config_format_t *fmt, void *options);
549 static int or_state_validate(or_state_t *old_options, or_state_t *options,
550 int from_setconf, char **msg);
551 static int or_state_load(void);
552 static int options_init_logs(or_options_t *options, int validate_only);
554 static int is_listening_on_low_port(uint16_t port_option,
555 const config_line_t *listen_options);
557 static uint64_t config_parse_memunit(const char *s, int *ok);
558 static int config_parse_interval(const char *s, int *ok);
559 static void init_libevent(void);
560 static int opt_streq(const char *s1, const char *s2);
562 /** Magic value for or_options_t. */
563 #define OR_OPTIONS_MAGIC 9090909
565 /** Configuration format for or_options_t. */
566 static config_format_t options_format = {
567 sizeof(or_options_t),
568 OR_OPTIONS_MAGIC,
569 STRUCT_OFFSET(or_options_t, _magic),
570 _option_abbrevs,
571 _option_vars,
572 (validate_fn_t)options_validate,
573 NULL
576 /** Magic value for or_state_t. */
577 #define OR_STATE_MAGIC 0x57A73f57
579 /** "Extra" variable in the state that receives lines we can't parse. This
580 * lets us preserve options from versions of Tor newer than us. */
581 static config_var_t state_extra_var = {
582 "__extra", CONFIG_TYPE_LINELIST, STRUCT_OFFSET(or_state_t, ExtraLines), NULL
585 /** Configuration format for or_state_t. */
586 static config_format_t state_format = {
587 sizeof(or_state_t),
588 OR_STATE_MAGIC,
589 STRUCT_OFFSET(or_state_t, _magic),
590 _state_abbrevs,
591 _state_vars,
592 (validate_fn_t)or_state_validate,
593 &state_extra_var,
597 * Functions to read and write the global options pointer.
600 /** Command-line and config-file options. */
601 static or_options_t *global_options = NULL;
602 /** Name of most recently read torrc file. */
603 static char *torrc_fname = NULL;
604 /** Persistent serialized state. */
605 static or_state_t *global_state = NULL;
606 /** Configuration Options set by command line. */
607 static config_line_t *global_cmdline_options = NULL;
608 /** Contents of most recently read DirPortFrontPage file. */
609 static char *global_dirfrontpagecontents = NULL;
611 /** Return the contents of our frontpage string, or NULL if not configured. */
612 const char *
613 get_dirportfrontpage(void)
615 return global_dirfrontpagecontents;
618 /** Allocate an empty configuration object of a given format type. */
619 static void *
620 config_alloc(config_format_t *fmt)
622 void *opts = tor_malloc_zero(fmt->size);
623 *(uint32_t*)STRUCT_VAR_P(opts, fmt->magic_offset) = fmt->magic;
624 CHECK(fmt, opts);
625 return opts;
628 /** Return the currently configured options. */
629 or_options_t *
630 get_options(void)
632 tor_assert(global_options);
633 return global_options;
636 /** Change the current global options to contain <b>new_val</b> instead of
637 * their current value; take action based on the new value; free the old value
638 * as necessary. Returns 0 on success, -1 on failure.
641 set_options(or_options_t *new_val, char **msg)
643 or_options_t *old_options = global_options;
644 global_options = new_val;
645 /* Note that we pass the *old* options below, for comparison. It
646 * pulls the new options directly out of global_options. */
647 if (options_act_reversible(old_options, msg)<0) {
648 tor_assert(*msg);
649 global_options = old_options;
650 return -1;
652 if (options_act(old_options) < 0) { /* acting on the options failed. die. */
653 log_err(LD_BUG,
654 "Acting on config options left us in a broken state. Dying.");
655 exit(1);
658 config_free(&options_format, old_options);
660 return 0;
663 extern const char tor_git_revision[]; /* from tor_main.c */
665 /** The version of this Tor process, as parsed. */
666 static char *_version = NULL;
668 /** Return the current Tor version. */
669 const char *
670 get_version(void)
672 if (_version == NULL) {
673 if (strlen(tor_git_revision)) {
674 size_t len = strlen(VERSION)+strlen(tor_git_revision)+16;
675 _version = tor_malloc(len);
676 tor_snprintf(_version, len, "%s (git-%s)", VERSION, tor_git_revision);
677 } else {
678 _version = tor_strdup(VERSION);
681 return _version;
684 /** Release additional memory allocated in options
686 static void
687 or_options_free(or_options_t *options)
689 if (!options)
690 return;
692 routerset_free(options->_ExcludeExitNodesUnion);
693 config_free(&options_format, options);
696 /** Release all memory and resources held by global configuration structures.
698 void
699 config_free_all(void)
701 or_options_free(global_options);
702 global_options = NULL;
704 config_free(&state_format, global_state);
705 global_state = NULL;
707 config_free_lines(global_cmdline_options);
708 global_cmdline_options = NULL;
710 tor_free(torrc_fname);
711 tor_free(_version);
712 tor_free(global_dirfrontpagecontents);
715 /** Make <b>address</b> -- a piece of information related to our operation as
716 * a client -- safe to log according to the settings in options->SafeLogging,
717 * and return it.
719 * (We return "[scrubbed]" if SafeLogging is "1", and address otherwise.)
721 const char *
722 safe_str_client(const char *address)
724 tor_assert(address);
725 if (get_options()->_SafeLogging == SAFELOG_SCRUB_ALL)
726 return "[scrubbed]";
727 else
728 return address;
731 /** Make <b>address</b> -- a piece of information of unspecified sensitivity
732 * -- safe to log according to the settings in options->SafeLogging, and
733 * return it.
735 * (We return "[scrubbed]" if SafeLogging is anything besides "0", and address
736 * otherwise.)
738 const char *
739 safe_str(const char *address)
741 tor_assert(address);
742 if (get_options()->_SafeLogging != SAFELOG_SCRUB_NONE)
743 return "[scrubbed]";
744 else
745 return address;
748 /** Equivalent to escaped(safe_str_client(address)). See reentrancy note on
749 * escaped(): don't use this outside the main thread, or twice in the same
750 * log statement. */
751 const char *
752 escaped_safe_str_client(const char *address)
754 if (get_options()->_SafeLogging == SAFELOG_SCRUB_ALL)
755 return "[scrubbed]";
756 else
757 return escaped(address);
760 /** Equivalent to escaped(safe_str(address)). See reentrancy note on
761 * escaped(): don't use this outside the main thread, or twice in the same
762 * log statement. */
763 const char *
764 escaped_safe_str(const char *address)
766 if (get_options()->_SafeLogging != SAFELOG_SCRUB_NONE)
767 return "[scrubbed]";
768 else
769 return escaped(address);
772 /** Add the default directory authorities directly into the trusted dir list,
773 * but only add them insofar as they share bits with <b>type</b>. */
774 static void
775 add_default_trusted_dir_authorities(authority_type_t type)
777 int i;
778 const char *dirservers[] = {
779 "moria1 orport=9101 no-v2 "
780 "v3ident=D586D18309DED4CD6D57C18FDB97EFA96D330566 "
781 "128.31.0.39:9131 9695 DFC3 5FFE B861 329B 9F1A B04C 4639 7020 CE31",
782 "tor26 v1 orport=443 v3ident=14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4 "
783 "86.59.21.38:80 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D",
784 "dizum orport=443 v3ident=E8A9C45EDE6D711294FADF8E7951F4DE6CA56B58 "
785 "194.109.206.212:80 7EA6 EAD6 FD83 083C 538F 4403 8BBF A077 587D D755",
786 "Tonga orport=443 bridge no-v2 82.94.251.203:80 "
787 "4A0C CD2D DC79 9508 3D73 F5D6 6710 0C8A 5831 F16D",
788 "ides orport=9090 no-v2 v3ident=27B6B5996C426270A5C95488AA5BCEB6BCC86956 "
789 "216.224.124.114:9030 F397 038A DC51 3361 35E7 B80B D99C A384 4360 292B",
790 "gabelmoo orport=443 no-v2 "
791 "v3ident=ED03BB616EB2F60BEC80151114BB25CEF515B226 "
792 "212.112.245.170:80 F204 4413 DAC2 E02E 3D6B CF47 35A1 9BCA 1DE9 7281",
793 "dannenberg orport=443 no-v2 "
794 "v3ident=585769C78764D58426B8B52B6651A5A71137189A "
795 "193.23.244.244:80 7BE6 83E6 5D48 1413 21C5 ED92 F075 C553 64AC 7123",
796 "urras orport=80 no-v2 v3ident=80550987E1D626E3EBA5E5E75A458DE0626D088C "
797 "208.83.223.34:443 0AD3 FA88 4D18 F89E EA2D 89C0 1937 9E0E 7FD9 4417",
798 "maatuska orport=80 no-v2 "
799 "v3ident=49015F787433103580E3B66A1707A00E60F2D15B "
800 "213.115.239.118:443 BD6A 8292 55CB 08E6 6FBE 7D37 4836 3586 E46B 3810",
801 NULL
803 for (i=0; dirservers[i]; i++) {
804 if (parse_dir_server_line(dirservers[i], type, 0)<0) {
805 log_err(LD_BUG, "Couldn't parse internal dirserver line %s",
806 dirservers[i]);
811 /** Look at all the config options for using alternate directory
812 * authorities, and make sure none of them are broken. Also, warn the
813 * user if we changed any dangerous ones.
815 static int
816 validate_dir_authorities(or_options_t *options, or_options_t *old_options)
818 config_line_t *cl;
820 if (options->DirServers &&
821 (options->AlternateDirAuthority || options->AlternateBridgeAuthority ||
822 options->AlternateHSAuthority)) {
823 log_warn(LD_CONFIG,
824 "You cannot set both DirServers and Alternate*Authority.");
825 return -1;
828 /* do we want to complain to the user about being partitionable? */
829 if ((options->DirServers &&
830 (!old_options ||
831 !config_lines_eq(options->DirServers, old_options->DirServers))) ||
832 (options->AlternateDirAuthority &&
833 (!old_options ||
834 !config_lines_eq(options->AlternateDirAuthority,
835 old_options->AlternateDirAuthority)))) {
836 log_warn(LD_CONFIG,
837 "You have used DirServer or AlternateDirAuthority to "
838 "specify alternate directory authorities in "
839 "your configuration. This is potentially dangerous: it can "
840 "make you look different from all other Tor users, and hurt "
841 "your anonymity. Even if you've specified the same "
842 "authorities as Tor uses by default, the defaults could "
843 "change in the future. Be sure you know what you're doing.");
846 /* Now go through the four ways you can configure an alternate
847 * set of directory authorities, and make sure none are broken. */
848 for (cl = options->DirServers; cl; cl = cl->next)
849 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
850 return -1;
851 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
852 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
853 return -1;
854 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
855 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
856 return -1;
857 for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
858 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
859 return -1;
860 return 0;
863 /** Look at all the config options and assign new dir authorities
864 * as appropriate.
866 static int
867 consider_adding_dir_authorities(or_options_t *options,
868 or_options_t *old_options)
870 config_line_t *cl;
871 int need_to_update =
872 !smartlist_len(router_get_trusted_dir_servers()) || !old_options ||
873 !config_lines_eq(options->DirServers, old_options->DirServers) ||
874 !config_lines_eq(options->AlternateBridgeAuthority,
875 old_options->AlternateBridgeAuthority) ||
876 !config_lines_eq(options->AlternateDirAuthority,
877 old_options->AlternateDirAuthority) ||
878 !config_lines_eq(options->AlternateHSAuthority,
879 old_options->AlternateHSAuthority);
881 if (!need_to_update)
882 return 0; /* all done */
884 /* Start from a clean slate. */
885 clear_trusted_dir_servers();
887 if (!options->DirServers) {
888 /* then we may want some of the defaults */
889 authority_type_t type = NO_AUTHORITY;
890 if (!options->AlternateBridgeAuthority)
891 type |= BRIDGE_AUTHORITY;
892 if (!options->AlternateDirAuthority)
893 type |= V1_AUTHORITY | V2_AUTHORITY | V3_AUTHORITY;
894 if (!options->AlternateHSAuthority)
895 type |= HIDSERV_AUTHORITY;
896 add_default_trusted_dir_authorities(type);
899 for (cl = options->DirServers; cl; cl = cl->next)
900 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
901 return -1;
902 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
903 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
904 return -1;
905 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
906 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
907 return -1;
908 for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
909 if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
910 return -1;
911 return 0;
914 /** Fetch the active option list, and take actions based on it. All of the
915 * things we do should survive being done repeatedly. If present,
916 * <b>old_options</b> contains the previous value of the options.
918 * Return 0 if all goes well, return -1 if things went badly.
920 static int
921 options_act_reversible(or_options_t *old_options, char **msg)
923 smartlist_t *new_listeners = smartlist_create();
924 smartlist_t *replaced_listeners = smartlist_create();
925 static int libevent_initialized = 0;
926 or_options_t *options = get_options();
927 int running_tor = options->command == CMD_RUN_TOR;
928 int set_conn_limit = 0;
929 int r = -1;
930 int logs_marked = 0;
932 /* Daemonize _first_, since we only want to open most of this stuff in
933 * the subprocess. Libevent bases can't be reliably inherited across
934 * processes. */
935 if (running_tor && options->RunAsDaemon) {
936 /* No need to roll back, since you can't change the value. */
937 start_daemon();
940 #ifndef HAVE_SYS_UN_H
941 if (options->ControlSocket) {
942 *msg = tor_strdup("Unix domain sockets (ControlSocket) not supported"
943 " on this OS/with this build.");
944 goto rollback;
946 #endif
948 if (running_tor) {
949 /* We need to set the connection limit before we can open the listeners. */
950 if (set_max_file_descriptors((unsigned)options->ConnLimit,
951 &options->_ConnLimit) < 0) {
952 *msg = tor_strdup("Problem with ConnLimit value. See logs for details.");
953 goto rollback;
955 set_conn_limit = 1;
957 /* Set up libevent. (We need to do this before we can register the
958 * listeners as listeners.) */
959 if (running_tor && !libevent_initialized) {
960 init_libevent();
961 libevent_initialized = 1;
964 /* Launch the listeners. (We do this before we setuid, so we can bind to
965 * ports under 1024.) We don't want to rebind if we're hibernating. */
966 if (!we_are_hibernating()) {
967 if (retry_all_listeners(replaced_listeners, new_listeners) < 0) {
968 *msg = tor_strdup("Failed to bind one of the listener ports.");
969 goto rollback;
974 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
975 /* Open /dev/pf before dropping privileges. */
976 if (options->TransPort) {
977 if (get_pf_socket() < 0) {
978 *msg = tor_strdup("Unable to open /dev/pf for transparent proxy.");
979 goto rollback;
982 #endif
984 /* Attempt to lock all current and future memory with mlockall() only once */
985 if (options->DisableAllSwap) {
986 if (tor_mlockall() == -1) {
987 *msg = tor_strdup("DisableAllSwap failure. Do you have proper "
988 "permissions?");
989 goto done;
993 /* Setuid/setgid as appropriate */
994 if (options->User) {
995 if (switch_id(options->User) != 0) {
996 /* No need to roll back, since you can't change the value. */
997 *msg = tor_strdup("Problem with User value. See logs for details.");
998 goto done;
1002 /* Ensure data directory is private; create if possible. */
1003 if (check_private_dir(options->DataDirectory,
1004 running_tor ? CPD_CREATE : CPD_CHECK)<0) {
1005 tor_asprintf(msg,
1006 "Couldn't access/create private data directory \"%s\"",
1007 options->DataDirectory);
1008 goto done;
1009 /* No need to roll back, since you can't change the value. */
1012 if (directory_caches_v2_dir_info(options)) {
1013 size_t len = strlen(options->DataDirectory)+32;
1014 char *fn = tor_malloc(len);
1015 tor_snprintf(fn, len, "%s"PATH_SEPARATOR"cached-status",
1016 options->DataDirectory);
1017 if (check_private_dir(fn, running_tor ? CPD_CREATE : CPD_CHECK) < 0) {
1018 tor_asprintf(msg,
1019 "Couldn't access/create private data directory \"%s\"", fn);
1020 tor_free(fn);
1021 goto done;
1023 tor_free(fn);
1026 /* Bail out at this point if we're not going to be a client or server:
1027 * we don't run Tor itself. */
1028 if (!running_tor)
1029 goto commit;
1031 mark_logs_temp(); /* Close current logs once new logs are open. */
1032 logs_marked = 1;
1033 if (options_init_logs(options, 0)<0) { /* Configure the log(s) */
1034 *msg = tor_strdup("Failed to init Log options. See logs for details.");
1035 goto rollback;
1038 commit:
1039 r = 0;
1040 if (logs_marked) {
1041 log_severity_list_t *severity =
1042 tor_malloc_zero(sizeof(log_severity_list_t));
1043 close_temp_logs();
1044 add_callback_log(severity, control_event_logmsg);
1045 control_adjust_event_log_severity();
1046 tor_free(severity);
1048 SMARTLIST_FOREACH(replaced_listeners, connection_t *, conn,
1050 log_notice(LD_NET, "Closing old %s on %s:%d",
1051 conn_type_to_string(conn->type), conn->address, conn->port);
1052 connection_close_immediate(conn);
1053 connection_mark_for_close(conn);
1055 goto done;
1057 rollback:
1058 r = -1;
1059 tor_assert(*msg);
1061 if (logs_marked) {
1062 rollback_log_changes();
1063 control_adjust_event_log_severity();
1066 if (set_conn_limit && old_options)
1067 set_max_file_descriptors((unsigned)old_options->ConnLimit,
1068 &options->_ConnLimit);
1070 SMARTLIST_FOREACH(new_listeners, connection_t *, conn,
1072 log_notice(LD_NET, "Closing partially-constructed listener %s on %s:%d",
1073 conn_type_to_string(conn->type), conn->address, conn->port);
1074 connection_close_immediate(conn);
1075 connection_mark_for_close(conn);
1078 done:
1079 smartlist_free(new_listeners);
1080 smartlist_free(replaced_listeners);
1081 return r;
1084 /** If we need to have a GEOIP ip-to-country map to run with our configured
1085 * options, return 1 and set *<b>reason_out</b> to a description of why. */
1087 options_need_geoip_info(or_options_t *options, const char **reason_out)
1089 int bridge_usage =
1090 options->BridgeRelay && options->BridgeRecordUsageByCountry;
1091 int routerset_usage =
1092 routerset_needs_geoip(options->EntryNodes) ||
1093 routerset_needs_geoip(options->ExitNodes) ||
1094 routerset_needs_geoip(options->ExcludeExitNodes) ||
1095 routerset_needs_geoip(options->ExcludeNodes);
1097 if (routerset_usage && reason_out) {
1098 *reason_out = "We've been configured to use (or avoid) nodes in certain "
1099 "countries, and we need GEOIP information to figure out which ones they "
1100 "are.";
1101 } else if (bridge_usage && reason_out) {
1102 *reason_out = "We've been configured to see which countries can access "
1103 "us as a bridge, and we need GEOIP information to tell which countries "
1104 "clients are in.";
1106 return bridge_usage || routerset_usage;
1109 /** Return the bandwidthrate that we are going to report to the authorities
1110 * based on the config options. */
1111 uint32_t
1112 get_effective_bwrate(or_options_t *options)
1114 uint64_t bw = options->BandwidthRate;
1115 if (bw > options->MaxAdvertisedBandwidth)
1116 bw = options->MaxAdvertisedBandwidth;
1117 if (options->RelayBandwidthRate > 0 && bw > options->RelayBandwidthRate)
1118 bw = options->RelayBandwidthRate;
1119 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1120 return (uint32_t)bw;
1123 /** Return the bandwidthburst that we are going to report to the authorities
1124 * based on the config options. */
1125 uint32_t
1126 get_effective_bwburst(or_options_t *options)
1128 uint64_t bw = options->BandwidthBurst;
1129 if (options->RelayBandwidthBurst > 0 && bw > options->RelayBandwidthBurst)
1130 bw = options->RelayBandwidthBurst;
1131 /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1132 return (uint32_t)bw;
1135 /** Fetch the active option list, and take actions based on it. All of the
1136 * things we do should survive being done repeatedly. If present,
1137 * <b>old_options</b> contains the previous value of the options.
1139 * Return 0 if all goes well, return -1 if it's time to die.
1141 * Note: We haven't moved all the "act on new configuration" logic
1142 * here yet. Some is still in do_hup() and other places.
1144 static int
1145 options_act(or_options_t *old_options)
1147 config_line_t *cl;
1148 or_options_t *options = get_options();
1149 int running_tor = options->command == CMD_RUN_TOR;
1150 char *msg;
1152 if (running_tor && !have_lockfile()) {
1153 if (try_locking(options, 1) < 0)
1154 return -1;
1157 if (consider_adding_dir_authorities(options, old_options) < 0)
1158 return -1;
1160 if (options->Bridges) {
1161 clear_bridge_list();
1162 for (cl = options->Bridges; cl; cl = cl->next) {
1163 if (parse_bridge_line(cl->value, 0)<0) {
1164 log_warn(LD_BUG,
1165 "Previously validated Bridge line could not be added!");
1166 return -1;
1171 if (running_tor && rend_config_services(options, 0)<0) {
1172 log_warn(LD_BUG,
1173 "Previously validated hidden services line could not be added!");
1174 return -1;
1177 if (running_tor && rend_parse_service_authorization(options, 0) < 0) {
1178 log_warn(LD_BUG, "Previously validated client authorization for "
1179 "hidden services could not be added!");
1180 return -1;
1183 /* Load state */
1184 if (! global_state && running_tor) {
1185 if (or_state_load())
1186 return -1;
1187 rep_hist_load_mtbf_data(time(NULL));
1190 /* Bail out at this point if we're not going to be a client or server:
1191 * we want to not fork, and to log stuff to stderr. */
1192 if (!running_tor)
1193 return 0;
1195 /* Finish backgrounding the process */
1196 if (options->RunAsDaemon) {
1197 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
1198 finish_daemon(options->DataDirectory);
1201 /* Write our PID to the PID file. If we do not have write permissions we
1202 * will log a warning */
1203 if (options->PidFile)
1204 write_pidfile(options->PidFile);
1206 /* Register addressmap directives */
1207 config_register_addressmaps(options);
1208 parse_virtual_addr_network(options->VirtualAddrNetwork, 0, &msg);
1210 /* Update address policies. */
1211 if (policies_parse_from_options(options) < 0) {
1212 /* This should be impossible, but let's be sure. */
1213 log_warn(LD_BUG,"Error parsing already-validated policy options.");
1214 return -1;
1217 if (init_cookie_authentication(options->CookieAuthentication) < 0) {
1218 log_warn(LD_CONFIG,"Error creating cookie authentication file.");
1219 return -1;
1222 /* reload keys as needed for rendezvous services. */
1223 if (rend_service_load_keys()<0) {
1224 log_warn(LD_GENERAL,"Error loading rendezvous service keys");
1225 return -1;
1228 /* Set up accounting */
1229 if (accounting_parse_options(options, 0)<0) {
1230 log_warn(LD_CONFIG,"Error in accounting options");
1231 return -1;
1233 if (accounting_is_enabled(options))
1234 configure_accounting(time(NULL));
1236 /* parse RefuseUnknownExits tristate */
1237 if (!strcmp(options->RefuseUnknownExits, "0"))
1238 options->RefuseUnknownExits_ = 0;
1239 else if (!strcmp(options->RefuseUnknownExits, "1"))
1240 options->RefuseUnknownExits_ = 1;
1241 else if (!strcmp(options->RefuseUnknownExits, "auto"))
1242 options->RefuseUnknownExits_ = -1;
1243 else {
1244 /* Should have caught this in options_validate */
1245 return -1;
1248 /* Change the cell EWMA settings */
1249 cell_ewma_set_scale_factor(options, networkstatus_get_latest_consensus());
1251 /* Check for transitions that need action. */
1252 if (old_options) {
1254 if ((options->UseEntryGuards && !old_options->UseEntryGuards) ||
1255 (options->ExcludeNodes &&
1256 !routerset_equal(old_options->ExcludeNodes,options->ExcludeNodes)) ||
1257 (options->ExcludeExitNodes &&
1258 !routerset_equal(old_options->ExcludeExitNodes,
1259 options->ExcludeExitNodes)) ||
1260 (options->EntryNodes &&
1261 !routerset_equal(old_options->EntryNodes, options->EntryNodes)) ||
1262 (options->ExitNodes &&
1263 !routerset_equal(old_options->ExitNodes, options->ExitNodes)) ||
1264 options->StrictNodes != old_options->StrictNodes) {
1265 log_info(LD_CIRC,
1266 "Changed to using entry guards, or changed preferred or "
1267 "excluded node lists. Abandoning previous circuits.");
1268 circuit_mark_all_unused_circs();
1269 circuit_expire_all_dirty_circs();
1272 /* How long should we delay counting bridge stats after becoming a bridge?
1273 * We use this so we don't count people who used our bridge thinking it is
1274 * a relay. If you change this, don't forget to change the log message
1275 * below. It's 4 hours (the time it takes to stop being used by clients)
1276 * plus some extra time for clock skew. */
1277 #define RELAY_BRIDGE_STATS_DELAY (6 * 60 * 60)
1279 if (! bool_eq(options->BridgeRelay, old_options->BridgeRelay)) {
1280 int was_relay = 0;
1281 if (options->BridgeRelay) {
1282 time_t int_start = time(NULL);
1283 if (old_options->ORPort == options->ORPort) {
1284 int_start += RELAY_BRIDGE_STATS_DELAY;
1285 was_relay = 1;
1287 geoip_bridge_stats_init(int_start);
1288 log_info(LD_CONFIG, "We are acting as a bridge now. Starting new "
1289 "GeoIP stats interval%s.", was_relay ? " in 6 "
1290 "hours from now" : "");
1291 } else {
1292 geoip_bridge_stats_term();
1293 log_info(LD_GENERAL, "We are no longer acting as a bridge. "
1294 "Forgetting GeoIP stats.");
1298 if (options_transition_affects_workers(old_options, options)) {
1299 log_info(LD_GENERAL,
1300 "Worker-related options changed. Rotating workers.");
1301 if (server_mode(options) && !server_mode(old_options)) {
1302 if (init_keys() < 0) {
1303 log_warn(LD_BUG,"Error initializing keys; exiting");
1304 return -1;
1306 ip_address_changed(0);
1307 if (can_complete_circuit || !any_predicted_circuits(time(NULL)))
1308 inform_testing_reachability();
1310 cpuworkers_rotate();
1311 if (dns_reset())
1312 return -1;
1313 } else {
1314 if (dns_reset())
1315 return -1;
1318 if (options->V3AuthoritativeDir && !old_options->V3AuthoritativeDir)
1319 init_keys();
1321 if (options->PerConnBWRate != old_options->PerConnBWRate ||
1322 options->PerConnBWBurst != old_options->PerConnBWBurst)
1323 connection_or_update_token_buckets(get_connection_array(), options);
1326 /* Maybe load geoip file */
1327 if (options->GeoIPFile &&
1328 ((!old_options || !opt_streq(old_options->GeoIPFile, options->GeoIPFile))
1329 || !geoip_is_loaded())) {
1330 /* XXXX Don't use this "<default>" junk; make our filename options
1331 * understand prefixes somehow. -NM */
1332 /* XXXX021 Reload GeoIPFile on SIGHUP. -NM */
1333 char *actual_fname = tor_strdup(options->GeoIPFile);
1334 #ifdef WIN32
1335 if (!strcmp(actual_fname, "<default>")) {
1336 const char *conf_root = get_windows_conf_root();
1337 size_t len = strlen(conf_root)+16;
1338 tor_free(actual_fname);
1339 actual_fname = tor_malloc(len+1);
1340 tor_snprintf(actual_fname, len, "%s\\geoip", conf_root);
1342 #endif
1343 geoip_load_file(actual_fname, options);
1344 tor_free(actual_fname);
1347 if (options->DirReqStatistics && !geoip_is_loaded()) {
1348 /* Check if GeoIP database could be loaded. */
1349 log_warn(LD_CONFIG, "Configured to measure directory request "
1350 "statistics, but no GeoIP database found!");
1351 return -1;
1354 if (options->EntryStatistics) {
1355 if (should_record_bridge_info(options)) {
1356 /* Don't allow measuring statistics on entry guards when configured
1357 * as bridge. */
1358 log_warn(LD_CONFIG, "Bridges cannot be configured to measure "
1359 "additional GeoIP statistics as entry guards.");
1360 return -1;
1361 } else if (!geoip_is_loaded()) {
1362 /* Check if GeoIP database could be loaded. */
1363 log_warn(LD_CONFIG, "Configured to measure entry node statistics, "
1364 "but no GeoIP database found!");
1365 return -1;
1369 if (options->CellStatistics || options->DirReqStatistics ||
1370 options->EntryStatistics || options->ExitPortStatistics) {
1371 time_t now = time(NULL);
1372 if ((!old_options || !old_options->CellStatistics) &&
1373 options->CellStatistics)
1374 rep_hist_buffer_stats_init(now);
1375 if ((!old_options || !old_options->DirReqStatistics) &&
1376 options->DirReqStatistics)
1377 geoip_dirreq_stats_init(now);
1378 if ((!old_options || !old_options->EntryStatistics) &&
1379 options->EntryStatistics)
1380 geoip_entry_stats_init(now);
1381 if ((!old_options || !old_options->ExitPortStatistics) &&
1382 options->ExitPortStatistics)
1383 rep_hist_exit_stats_init(now);
1384 if (!old_options)
1385 log_notice(LD_CONFIG, "Configured to measure statistics. Look for "
1386 "the *-stats files that will first be written to the "
1387 "data directory in 24 hours from now.");
1390 if (old_options && old_options->CellStatistics &&
1391 !options->CellStatistics)
1392 rep_hist_buffer_stats_term();
1393 if (old_options && old_options->DirReqStatistics &&
1394 !options->DirReqStatistics)
1395 geoip_dirreq_stats_term();
1396 if (old_options && old_options->EntryStatistics &&
1397 !options->EntryStatistics)
1398 geoip_entry_stats_term();
1399 if (old_options && old_options->ExitPortStatistics &&
1400 !options->ExitPortStatistics)
1401 rep_hist_exit_stats_term();
1403 /* Check if we need to parse and add the EntryNodes config option. */
1404 if (options->EntryNodes &&
1405 (!old_options ||
1406 (!routerset_equal(old_options->EntryNodes,options->EntryNodes))))
1407 entry_nodes_should_be_added();
1409 /* Since our options changed, we might need to regenerate and upload our
1410 * server descriptor.
1412 if (!old_options ||
1413 options_transition_affects_descriptor(old_options, options))
1414 mark_my_descriptor_dirty();
1416 /* We may need to reschedule some directory stuff if our status changed. */
1417 if (old_options) {
1418 if (authdir_mode_v3(options) && !authdir_mode_v3(old_options))
1419 dirvote_recalculate_timing(options, time(NULL));
1420 if (!bool_eq(directory_fetches_dir_info_early(options),
1421 directory_fetches_dir_info_early(old_options)) ||
1422 !bool_eq(directory_fetches_dir_info_later(options),
1423 directory_fetches_dir_info_later(old_options))) {
1424 /* Make sure update_router_have_min_dir_info gets called. */
1425 router_dir_info_changed();
1426 /* We might need to download a new consensus status later or sooner than
1427 * we had expected. */
1428 update_consensus_networkstatus_fetch_time(time(NULL));
1432 /* Load the webpage we're going to serve every time someone asks for '/' on
1433 our DirPort. */
1434 tor_free(global_dirfrontpagecontents);
1435 if (options->DirPortFrontPage) {
1436 global_dirfrontpagecontents =
1437 read_file_to_str(options->DirPortFrontPage, 0, NULL);
1438 if (!global_dirfrontpagecontents) {
1439 log_warn(LD_CONFIG,
1440 "DirPortFrontPage file '%s' not found. Continuing anyway.",
1441 options->DirPortFrontPage);
1445 return 0;
1449 * Functions to parse config options
1452 /** If <b>option</b> is an official abbreviation for a longer option,
1453 * return the longer option. Otherwise return <b>option</b>.
1454 * If <b>command_line</b> is set, apply all abbreviations. Otherwise, only
1455 * apply abbreviations that work for the config file and the command line.
1456 * If <b>warn_obsolete</b> is set, warn about deprecated names. */
1457 static const char *
1458 expand_abbrev(config_format_t *fmt, const char *option, int command_line,
1459 int warn_obsolete)
1461 int i;
1462 if (! fmt->abbrevs)
1463 return option;
1464 for (i=0; fmt->abbrevs[i].abbreviated; ++i) {
1465 /* Abbreviations are case insensitive. */
1466 if (!strcasecmp(option,fmt->abbrevs[i].abbreviated) &&
1467 (command_line || !fmt->abbrevs[i].commandline_only)) {
1468 if (warn_obsolete && fmt->abbrevs[i].warn) {
1469 log_warn(LD_CONFIG,
1470 "The configuration option '%s' is deprecated; "
1471 "use '%s' instead.",
1472 fmt->abbrevs[i].abbreviated,
1473 fmt->abbrevs[i].full);
1475 /* Keep going through the list in case we want to rewrite it more.
1476 * (We could imagine recursing here, but I don't want to get the
1477 * user into an infinite loop if we craft our list wrong.) */
1478 option = fmt->abbrevs[i].full;
1481 return option;
1484 /** Helper: Read a list of configuration options from the command line.
1485 * If successful, put them in *<b>result</b> and return 0, and return
1486 * -1 and leave *<b>result</b> alone. */
1487 static int
1488 config_get_commandlines(int argc, char **argv, config_line_t **result)
1490 config_line_t *front = NULL;
1491 config_line_t **new = &front;
1492 char *s;
1493 int i = 1;
1495 while (i < argc) {
1496 if (!strcmp(argv[i],"-f") ||
1497 !strcmp(argv[i],"--hash-password")) {
1498 i += 2; /* command-line option with argument. ignore them. */
1499 continue;
1500 } else if (!strcmp(argv[i],"--list-fingerprint") ||
1501 !strcmp(argv[i],"--verify-config") ||
1502 !strcmp(argv[i],"--ignore-missing-torrc") ||
1503 !strcmp(argv[i],"--quiet") ||
1504 !strcmp(argv[i],"--hush")) {
1505 i += 1; /* command-line option. ignore it. */
1506 continue;
1507 } else if (!strcmp(argv[i],"--nt-service") ||
1508 !strcmp(argv[i],"-nt-service")) {
1509 i += 1;
1510 continue;
1513 if (i == argc-1) {
1514 log_warn(LD_CONFIG,"Command-line option '%s' with no value. Failing.",
1515 argv[i]);
1516 config_free_lines(front);
1517 return -1;
1520 *new = tor_malloc_zero(sizeof(config_line_t));
1521 s = argv[i];
1523 /* Each keyword may be prefixed with one or two dashes. */
1524 if (*s == '-')
1525 s++;
1526 if (*s == '-')
1527 s++;
1529 (*new)->key = tor_strdup(expand_abbrev(&options_format, s, 1, 1));
1530 (*new)->value = tor_strdup(argv[i+1]);
1531 (*new)->next = NULL;
1532 log(LOG_DEBUG, LD_CONFIG, "command line: parsed keyword '%s', value '%s'",
1533 (*new)->key, (*new)->value);
1535 new = &((*new)->next);
1536 i += 2;
1538 *result = front;
1539 return 0;
1542 /** Helper: allocate a new configuration option mapping 'key' to 'val',
1543 * append it to *<b>lst</b>. */
1544 static void
1545 config_line_append(config_line_t **lst,
1546 const char *key,
1547 const char *val)
1549 config_line_t *newline;
1551 newline = tor_malloc(sizeof(config_line_t));
1552 newline->key = tor_strdup(key);
1553 newline->value = tor_strdup(val);
1554 newline->next = NULL;
1555 while (*lst)
1556 lst = &((*lst)->next);
1558 (*lst) = newline;
1561 /** Helper: parse the config string and strdup into key/value
1562 * strings. Set *result to the list, or NULL if parsing the string
1563 * failed. Return 0 on success, -1 on failure. Warn and ignore any
1564 * misformatted lines. */
1566 config_get_lines(const char *string, config_line_t **result)
1568 config_line_t *list = NULL, **next;
1569 char *k, *v;
1571 next = &list;
1572 do {
1573 k = v = NULL;
1574 string = parse_config_line_from_str(string, &k, &v);
1575 if (!string) {
1576 config_free_lines(list);
1577 tor_free(k);
1578 tor_free(v);
1579 return -1;
1581 if (k && v) {
1582 /* This list can get long, so we keep a pointer to the end of it
1583 * rather than using config_line_append over and over and getting
1584 * n^2 performance. */
1585 *next = tor_malloc(sizeof(config_line_t));
1586 (*next)->key = k;
1587 (*next)->value = v;
1588 (*next)->next = NULL;
1589 next = &((*next)->next);
1590 } else {
1591 tor_free(k);
1592 tor_free(v);
1594 } while (*string);
1596 *result = list;
1597 return 0;
1601 * Free all the configuration lines on the linked list <b>front</b>.
1603 void
1604 config_free_lines(config_line_t *front)
1606 config_line_t *tmp;
1608 while (front) {
1609 tmp = front;
1610 front = tmp->next;
1612 tor_free(tmp->key);
1613 tor_free(tmp->value);
1614 tor_free(tmp);
1618 /** If <b>key</b> is a configuration option, return the corresponding
1619 * config_var_t. Otherwise, if <b>key</b> is a non-standard abbreviation,
1620 * warn, and return the corresponding config_var_t. Otherwise return NULL.
1622 static config_var_t *
1623 config_find_option(config_format_t *fmt, const char *key)
1625 int i;
1626 size_t keylen = strlen(key);
1627 if (!keylen)
1628 return NULL; /* if they say "--" on the command line, it's not an option */
1629 /* First, check for an exact (case-insensitive) match */
1630 for (i=0; fmt->vars[i].name; ++i) {
1631 if (!strcasecmp(key, fmt->vars[i].name)) {
1632 return &fmt->vars[i];
1635 /* If none, check for an abbreviated match */
1636 for (i=0; fmt->vars[i].name; ++i) {
1637 if (!strncasecmp(key, fmt->vars[i].name, keylen)) {
1638 log_warn(LD_CONFIG, "The abbreviation '%s' is deprecated. "
1639 "Please use '%s' instead",
1640 key, fmt->vars[i].name);
1641 return &fmt->vars[i];
1644 /* Okay, unrecognized option */
1645 return NULL;
1648 /** Return the number of option entries in <b>fmt</b>. */
1649 static int
1650 config_count_options(config_format_t *fmt)
1652 int i;
1653 for (i=0; fmt->vars[i].name; ++i)
1655 return i;
1659 * Functions to assign config options.
1662 /** <b>c</b>-\>key is known to be a real key. Update <b>options</b>
1663 * with <b>c</b>-\>value and return 0, or return -1 if bad value.
1665 * Called from config_assign_line() and option_reset().
1667 static int
1668 config_assign_value(config_format_t *fmt, or_options_t *options,
1669 config_line_t *c, char **msg)
1671 int i, ok;
1672 config_var_t *var;
1673 void *lvalue;
1675 CHECK(fmt, options);
1677 var = config_find_option(fmt, c->key);
1678 tor_assert(var);
1680 lvalue = STRUCT_VAR_P(options, var->var_offset);
1682 switch (var->type) {
1684 case CONFIG_TYPE_UINT:
1685 i = (int)tor_parse_long(c->value, 10, 0, INT_MAX, &ok, NULL);
1686 if (!ok) {
1687 tor_asprintf(msg,
1688 "Int keyword '%s %s' is malformed or out of bounds.",
1689 c->key, c->value);
1690 return -1;
1692 *(int *)lvalue = i;
1693 break;
1695 case CONFIG_TYPE_INTERVAL: {
1696 i = config_parse_interval(c->value, &ok);
1697 if (!ok) {
1698 tor_asprintf(msg,
1699 "Interval '%s %s' is malformed or out of bounds.",
1700 c->key, c->value);
1701 return -1;
1703 *(int *)lvalue = i;
1704 break;
1707 case CONFIG_TYPE_MEMUNIT: {
1708 uint64_t u64 = config_parse_memunit(c->value, &ok);
1709 if (!ok) {
1710 tor_asprintf(msg,
1711 "Value '%s %s' is malformed or out of bounds.",
1712 c->key, c->value);
1713 return -1;
1715 *(uint64_t *)lvalue = u64;
1716 break;
1719 case CONFIG_TYPE_BOOL:
1720 i = (int)tor_parse_long(c->value, 10, 0, 1, &ok, NULL);
1721 if (!ok) {
1722 tor_asprintf(msg,
1723 "Boolean '%s %s' expects 0 or 1.",
1724 c->key, c->value);
1725 return -1;
1727 *(int *)lvalue = i;
1728 break;
1730 case CONFIG_TYPE_STRING:
1731 case CONFIG_TYPE_FILENAME:
1732 tor_free(*(char **)lvalue);
1733 *(char **)lvalue = tor_strdup(c->value);
1734 break;
1736 case CONFIG_TYPE_DOUBLE:
1737 *(double *)lvalue = atof(c->value);
1738 break;
1740 case CONFIG_TYPE_ISOTIME:
1741 if (parse_iso_time(c->value, (time_t *)lvalue)) {
1742 tor_asprintf(msg,
1743 "Invalid time '%s' for keyword '%s'", c->value, c->key);
1744 return -1;
1746 break;
1748 case CONFIG_TYPE_ROUTERSET:
1749 if (*(routerset_t**)lvalue) {
1750 routerset_free(*(routerset_t**)lvalue);
1752 *(routerset_t**)lvalue = routerset_new();
1753 if (routerset_parse(*(routerset_t**)lvalue, c->value, c->key)<0) {
1754 tor_asprintf(msg, "Invalid exit list '%s' for option '%s'",
1755 c->value, c->key);
1756 return -1;
1758 break;
1760 case CONFIG_TYPE_CSV:
1761 if (*(smartlist_t**)lvalue) {
1762 SMARTLIST_FOREACH(*(smartlist_t**)lvalue, char *, cp, tor_free(cp));
1763 smartlist_clear(*(smartlist_t**)lvalue);
1764 } else {
1765 *(smartlist_t**)lvalue = smartlist_create();
1768 smartlist_split_string(*(smartlist_t**)lvalue, c->value, ",",
1769 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1770 break;
1772 case CONFIG_TYPE_LINELIST:
1773 case CONFIG_TYPE_LINELIST_S:
1774 config_line_append((config_line_t**)lvalue, c->key, c->value);
1775 break;
1776 case CONFIG_TYPE_OBSOLETE:
1777 log_warn(LD_CONFIG, "Skipping obsolete configuration option '%s'", c->key);
1778 break;
1779 case CONFIG_TYPE_LINELIST_V:
1780 tor_asprintf(msg,
1781 "You may not provide a value for virtual option '%s'", c->key);
1782 return -1;
1783 default:
1784 tor_assert(0);
1785 break;
1787 return 0;
1790 /** If <b>c</b> is a syntactically valid configuration line, update
1791 * <b>options</b> with its value and return 0. Otherwise return -1 for bad
1792 * key, -2 for bad value.
1794 * If <b>clear_first</b> is set, clear the value first. Then if
1795 * <b>use_defaults</b> is set, set the value to the default.
1797 * Called from config_assign().
1799 static int
1800 config_assign_line(config_format_t *fmt, or_options_t *options,
1801 config_line_t *c, int use_defaults,
1802 int clear_first, bitarray_t *options_seen, char **msg)
1804 config_var_t *var;
1806 CHECK(fmt, options);
1808 var = config_find_option(fmt, c->key);
1809 if (!var) {
1810 if (fmt->extra) {
1811 void *lvalue = STRUCT_VAR_P(options, fmt->extra->var_offset);
1812 log_info(LD_CONFIG,
1813 "Found unrecognized option '%s'; saving it.", c->key);
1814 config_line_append((config_line_t**)lvalue, c->key, c->value);
1815 return 0;
1816 } else {
1817 tor_asprintf(msg,
1818 "Unknown option '%s'. Failing.", c->key);
1819 return -1;
1823 /* Put keyword into canonical case. */
1824 if (strcmp(var->name, c->key)) {
1825 tor_free(c->key);
1826 c->key = tor_strdup(var->name);
1829 if (!strlen(c->value)) {
1830 /* reset or clear it, then return */
1831 if (!clear_first) {
1832 if (var->type == CONFIG_TYPE_LINELIST ||
1833 var->type == CONFIG_TYPE_LINELIST_S) {
1834 /* We got an empty linelist from the torrc or command line.
1835 As a special case, call this an error. Warn and ignore. */
1836 log_warn(LD_CONFIG,
1837 "Linelist option '%s' has no value. Skipping.", c->key);
1838 } else { /* not already cleared */
1839 option_reset(fmt, options, var, use_defaults);
1842 return 0;
1845 if (options_seen && (var->type != CONFIG_TYPE_LINELIST &&
1846 var->type != CONFIG_TYPE_LINELIST_S)) {
1847 /* We're tracking which options we've seen, and this option is not
1848 * supposed to occur more than once. */
1849 int var_index = (int)(var - fmt->vars);
1850 if (bitarray_is_set(options_seen, var_index)) {
1851 log_warn(LD_CONFIG, "Option '%s' used more than once; all but the last "
1852 "value will be ignored.", var->name);
1854 bitarray_set(options_seen, var_index);
1857 if (config_assign_value(fmt, options, c, msg) < 0)
1858 return -2;
1859 return 0;
1862 /** Restore the option named <b>key</b> in options to its default value.
1863 * Called from config_assign(). */
1864 static void
1865 config_reset_line(config_format_t *fmt, or_options_t *options,
1866 const char *key, int use_defaults)
1868 config_var_t *var;
1870 CHECK(fmt, options);
1872 var = config_find_option(fmt, key);
1873 if (!var)
1874 return; /* give error on next pass. */
1876 option_reset(fmt, options, var, use_defaults);
1879 /** Return true iff key is a valid configuration option. */
1881 option_is_recognized(const char *key)
1883 config_var_t *var = config_find_option(&options_format, key);
1884 return (var != NULL);
1887 /** Return the canonical name of a configuration option, or NULL
1888 * if no such option exists. */
1889 const char *
1890 option_get_canonical_name(const char *key)
1892 config_var_t *var = config_find_option(&options_format, key);
1893 return var ? var->name : NULL;
1896 /** Return a canonical list of the options assigned for key.
1898 config_line_t *
1899 option_get_assignment(or_options_t *options, const char *key)
1901 return get_assigned_option(&options_format, options, key, 1);
1904 /** Return true iff value needs to be quoted and escaped to be used in
1905 * a configuration file. */
1906 static int
1907 config_value_needs_escape(const char *value)
1909 if (*value == '\"')
1910 return 1;
1911 while (*value) {
1912 switch (*value)
1914 case '\r':
1915 case '\n':
1916 case '#':
1917 /* Note: quotes and backspaces need special handling when we are using
1918 * quotes, not otherwise, so they don't trigger escaping on their
1919 * own. */
1920 return 1;
1921 default:
1922 if (!TOR_ISPRINT(*value))
1923 return 1;
1925 ++value;
1927 return 0;
1930 /** Return a newly allocated deep copy of the lines in <b>inp</b>. */
1931 static config_line_t *
1932 config_lines_dup(const config_line_t *inp)
1934 config_line_t *result = NULL;
1935 config_line_t **next_out = &result;
1936 while (inp) {
1937 *next_out = tor_malloc(sizeof(config_line_t));
1938 (*next_out)->key = tor_strdup(inp->key);
1939 (*next_out)->value = tor_strdup(inp->value);
1940 inp = inp->next;
1941 next_out = &((*next_out)->next);
1943 (*next_out) = NULL;
1944 return result;
1947 /** Return newly allocated line or lines corresponding to <b>key</b> in the
1948 * configuration <b>options</b>. If <b>escape_val</b> is true and a
1949 * value needs to be quoted before it's put in a config file, quote and
1950 * escape that value. Return NULL if no such key exists. */
1951 static config_line_t *
1952 get_assigned_option(config_format_t *fmt, void *options,
1953 const char *key, int escape_val)
1955 config_var_t *var;
1956 const void *value;
1957 config_line_t *result;
1958 tor_assert(options && key);
1960 CHECK(fmt, options);
1962 var = config_find_option(fmt, key);
1963 if (!var) {
1964 log_warn(LD_CONFIG, "Unknown option '%s'. Failing.", key);
1965 return NULL;
1967 value = STRUCT_VAR_P(options, var->var_offset);
1969 result = tor_malloc_zero(sizeof(config_line_t));
1970 result->key = tor_strdup(var->name);
1971 switch (var->type)
1973 case CONFIG_TYPE_STRING:
1974 case CONFIG_TYPE_FILENAME:
1975 if (*(char**)value) {
1976 result->value = tor_strdup(*(char**)value);
1977 } else {
1978 tor_free(result->key);
1979 tor_free(result);
1980 return NULL;
1982 break;
1983 case CONFIG_TYPE_ISOTIME:
1984 if (*(time_t*)value) {
1985 result->value = tor_malloc(ISO_TIME_LEN+1);
1986 format_iso_time(result->value, *(time_t*)value);
1987 } else {
1988 tor_free(result->key);
1989 tor_free(result);
1991 escape_val = 0; /* Can't need escape. */
1992 break;
1993 case CONFIG_TYPE_INTERVAL:
1994 case CONFIG_TYPE_UINT:
1995 /* This means every or_options_t uint or bool element
1996 * needs to be an int. Not, say, a uint16_t or char. */
1997 tor_asprintf(&result->value, "%d", *(int*)value);
1998 escape_val = 0; /* Can't need escape. */
1999 break;
2000 case CONFIG_TYPE_MEMUNIT:
2001 tor_asprintf(&result->value, U64_FORMAT,
2002 U64_PRINTF_ARG(*(uint64_t*)value));
2003 escape_val = 0; /* Can't need escape. */
2004 break;
2005 case CONFIG_TYPE_DOUBLE:
2006 tor_asprintf(&result->value, "%f", *(double*)value);
2007 escape_val = 0; /* Can't need escape. */
2008 break;
2009 case CONFIG_TYPE_BOOL:
2010 result->value = tor_strdup(*(int*)value ? "1" : "0");
2011 escape_val = 0; /* Can't need escape. */
2012 break;
2013 case CONFIG_TYPE_ROUTERSET:
2014 result->value = routerset_to_string(*(routerset_t**)value);
2015 break;
2016 case CONFIG_TYPE_CSV:
2017 if (*(smartlist_t**)value)
2018 result->value =
2019 smartlist_join_strings(*(smartlist_t**)value, ",", 0, NULL);
2020 else
2021 result->value = tor_strdup("");
2022 break;
2023 case CONFIG_TYPE_OBSOLETE:
2024 log_fn(LOG_PROTOCOL_WARN, LD_CONFIG,
2025 "You asked me for the value of an obsolete config option '%s'.",
2026 key);
2027 tor_free(result->key);
2028 tor_free(result);
2029 return NULL;
2030 case CONFIG_TYPE_LINELIST_S:
2031 log_warn(LD_CONFIG,
2032 "Can't return context-sensitive '%s' on its own", key);
2033 tor_free(result->key);
2034 tor_free(result);
2035 return NULL;
2036 case CONFIG_TYPE_LINELIST:
2037 case CONFIG_TYPE_LINELIST_V:
2038 tor_free(result->key);
2039 tor_free(result);
2040 result = config_lines_dup(*(const config_line_t**)value);
2041 break;
2042 default:
2043 tor_free(result->key);
2044 tor_free(result);
2045 log_warn(LD_BUG,"Unknown type %d for known key '%s'",
2046 var->type, key);
2047 return NULL;
2050 if (escape_val) {
2051 config_line_t *line;
2052 for (line = result; line; line = line->next) {
2053 if (line->value && config_value_needs_escape(line->value)) {
2054 char *newval = esc_for_log(line->value);
2055 tor_free(line->value);
2056 line->value = newval;
2061 return result;
2064 /** Iterate through the linked list of requested options <b>list</b>.
2065 * For each item, convert as appropriate and assign to <b>options</b>.
2066 * If an item is unrecognized, set *msg and return -1 immediately,
2067 * else return 0 for success.
2069 * If <b>clear_first</b>, interpret config options as replacing (not
2070 * extending) their previous values. If <b>clear_first</b> is set,
2071 * then <b>use_defaults</b> to decide if you set to defaults after
2072 * clearing, or make the value 0 or NULL.
2074 * Here are the use cases:
2075 * 1. A non-empty AllowInvalid line in your torrc. Appends to current
2076 * if linelist, replaces current if csv.
2077 * 2. An empty AllowInvalid line in your torrc. Should clear it.
2078 * 3. "RESETCONF AllowInvalid" sets it to default.
2079 * 4. "SETCONF AllowInvalid" makes it NULL.
2080 * 5. "SETCONF AllowInvalid=foo" clears it and sets it to "foo".
2082 * Use_defaults Clear_first
2083 * 0 0 "append"
2084 * 1 0 undefined, don't use
2085 * 0 1 "set to null first"
2086 * 1 1 "set to defaults first"
2087 * Return 0 on success, -1 on bad key, -2 on bad value.
2089 * As an additional special case, if a LINELIST config option has
2090 * no value and clear_first is 0, then warn and ignore it.
2094 There are three call cases for config_assign() currently.
2096 Case one: Torrc entry
2097 options_init_from_torrc() calls config_assign(0, 0)
2098 calls config_assign_line(0, 0).
2099 if value is empty, calls option_reset(0) and returns.
2100 calls config_assign_value(), appends.
2102 Case two: setconf
2103 options_trial_assign() calls config_assign(0, 1)
2104 calls config_reset_line(0)
2105 calls option_reset(0)
2106 calls option_clear().
2107 calls config_assign_line(0, 1).
2108 if value is empty, returns.
2109 calls config_assign_value(), appends.
2111 Case three: resetconf
2112 options_trial_assign() calls config_assign(1, 1)
2113 calls config_reset_line(1)
2114 calls option_reset(1)
2115 calls option_clear().
2116 calls config_assign_value(default)
2117 calls config_assign_line(1, 1).
2118 returns.
2120 static int
2121 config_assign(config_format_t *fmt, void *options, config_line_t *list,
2122 int use_defaults, int clear_first, char **msg)
2124 config_line_t *p;
2125 bitarray_t *options_seen;
2126 const int n_options = config_count_options(fmt);
2128 CHECK(fmt, options);
2130 /* pass 1: normalize keys */
2131 for (p = list; p; p = p->next) {
2132 const char *full = expand_abbrev(fmt, p->key, 0, 1);
2133 if (strcmp(full,p->key)) {
2134 tor_free(p->key);
2135 p->key = tor_strdup(full);
2139 /* pass 2: if we're reading from a resetting source, clear all
2140 * mentioned config options, and maybe set to their defaults. */
2141 if (clear_first) {
2142 for (p = list; p; p = p->next)
2143 config_reset_line(fmt, options, p->key, use_defaults);
2146 options_seen = bitarray_init_zero(n_options);
2147 /* pass 3: assign. */
2148 while (list) {
2149 int r;
2150 if ((r=config_assign_line(fmt, options, list, use_defaults,
2151 clear_first, options_seen, msg))) {
2152 bitarray_free(options_seen);
2153 return r;
2155 list = list->next;
2157 bitarray_free(options_seen);
2158 return 0;
2161 /** Try assigning <b>list</b> to the global options. You do this by duping
2162 * options, assigning list to the new one, then validating it. If it's
2163 * ok, then throw out the old one and stick with the new one. Else,
2164 * revert to old and return failure. Return SETOPT_OK on success, or
2165 * a setopt_err_t on failure.
2167 * If not success, point *<b>msg</b> to a newly allocated string describing
2168 * what went wrong.
2170 setopt_err_t
2171 options_trial_assign(config_line_t *list, int use_defaults,
2172 int clear_first, char **msg)
2174 int r;
2175 or_options_t *trial_options = options_dup(&options_format, get_options());
2177 if ((r=config_assign(&options_format, trial_options,
2178 list, use_defaults, clear_first, msg)) < 0) {
2179 config_free(&options_format, trial_options);
2180 return r;
2183 if (options_validate(get_options(), trial_options, 1, msg) < 0) {
2184 config_free(&options_format, trial_options);
2185 return SETOPT_ERR_PARSE; /*XXX make this a separate return value. */
2188 if (options_transition_allowed(get_options(), trial_options, msg) < 0) {
2189 config_free(&options_format, trial_options);
2190 return SETOPT_ERR_TRANSITION;
2193 if (set_options(trial_options, msg)<0) {
2194 config_free(&options_format, trial_options);
2195 return SETOPT_ERR_SETTING;
2198 /* we liked it. put it in place. */
2199 return SETOPT_OK;
2202 /** Reset config option <b>var</b> to 0, 0.0, NULL, or the equivalent.
2203 * Called from option_reset() and config_free(). */
2204 static void
2205 option_clear(config_format_t *fmt, or_options_t *options, config_var_t *var)
2207 void *lvalue = STRUCT_VAR_P(options, var->var_offset);
2208 (void)fmt; /* unused */
2209 switch (var->type) {
2210 case CONFIG_TYPE_STRING:
2211 case CONFIG_TYPE_FILENAME:
2212 tor_free(*(char**)lvalue);
2213 break;
2214 case CONFIG_TYPE_DOUBLE:
2215 *(double*)lvalue = 0.0;
2216 break;
2217 case CONFIG_TYPE_ISOTIME:
2218 *(time_t*)lvalue = 0;
2219 break;
2220 case CONFIG_TYPE_INTERVAL:
2221 case CONFIG_TYPE_UINT:
2222 case CONFIG_TYPE_BOOL:
2223 *(int*)lvalue = 0;
2224 break;
2225 case CONFIG_TYPE_MEMUNIT:
2226 *(uint64_t*)lvalue = 0;
2227 break;
2228 case CONFIG_TYPE_ROUTERSET:
2229 if (*(routerset_t**)lvalue) {
2230 routerset_free(*(routerset_t**)lvalue);
2231 *(routerset_t**)lvalue = NULL;
2233 break;
2234 case CONFIG_TYPE_CSV:
2235 if (*(smartlist_t**)lvalue) {
2236 SMARTLIST_FOREACH(*(smartlist_t **)lvalue, char *, cp, tor_free(cp));
2237 smartlist_free(*(smartlist_t **)lvalue);
2238 *(smartlist_t **)lvalue = NULL;
2240 break;
2241 case CONFIG_TYPE_LINELIST:
2242 case CONFIG_TYPE_LINELIST_S:
2243 config_free_lines(*(config_line_t **)lvalue);
2244 *(config_line_t **)lvalue = NULL;
2245 break;
2246 case CONFIG_TYPE_LINELIST_V:
2247 /* handled by linelist_s. */
2248 break;
2249 case CONFIG_TYPE_OBSOLETE:
2250 break;
2254 /** Clear the option indexed by <b>var</b> in <b>options</b>. Then if
2255 * <b>use_defaults</b>, set it to its default value.
2256 * Called by config_init() and option_reset_line() and option_assign_line(). */
2257 static void
2258 option_reset(config_format_t *fmt, or_options_t *options,
2259 config_var_t *var, int use_defaults)
2261 config_line_t *c;
2262 char *msg = NULL;
2263 CHECK(fmt, options);
2264 option_clear(fmt, options, var); /* clear it first */
2265 if (!use_defaults)
2266 return; /* all done */
2267 if (var->initvalue) {
2268 c = tor_malloc_zero(sizeof(config_line_t));
2269 c->key = tor_strdup(var->name);
2270 c->value = tor_strdup(var->initvalue);
2271 if (config_assign_value(fmt, options, c, &msg) < 0) {
2272 log_warn(LD_BUG, "Failed to assign default: %s", msg);
2273 tor_free(msg); /* if this happens it's a bug */
2275 config_free_lines(c);
2279 /** Print a usage message for tor. */
2280 static void
2281 print_usage(void)
2283 printf(
2284 "Copyright (c) 2001-2004, Roger Dingledine\n"
2285 "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
2286 "Copyright (c) 2007-2011, The Tor Project, Inc.\n\n"
2287 "tor -f <torrc> [args]\n"
2288 "See man page for options, or https://www.torproject.org/ for "
2289 "documentation.\n");
2292 /** Print all non-obsolete torrc options. */
2293 static void
2294 list_torrc_options(void)
2296 int i;
2297 smartlist_t *lines = smartlist_create();
2298 for (i = 0; _option_vars[i].name; ++i) {
2299 config_var_t *var = &_option_vars[i];
2300 if (var->type == CONFIG_TYPE_OBSOLETE ||
2301 var->type == CONFIG_TYPE_LINELIST_V)
2302 continue;
2303 printf("%s\n", var->name);
2305 smartlist_free(lines);
2308 /** Last value actually set by resolve_my_address. */
2309 static uint32_t last_resolved_addr = 0;
2311 * Based on <b>options-\>Address</b>, guess our public IP address and put it
2312 * (in host order) into *<b>addr_out</b>. If <b>hostname_out</b> is provided,
2313 * set *<b>hostname_out</b> to a new string holding the hostname we used to
2314 * get the address. Return 0 if all is well, or -1 if we can't find a suitable
2315 * public IP address.
2318 resolve_my_address(int warn_severity, or_options_t *options,
2319 uint32_t *addr_out, char **hostname_out)
2321 struct in_addr in;
2322 uint32_t addr; /* host order */
2323 char hostname[256];
2324 int explicit_ip=1;
2325 int explicit_hostname=1;
2326 int from_interface=0;
2327 char tmpbuf[INET_NTOA_BUF_LEN];
2328 const char *address = options->Address;
2329 int notice_severity = warn_severity <= LOG_NOTICE ?
2330 LOG_NOTICE : warn_severity;
2332 tor_assert(addr_out);
2334 if (address && *address) {
2335 strlcpy(hostname, address, sizeof(hostname));
2336 } else { /* then we need to guess our address */
2337 explicit_ip = 0; /* it's implicit */
2338 explicit_hostname = 0; /* it's implicit */
2340 if (gethostname(hostname, sizeof(hostname)) < 0) {
2341 log_fn(warn_severity, LD_NET,"Error obtaining local hostname");
2342 return -1;
2344 log_debug(LD_CONFIG,"Guessed local host name as '%s'",hostname);
2347 /* now we know hostname. resolve it and keep only the IP address */
2349 if (tor_inet_aton(hostname, &in) == 0) {
2350 /* then we have to resolve it */
2351 explicit_ip = 0;
2352 if (tor_lookup_hostname(hostname, &addr)) { /* failed to resolve */
2353 uint32_t interface_ip; /* host order */
2355 if (explicit_hostname) {
2356 log_fn(warn_severity, LD_CONFIG,
2357 "Could not resolve local Address '%s'. Failing.", hostname);
2358 return -1;
2360 log_fn(notice_severity, LD_CONFIG,
2361 "Could not resolve guessed local hostname '%s'. "
2362 "Trying something else.", hostname);
2363 if (get_interface_address(warn_severity, &interface_ip)) {
2364 log_fn(warn_severity, LD_CONFIG,
2365 "Could not get local interface IP address. Failing.");
2366 return -1;
2368 from_interface = 1;
2369 in.s_addr = htonl(interface_ip);
2370 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2371 log_fn(notice_severity, LD_CONFIG, "Learned IP address '%s' for "
2372 "local interface. Using that.", tmpbuf);
2373 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2374 } else { /* resolved hostname into addr */
2375 in.s_addr = htonl(addr);
2377 if (!explicit_hostname &&
2378 is_internal_IP(ntohl(in.s_addr), 0)) {
2379 uint32_t interface_ip;
2381 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2382 log_fn(notice_severity, LD_CONFIG, "Guessed local hostname '%s' "
2383 "resolves to a private IP address (%s). Trying something "
2384 "else.", hostname, tmpbuf);
2386 if (get_interface_address(warn_severity, &interface_ip)) {
2387 log_fn(warn_severity, LD_CONFIG,
2388 "Could not get local interface IP address. Too bad.");
2389 } else if (is_internal_IP(interface_ip, 0)) {
2390 struct in_addr in2;
2391 in2.s_addr = htonl(interface_ip);
2392 tor_inet_ntoa(&in2,tmpbuf,sizeof(tmpbuf));
2393 log_fn(notice_severity, LD_CONFIG,
2394 "Interface IP address '%s' is a private address too. "
2395 "Ignoring.", tmpbuf);
2396 } else {
2397 from_interface = 1;
2398 in.s_addr = htonl(interface_ip);
2399 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2400 log_fn(notice_severity, LD_CONFIG,
2401 "Learned IP address '%s' for local interface."
2402 " Using that.", tmpbuf);
2403 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2409 tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
2410 if (is_internal_IP(ntohl(in.s_addr), 0)) {
2411 /* make sure we're ok with publishing an internal IP */
2412 if (!options->DirServers && !options->AlternateDirAuthority) {
2413 /* if they are using the default dirservers, disallow internal IPs
2414 * always. */
2415 log_fn(warn_severity, LD_CONFIG,
2416 "Address '%s' resolves to private IP address '%s'. "
2417 "Tor servers that use the default DirServers must have public "
2418 "IP addresses.", hostname, tmpbuf);
2419 return -1;
2421 if (!explicit_ip) {
2422 /* even if they've set their own dirservers, require an explicit IP if
2423 * they're using an internal address. */
2424 log_fn(warn_severity, LD_CONFIG, "Address '%s' resolves to private "
2425 "IP address '%s'. Please set the Address config option to be "
2426 "the IP address you want to use.", hostname, tmpbuf);
2427 return -1;
2431 log_debug(LD_CONFIG, "Resolved Address to '%s'.", tmpbuf);
2432 *addr_out = ntohl(in.s_addr);
2433 if (last_resolved_addr && last_resolved_addr != *addr_out) {
2434 /* Leave this as a notice, regardless of the requested severity,
2435 * at least until dynamic IP address support becomes bulletproof. */
2436 log_notice(LD_NET,
2437 "Your IP address seems to have changed to %s. Updating.",
2438 tmpbuf);
2439 ip_address_changed(0);
2441 if (last_resolved_addr != *addr_out) {
2442 const char *method;
2443 const char *h = hostname;
2444 if (explicit_ip) {
2445 method = "CONFIGURED";
2446 h = NULL;
2447 } else if (explicit_hostname) {
2448 method = "RESOLVED";
2449 } else if (from_interface) {
2450 method = "INTERFACE";
2451 h = NULL;
2452 } else {
2453 method = "GETHOSTNAME";
2455 control_event_server_status(LOG_NOTICE,
2456 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s %s%s",
2457 tmpbuf, method, h?"HOSTNAME=":"", h);
2459 last_resolved_addr = *addr_out;
2460 if (hostname_out)
2461 *hostname_out = tor_strdup(hostname);
2462 return 0;
2465 /** Return true iff <b>addr</b> is judged to be on the same network as us, or
2466 * on a private network.
2469 is_local_addr(const tor_addr_t *addr)
2471 if (tor_addr_is_internal(addr, 0))
2472 return 1;
2473 /* Check whether ip is on the same /24 as we are. */
2474 if (get_options()->EnforceDistinctSubnets == 0)
2475 return 0;
2476 if (tor_addr_family(addr) == AF_INET) {
2477 /*XXXX022 IP6 what corresponds to an /24? */
2478 uint32_t ip = tor_addr_to_ipv4h(addr);
2480 /* It's possible that this next check will hit before the first time
2481 * resolve_my_address actually succeeds. (For clients, it is likely that
2482 * resolve_my_address will never be called at all). In those cases,
2483 * last_resolved_addr will be 0, and so checking to see whether ip is on
2484 * the same /24 as last_resolved_addr will be the same as checking whether
2485 * it was on net 0, which is already done by is_internal_IP.
2487 if ((last_resolved_addr & (uint32_t)0xffffff00ul)
2488 == (ip & (uint32_t)0xffffff00ul))
2489 return 1;
2491 return 0;
2494 /** Called when we don't have a nickname set. Try to guess a good nickname
2495 * based on the hostname, and return it in a newly allocated string. If we
2496 * can't, return NULL and let the caller warn if it wants to. */
2497 static char *
2498 get_default_nickname(void)
2500 static const char * const bad_default_nicknames[] = {
2501 "localhost",
2502 NULL,
2504 char localhostname[256];
2505 char *cp, *out, *outp;
2506 int i;
2508 if (gethostname(localhostname, sizeof(localhostname)) < 0)
2509 return NULL;
2511 /* Put it in lowercase; stop at the first dot. */
2512 if ((cp = strchr(localhostname, '.')))
2513 *cp = '\0';
2514 tor_strlower(localhostname);
2516 /* Strip invalid characters. */
2517 cp = localhostname;
2518 out = outp = tor_malloc(strlen(localhostname) + 1);
2519 while (*cp) {
2520 if (strchr(LEGAL_NICKNAME_CHARACTERS, *cp))
2521 *outp++ = *cp++;
2522 else
2523 cp++;
2525 *outp = '\0';
2527 /* Enforce length. */
2528 if (strlen(out) > MAX_NICKNAME_LEN)
2529 out[MAX_NICKNAME_LEN]='\0';
2531 /* Check for dumb names. */
2532 for (i = 0; bad_default_nicknames[i]; ++i) {
2533 if (!strcmp(out, bad_default_nicknames[i])) {
2534 tor_free(out);
2535 return NULL;
2539 return out;
2542 /** Release storage held by <b>options</b>. */
2543 static void
2544 config_free(config_format_t *fmt, void *options)
2546 int i;
2548 if (!options)
2549 return;
2551 tor_assert(fmt);
2553 for (i=0; fmt->vars[i].name; ++i)
2554 option_clear(fmt, options, &(fmt->vars[i]));
2555 if (fmt->extra) {
2556 config_line_t **linep = STRUCT_VAR_P(options, fmt->extra->var_offset);
2557 config_free_lines(*linep);
2558 *linep = NULL;
2560 tor_free(options);
2563 /** Return true iff a and b contain identical keys and values in identical
2564 * order. */
2565 static int
2566 config_lines_eq(config_line_t *a, config_line_t *b)
2568 while (a && b) {
2569 if (strcasecmp(a->key, b->key) || strcmp(a->value, b->value))
2570 return 0;
2571 a = a->next;
2572 b = b->next;
2574 if (a || b)
2575 return 0;
2576 return 1;
2579 /** Return true iff the option <b>name</b> has the same value in <b>o1</b>
2580 * and <b>o2</b>. Must not be called for LINELIST_S or OBSOLETE options.
2582 static int
2583 option_is_same(config_format_t *fmt,
2584 or_options_t *o1, or_options_t *o2, const char *name)
2586 config_line_t *c1, *c2;
2587 int r = 1;
2588 CHECK(fmt, o1);
2589 CHECK(fmt, o2);
2591 c1 = get_assigned_option(fmt, o1, name, 0);
2592 c2 = get_assigned_option(fmt, o2, name, 0);
2593 r = config_lines_eq(c1, c2);
2594 config_free_lines(c1);
2595 config_free_lines(c2);
2596 return r;
2599 /** Copy storage held by <b>old</b> into a new or_options_t and return it. */
2600 static or_options_t *
2601 options_dup(config_format_t *fmt, or_options_t *old)
2603 or_options_t *newopts;
2604 int i;
2605 config_line_t *line;
2607 newopts = config_alloc(fmt);
2608 for (i=0; fmt->vars[i].name; ++i) {
2609 if (fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
2610 continue;
2611 if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE)
2612 continue;
2613 line = get_assigned_option(fmt, old, fmt->vars[i].name, 0);
2614 if (line) {
2615 char *msg = NULL;
2616 if (config_assign(fmt, newopts, line, 0, 0, &msg) < 0) {
2617 log_err(LD_BUG, "Config_get_assigned_option() generated "
2618 "something we couldn't config_assign(): %s", msg);
2619 tor_free(msg);
2620 tor_assert(0);
2623 config_free_lines(line);
2625 return newopts;
2628 /** Return a new empty or_options_t. Used for testing. */
2629 or_options_t *
2630 options_new(void)
2632 return config_alloc(&options_format);
2635 /** Set <b>options</b> to hold reasonable defaults for most options.
2636 * Each option defaults to zero. */
2637 void
2638 options_init(or_options_t *options)
2640 config_init(&options_format, options);
2643 /* Check if the port number given in <b>port_option</b> in combination with
2644 * the specified port in <b>listen_options</b> will result in Tor actually
2645 * opening a low port (meaning a port lower than 1024). Return 1 if
2646 * it is, or 0 if it isn't or the concept of a low port isn't applicable for
2647 * the platform we're on. */
2648 static int
2649 is_listening_on_low_port(uint16_t port_option,
2650 const config_line_t *listen_options)
2652 #ifdef MS_WINDOWS
2653 (void) port_option;
2654 (void) listen_options;
2655 return 0; /* No port is too low for windows. */
2656 #else
2657 const config_line_t *l;
2658 uint16_t p;
2659 if (port_option == 0)
2660 return 0; /* We're not listening */
2661 if (listen_options == NULL)
2662 return (port_option < 1024);
2664 for (l = listen_options; l; l = l->next) {
2665 parse_addr_port(LOG_WARN, l->value, NULL, NULL, &p);
2666 if (p<1024) {
2667 return 1;
2670 return 0;
2671 #endif
2674 /** Set all vars in the configuration object <b>options</b> to their default
2675 * values. */
2676 static void
2677 config_init(config_format_t *fmt, void *options)
2679 int i;
2680 config_var_t *var;
2681 CHECK(fmt, options);
2683 for (i=0; fmt->vars[i].name; ++i) {
2684 var = &fmt->vars[i];
2685 if (!var->initvalue)
2686 continue; /* defaults to NULL or 0 */
2687 option_reset(fmt, options, var, 1);
2691 /** Allocate and return a new string holding the written-out values of the vars
2692 * in 'options'. If 'minimal', do not write out any default-valued vars.
2693 * Else, if comment_defaults, write default values as comments.
2695 static char *
2696 config_dump(config_format_t *fmt, void *options, int minimal,
2697 int comment_defaults)
2699 smartlist_t *elements;
2700 or_options_t *defaults;
2701 config_line_t *line, *assigned;
2702 char *result;
2703 int i;
2704 char *msg = NULL;
2706 defaults = config_alloc(fmt);
2707 config_init(fmt, defaults);
2709 /* XXX use a 1 here so we don't add a new log line while dumping */
2710 if (fmt->validate_fn(NULL,defaults, 1, &msg) < 0) {
2711 log_err(LD_BUG, "Failed to validate default config.");
2712 tor_free(msg);
2713 tor_assert(0);
2716 elements = smartlist_create();
2717 for (i=0; fmt->vars[i].name; ++i) {
2718 int comment_option = 0;
2719 if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE ||
2720 fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
2721 continue;
2722 /* Don't save 'hidden' control variables. */
2723 if (!strcmpstart(fmt->vars[i].name, "__"))
2724 continue;
2725 if (minimal && option_is_same(fmt, options, defaults, fmt->vars[i].name))
2726 continue;
2727 else if (comment_defaults &&
2728 option_is_same(fmt, options, defaults, fmt->vars[i].name))
2729 comment_option = 1;
2731 line = assigned = get_assigned_option(fmt, options, fmt->vars[i].name, 1);
2733 for (; line; line = line->next) {
2734 char *tmp;
2735 tor_asprintf(&tmp, "%s%s %s\n",
2736 comment_option ? "# " : "",
2737 line->key, line->value);
2738 smartlist_add(elements, tmp);
2740 config_free_lines(assigned);
2743 if (fmt->extra) {
2744 line = *(config_line_t**)STRUCT_VAR_P(options, fmt->extra->var_offset);
2745 for (; line; line = line->next) {
2746 char *tmp;
2747 tor_asprintf(&tmp, "%s %s\n", line->key, line->value);
2748 smartlist_add(elements, tmp);
2752 result = smartlist_join_strings(elements, "", 0, NULL);
2753 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
2754 smartlist_free(elements);
2755 config_free(fmt, defaults);
2756 return result;
2759 /** Return a string containing a possible configuration file that would give
2760 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
2761 * include options that are the same as Tor's defaults.
2763 char *
2764 options_dump(or_options_t *options, int minimal)
2766 return config_dump(&options_format, options, minimal, 0);
2769 /** Return 0 if every element of sl is a string holding a decimal
2770 * representation of a port number, or if sl is NULL.
2771 * Otherwise set *msg and return -1. */
2772 static int
2773 validate_ports_csv(smartlist_t *sl, const char *name, char **msg)
2775 int i;
2776 tor_assert(name);
2778 if (!sl)
2779 return 0;
2781 SMARTLIST_FOREACH(sl, const char *, cp,
2783 i = atoi(cp);
2784 if (i < 1 || i > 65535) {
2785 tor_asprintf(msg, "Port '%s' out of range in %s", cp, name);
2786 return -1;
2789 return 0;
2792 /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
2793 * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
2794 * Else return 0.
2796 static int
2797 ensure_bandwidth_cap(uint64_t *value, const char *desc, char **msg)
2799 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2800 /* This handles an understandable special case where somebody says "2gb"
2801 * whereas our actual maximum is 2gb-1 (INT_MAX) */
2802 --*value;
2804 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2805 tor_asprintf(msg, "%s ("U64_FORMAT") must be at most %d",
2806 desc, U64_PRINTF_ARG(*value),
2807 ROUTER_MAX_DECLARED_BANDWIDTH);
2808 return -1;
2810 return 0;
2813 /** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
2814 * and write it to <b>options</b>-\>_PublishServerDescriptor. Treat "1"
2815 * as "v2,v3" unless BridgeRelay is 1, in which case treat it as "bridge".
2816 * Treat "0" as "".
2817 * Return 0 on success or -1 if not a recognized authority type (in which
2818 * case the value of _PublishServerDescriptor is undefined). */
2819 static int
2820 compute_publishserverdescriptor(or_options_t *options)
2822 smartlist_t *list = options->PublishServerDescriptor;
2823 authority_type_t *auth = &options->_PublishServerDescriptor;
2824 *auth = NO_AUTHORITY;
2825 if (!list) /* empty list, answer is none */
2826 return 0;
2827 SMARTLIST_FOREACH(list, const char *, string, {
2828 if (!strcasecmp(string, "v1"))
2829 *auth |= V1_AUTHORITY;
2830 else if (!strcmp(string, "1"))
2831 if (options->BridgeRelay)
2832 *auth |= BRIDGE_AUTHORITY;
2833 else
2834 *auth |= V2_AUTHORITY | V3_AUTHORITY;
2835 else if (!strcasecmp(string, "v2"))
2836 *auth |= V2_AUTHORITY;
2837 else if (!strcasecmp(string, "v3"))
2838 *auth |= V3_AUTHORITY;
2839 else if (!strcasecmp(string, "bridge"))
2840 *auth |= BRIDGE_AUTHORITY;
2841 else if (!strcasecmp(string, "hidserv"))
2842 *auth |= HIDSERV_AUTHORITY;
2843 else if (!strcasecmp(string, "") || !strcmp(string, "0"))
2844 /* no authority */;
2845 else
2846 return -1;
2848 return 0;
2851 /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
2852 * services can overload the directory system. */
2853 #define MIN_REND_POST_PERIOD (10*60)
2855 /** Highest allowable value for RendPostPeriod. */
2856 #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
2858 /** Lowest allowable value for MaxCircuitDirtiness; if this is too low, Tor
2859 * will generate too many circuits and potentially overload the network. */
2860 #define MIN_MAX_CIRCUIT_DIRTINESS 10
2862 /** Lowest allowable value for CircuitStreamTimeout; if this is too low, Tor
2863 * will generate too many circuits and potentially overload the network. */
2864 #define MIN_CIRCUIT_STREAM_TIMEOUT 10
2866 /** Return 0 if every setting in <b>options</b> is reasonable, and a
2867 * permissible transition from <b>old_options</b>. Else return -1.
2868 * Should have no side effects, except for normalizing the contents of
2869 * <b>options</b>.
2871 * On error, tor_strdup an error explanation into *<b>msg</b>.
2873 * XXX
2874 * If <b>from_setconf</b>, we were called by the controller, and our
2875 * Log line should stay empty. If it's 0, then give us a default log
2876 * if there are no logs defined.
2878 static int
2879 options_validate(or_options_t *old_options, or_options_t *options,
2880 int from_setconf, char **msg)
2882 int i;
2883 config_line_t *cl;
2884 const char *uname = get_uname();
2885 #define REJECT(arg) \
2886 STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
2887 #define COMPLAIN(arg) STMT_BEGIN log(LOG_WARN, LD_CONFIG, arg); STMT_END
2889 tor_assert(msg);
2890 *msg = NULL;
2892 if (options->ORPort < 0 || options->ORPort > 65535)
2893 REJECT("ORPort option out of bounds.");
2895 if (server_mode(options) &&
2896 (!strcmpstart(uname, "Windows 95") ||
2897 !strcmpstart(uname, "Windows 98") ||
2898 !strcmpstart(uname, "Windows Me"))) {
2899 log(LOG_WARN, LD_CONFIG, "Tor is running as a server, but you are "
2900 "running %s; this probably won't work. See "
2901 "https://wiki.torproject.org/TheOnionRouter/TorFAQ#ServerOS "
2902 "for details.", uname);
2905 if (options->ORPort == 0 && options->ORListenAddress != NULL)
2906 REJECT("ORPort must be defined if ORListenAddress is defined.");
2908 if (options->DirPort == 0 && options->DirListenAddress != NULL)
2909 REJECT("DirPort must be defined if DirListenAddress is defined.");
2911 if (options->DNSPort == 0 && options->DNSListenAddress != NULL)
2912 REJECT("DNSPort must be defined if DNSListenAddress is defined.");
2914 if (options->ControlPort == 0 && options->ControlListenAddress != NULL)
2915 REJECT("ControlPort must be defined if ControlListenAddress is defined.");
2917 if (options->TransPort == 0 && options->TransListenAddress != NULL)
2918 REJECT("TransPort must be defined if TransListenAddress is defined.");
2920 if (options->NATDPort == 0 && options->NATDListenAddress != NULL)
2921 REJECT("NATDPort must be defined if NATDListenAddress is defined.");
2923 /* Don't gripe about SocksPort 0 with SocksListenAddress set; a standard
2924 * configuration does this. */
2926 for (i = 0; i < 3; ++i) {
2927 int is_socks = i==0;
2928 int is_trans = i==1;
2929 config_line_t *line, *opt, *old;
2930 const char *tp;
2931 if (is_socks) {
2932 opt = options->SocksListenAddress;
2933 old = old_options ? old_options->SocksListenAddress : NULL;
2934 tp = "SOCKS proxy";
2935 } else if (is_trans) {
2936 opt = options->TransListenAddress;
2937 old = old_options ? old_options->TransListenAddress : NULL;
2938 tp = "transparent proxy";
2939 } else {
2940 opt = options->NATDListenAddress;
2941 old = old_options ? old_options->NATDListenAddress : NULL;
2942 tp = "natd proxy";
2945 for (line = opt; line; line = line->next) {
2946 char *address = NULL;
2947 uint16_t port;
2948 uint32_t addr;
2949 if (parse_addr_port(LOG_WARN, line->value, &address, &addr, &port)<0)
2950 continue; /* We'll warn about this later. */
2951 if (!is_internal_IP(addr, 1) &&
2952 (!old_options || !config_lines_eq(old, opt))) {
2953 log_warn(LD_CONFIG,
2954 "You specified a public address '%s' for a %s. Other "
2955 "people on the Internet might find your computer and use it as "
2956 "an open %s. Please don't allow this unless you have "
2957 "a good reason.", address, tp, tp);
2959 tor_free(address);
2963 if (validate_data_directory(options)<0)
2964 REJECT("Invalid DataDirectory");
2966 if (options->Nickname == NULL) {
2967 if (server_mode(options)) {
2968 if (!(options->Nickname = get_default_nickname())) {
2969 log_notice(LD_CONFIG, "Couldn't pick a nickname based on "
2970 "our hostname; using %s instead.", UNNAMED_ROUTER_NICKNAME);
2971 options->Nickname = tor_strdup(UNNAMED_ROUTER_NICKNAME);
2972 } else {
2973 log_notice(LD_CONFIG, "Choosing default nickname '%s'",
2974 options->Nickname);
2977 } else {
2978 if (!is_legal_nickname(options->Nickname)) {
2979 tor_asprintf(msg,
2980 "Nickname '%s' is wrong length or contains illegal characters.",
2981 options->Nickname);
2982 return -1;
2986 if (server_mode(options) && !options->ContactInfo)
2987 log(LOG_NOTICE, LD_CONFIG, "Your ContactInfo config option is not set. "
2988 "Please consider setting it, so we can contact you if your server is "
2989 "misconfigured or something else goes wrong.");
2991 /* Special case on first boot if no Log options are given. */
2992 if (!options->Logs && !options->RunAsDaemon && !from_setconf)
2993 config_line_append(&options->Logs, "Log", "notice stdout");
2995 if (options_init_logs(options, 1)<0) /* Validate the log(s) */
2996 REJECT("Failed to validate Log options. See logs for details.");
2998 if (authdir_mode(options)) {
2999 /* confirm that our address isn't broken, so we can complain now */
3000 uint32_t tmp;
3001 if (resolve_my_address(LOG_WARN, options, &tmp, NULL) < 0)
3002 REJECT("Failed to resolve/guess local address. See logs for details.");
3005 if (strcmp(options->RefuseUnknownExits, "0") &&
3006 strcmp(options->RefuseUnknownExits, "1") &&
3007 strcmp(options->RefuseUnknownExits, "auto")) {
3008 REJECT("RefuseUnknownExits must be 0, 1, or auto");
3011 #ifndef MS_WINDOWS
3012 if (options->RunAsDaemon && torrc_fname && path_is_relative(torrc_fname))
3013 REJECT("Can't use a relative path to torrc when RunAsDaemon is set.");
3014 #endif
3016 if (options->SocksPort < 0 || options->SocksPort > 65535)
3017 REJECT("SocksPort option out of bounds.");
3019 if (options->DNSPort < 0 || options->DNSPort > 65535)
3020 REJECT("DNSPort option out of bounds.");
3022 if (options->TransPort < 0 || options->TransPort > 65535)
3023 REJECT("TransPort option out of bounds.");
3025 if (options->NATDPort < 0 || options->NATDPort > 65535)
3026 REJECT("NATDPort option out of bounds.");
3028 if (options->SocksPort == 0 && options->TransPort == 0 &&
3029 options->NATDPort == 0 && options->ORPort == 0 &&
3030 options->DNSPort == 0 && !options->RendConfigLines)
3031 log(LOG_WARN, LD_CONFIG,
3032 "SocksPort, TransPort, NATDPort, DNSPort, and ORPort are all "
3033 "undefined, and there aren't any hidden services configured. "
3034 "Tor will still run, but probably won't do anything.");
3036 if (options->ControlPort < 0 || options->ControlPort > 65535)
3037 REJECT("ControlPort option out of bounds.");
3039 if (options->DirPort < 0 || options->DirPort > 65535)
3040 REJECT("DirPort option out of bounds.");
3042 #ifndef USE_TRANSPARENT
3043 if (options->TransPort || options->TransListenAddress)
3044 REJECT("TransPort and TransListenAddress are disabled in this build.");
3045 #endif
3047 if (options->AccountingMax &&
3048 (is_listening_on_low_port(options->ORPort, options->ORListenAddress) ||
3049 is_listening_on_low_port(options->DirPort, options->DirListenAddress)))
3051 log(LOG_WARN, LD_CONFIG,
3052 "You have set AccountingMax to use hibernation. You have also "
3053 "chosen a low DirPort or OrPort. This combination can make Tor stop "
3054 "working when it tries to re-attach the port after a period of "
3055 "hibernation. Please choose a different port or turn off "
3056 "hibernation unless you know this combination will work on your "
3057 "platform.");
3060 if (options->ExcludeExitNodes || options->ExcludeNodes) {
3061 options->_ExcludeExitNodesUnion = routerset_new();
3062 routerset_union(options->_ExcludeExitNodesUnion,options->ExcludeExitNodes);
3063 routerset_union(options->_ExcludeExitNodesUnion,options->ExcludeNodes);
3066 if (options->ExcludeNodes && options->StrictNodes) {
3067 COMPLAIN("You have asked to exclude certain relays from all positions "
3068 "in your circuits. Expect hidden services and other Tor "
3069 "features to be broken in unpredictable ways.");
3072 if (options->EntryNodes && !routerset_is_list(options->EntryNodes)) {
3073 /* XXXX fix this; see entry_guards_prepend_from_config(). */
3074 REJECT("IPs or countries are not yet supported in EntryNodes.");
3077 if (options->AuthoritativeDir) {
3078 if (!options->ContactInfo && !options->TestingTorNetwork)
3079 REJECT("Authoritative directory servers must set ContactInfo");
3080 if (options->V1AuthoritativeDir && !options->RecommendedVersions)
3081 REJECT("V1 authoritative dir servers must set RecommendedVersions.");
3082 if (!options->RecommendedClientVersions)
3083 options->RecommendedClientVersions =
3084 config_lines_dup(options->RecommendedVersions);
3085 if (!options->RecommendedServerVersions)
3086 options->RecommendedServerVersions =
3087 config_lines_dup(options->RecommendedVersions);
3088 if (options->VersioningAuthoritativeDir &&
3089 (!options->RecommendedClientVersions ||
3090 !options->RecommendedServerVersions))
3091 REJECT("Versioning authoritative dir servers must set "
3092 "Recommended*Versions.");
3093 if (options->UseEntryGuards) {
3094 log_info(LD_CONFIG, "Authoritative directory servers can't set "
3095 "UseEntryGuards. Disabling.");
3096 options->UseEntryGuards = 0;
3098 if (!options->DownloadExtraInfo && authdir_mode_any_main(options)) {
3099 log_info(LD_CONFIG, "Authoritative directories always try to download "
3100 "extra-info documents. Setting DownloadExtraInfo.");
3101 options->DownloadExtraInfo = 1;
3103 if (!(options->BridgeAuthoritativeDir || options->HSAuthoritativeDir ||
3104 options->V1AuthoritativeDir || options->V2AuthoritativeDir ||
3105 options->V3AuthoritativeDir))
3106 REJECT("AuthoritativeDir is set, but none of "
3107 "(Bridge/HS/V1/V2/V3)AuthoritativeDir is set.");
3108 /* If we have a v3bandwidthsfile and it's broken, complain on startup */
3109 if (options->V3BandwidthsFile && !old_options) {
3110 dirserv_read_measured_bandwidths(options->V3BandwidthsFile, NULL);
3114 if (options->AuthoritativeDir && !options->DirPort)
3115 REJECT("Running as authoritative directory, but no DirPort set.");
3117 if (options->AuthoritativeDir && !options->ORPort)
3118 REJECT("Running as authoritative directory, but no ORPort set.");
3120 if (options->AuthoritativeDir && options->ClientOnly)
3121 REJECT("Running as authoritative directory, but ClientOnly also set.");
3123 if (options->FetchDirInfoExtraEarly && !options->FetchDirInfoEarly)
3124 REJECT("FetchDirInfoExtraEarly requires that you also set "
3125 "FetchDirInfoEarly");
3127 if (options->ConnLimit <= 0) {
3128 tor_asprintf(msg,
3129 "ConnLimit must be greater than 0, but was set to %d",
3130 options->ConnLimit);
3131 return -1;
3134 if (validate_ports_csv(options->FirewallPorts, "FirewallPorts", msg) < 0)
3135 return -1;
3137 if (validate_ports_csv(options->LongLivedPorts, "LongLivedPorts", msg) < 0)
3138 return -1;
3140 if (validate_ports_csv(options->RejectPlaintextPorts,
3141 "RejectPlaintextPorts", msg) < 0)
3142 return -1;
3144 if (validate_ports_csv(options->WarnPlaintextPorts,
3145 "WarnPlaintextPorts", msg) < 0)
3146 return -1;
3148 if (options->FascistFirewall && !options->ReachableAddresses) {
3149 if (options->FirewallPorts && smartlist_len(options->FirewallPorts)) {
3150 /* We already have firewall ports set, so migrate them to
3151 * ReachableAddresses, which will set ReachableORAddresses and
3152 * ReachableDirAddresses if they aren't set explicitly. */
3153 smartlist_t *instead = smartlist_create();
3154 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3155 new_line->key = tor_strdup("ReachableAddresses");
3156 /* If we're configured with the old format, we need to prepend some
3157 * open ports. */
3158 SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
3160 int p = atoi(portno);
3161 char *s;
3162 if (p<0) continue;
3163 s = tor_malloc(16);
3164 tor_snprintf(s, 16, "*:%d", p);
3165 smartlist_add(instead, s);
3167 new_line->value = smartlist_join_strings(instead,",",0,NULL);
3168 /* These have been deprecated since 0.1.1.5-alpha-cvs */
3169 log(LOG_NOTICE, LD_CONFIG,
3170 "Converting FascistFirewall and FirewallPorts "
3171 "config options to new format: \"ReachableAddresses %s\"",
3172 new_line->value);
3173 options->ReachableAddresses = new_line;
3174 SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
3175 smartlist_free(instead);
3176 } else {
3177 /* We do not have FirewallPorts set, so add 80 to
3178 * ReachableDirAddresses, and 443 to ReachableORAddresses. */
3179 if (!options->ReachableDirAddresses) {
3180 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3181 new_line->key = tor_strdup("ReachableDirAddresses");
3182 new_line->value = tor_strdup("*:80");
3183 options->ReachableDirAddresses = new_line;
3184 log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
3185 "to new format: \"ReachableDirAddresses *:80\"");
3187 if (!options->ReachableORAddresses) {
3188 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3189 new_line->key = tor_strdup("ReachableORAddresses");
3190 new_line->value = tor_strdup("*:443");
3191 options->ReachableORAddresses = new_line;
3192 log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
3193 "to new format: \"ReachableORAddresses *:443\"");
3198 for (i=0; i<3; i++) {
3199 config_line_t **linep =
3200 (i==0) ? &options->ReachableAddresses :
3201 (i==1) ? &options->ReachableORAddresses :
3202 &options->ReachableDirAddresses;
3203 if (!*linep)
3204 continue;
3205 /* We need to end with a reject *:*, not an implicit accept *:* */
3206 for (;;) {
3207 if (!strcmp((*linep)->value, "reject *:*")) /* already there */
3208 break;
3209 linep = &((*linep)->next);
3210 if (!*linep) {
3211 *linep = tor_malloc_zero(sizeof(config_line_t));
3212 (*linep)->key = tor_strdup(
3213 (i==0) ? "ReachableAddresses" :
3214 (i==1) ? "ReachableORAddresses" :
3215 "ReachableDirAddresses");
3216 (*linep)->value = tor_strdup("reject *:*");
3217 break;
3222 if ((options->ReachableAddresses ||
3223 options->ReachableORAddresses ||
3224 options->ReachableDirAddresses) &&
3225 server_mode(options))
3226 REJECT("Servers must be able to freely connect to the rest "
3227 "of the Internet, so they must not set Reachable*Addresses "
3228 "or FascistFirewall.");
3230 if (options->UseBridges &&
3231 server_mode(options))
3232 REJECT("Servers must be able to freely connect to the rest "
3233 "of the Internet, so they must not set UseBridges.");
3235 options->_AllowInvalid = 0;
3236 if (options->AllowInvalidNodes) {
3237 SMARTLIST_FOREACH(options->AllowInvalidNodes, const char *, cp, {
3238 if (!strcasecmp(cp, "entry"))
3239 options->_AllowInvalid |= ALLOW_INVALID_ENTRY;
3240 else if (!strcasecmp(cp, "exit"))
3241 options->_AllowInvalid |= ALLOW_INVALID_EXIT;
3242 else if (!strcasecmp(cp, "middle"))
3243 options->_AllowInvalid |= ALLOW_INVALID_MIDDLE;
3244 else if (!strcasecmp(cp, "introduction"))
3245 options->_AllowInvalid |= ALLOW_INVALID_INTRODUCTION;
3246 else if (!strcasecmp(cp, "rendezvous"))
3247 options->_AllowInvalid |= ALLOW_INVALID_RENDEZVOUS;
3248 else {
3249 tor_asprintf(msg,
3250 "Unrecognized value '%s' in AllowInvalidNodes", cp);
3251 return -1;
3256 if (!options->SafeLogging ||
3257 !strcasecmp(options->SafeLogging, "0")) {
3258 options->_SafeLogging = SAFELOG_SCRUB_NONE;
3259 } else if (!strcasecmp(options->SafeLogging, "relay")) {
3260 options->_SafeLogging = SAFELOG_SCRUB_RELAY;
3261 } else if (!strcasecmp(options->SafeLogging, "1")) {
3262 options->_SafeLogging = SAFELOG_SCRUB_ALL;
3263 } else {
3264 tor_asprintf(msg,
3265 "Unrecognized value '%s' in SafeLogging",
3266 escaped(options->SafeLogging));
3267 return -1;
3270 if (compute_publishserverdescriptor(options) < 0) {
3271 tor_asprintf(msg, "Unrecognized value in PublishServerDescriptor");
3272 return -1;
3275 if ((options->BridgeRelay
3276 || options->_PublishServerDescriptor & BRIDGE_AUTHORITY)
3277 && (options->_PublishServerDescriptor
3278 & (V1_AUTHORITY|V2_AUTHORITY|V3_AUTHORITY))) {
3279 REJECT("Bridges are not supposed to publish router descriptors to the "
3280 "directory authorities. Please correct your "
3281 "PublishServerDescriptor line.");
3284 if (options->BridgeRelay && options->DirPort) {
3285 log_warn(LD_CONFIG, "Can't set a DirPort on a bridge relay; disabling "
3286 "DirPort");
3287 options->DirPort = 0;
3290 if (options->MinUptimeHidServDirectoryV2 < 0) {
3291 log_warn(LD_CONFIG, "MinUptimeHidServDirectoryV2 option must be at "
3292 "least 0 seconds. Changing to 0.");
3293 options->MinUptimeHidServDirectoryV2 = 0;
3296 if (options->RendPostPeriod < MIN_REND_POST_PERIOD) {
3297 log_warn(LD_CONFIG, "RendPostPeriod option is too short; "
3298 "raising to %d seconds.", MIN_REND_POST_PERIOD);
3299 options->RendPostPeriod = MIN_REND_POST_PERIOD;
3302 if (options->RendPostPeriod > MAX_DIR_PERIOD) {
3303 log_warn(LD_CONFIG, "RendPostPeriod is too large; clipping to %ds.",
3304 MAX_DIR_PERIOD);
3305 options->RendPostPeriod = MAX_DIR_PERIOD;
3308 if (options->MaxCircuitDirtiness < MIN_MAX_CIRCUIT_DIRTINESS) {
3309 log_warn(LD_CONFIG, "MaxCircuitDirtiness option is too short; "
3310 "raising to %d seconds.", MIN_MAX_CIRCUIT_DIRTINESS);
3311 options->MaxCircuitDirtiness = MIN_MAX_CIRCUIT_DIRTINESS;
3314 if (options->CircuitStreamTimeout &&
3315 options->CircuitStreamTimeout < MIN_CIRCUIT_STREAM_TIMEOUT) {
3316 log_warn(LD_CONFIG, "CircuitStreamTimeout option is too short; "
3317 "raising to %d seconds.", MIN_CIRCUIT_STREAM_TIMEOUT);
3318 options->CircuitStreamTimeout = MIN_CIRCUIT_STREAM_TIMEOUT;
3321 if (options->KeepalivePeriod < 1)
3322 REJECT("KeepalivePeriod option must be positive.");
3324 if (ensure_bandwidth_cap(&options->BandwidthRate,
3325 "BandwidthRate", msg) < 0)
3326 return -1;
3327 if (ensure_bandwidth_cap(&options->BandwidthBurst,
3328 "BandwidthBurst", msg) < 0)
3329 return -1;
3330 if (ensure_bandwidth_cap(&options->MaxAdvertisedBandwidth,
3331 "MaxAdvertisedBandwidth", msg) < 0)
3332 return -1;
3333 if (ensure_bandwidth_cap(&options->RelayBandwidthRate,
3334 "RelayBandwidthRate", msg) < 0)
3335 return -1;
3336 if (ensure_bandwidth_cap(&options->RelayBandwidthBurst,
3337 "RelayBandwidthBurst", msg) < 0)
3338 return -1;
3339 if (ensure_bandwidth_cap(&options->PerConnBWRate,
3340 "PerConnBWRate", msg) < 0)
3341 return -1;
3342 if (ensure_bandwidth_cap(&options->PerConnBWBurst,
3343 "PerConnBWBurst", msg) < 0)
3344 return -1;
3346 if (server_mode(options)) {
3347 if (options->BandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
3348 tor_asprintf(msg,
3349 "BandwidthRate is set to %d bytes/second. "
3350 "For servers, it must be at least %d.",
3351 (int)options->BandwidthRate,
3352 ROUTER_REQUIRED_MIN_BANDWIDTH);
3353 return -1;
3354 } else if (options->MaxAdvertisedBandwidth <
3355 ROUTER_REQUIRED_MIN_BANDWIDTH/2) {
3356 tor_asprintf(msg,
3357 "MaxAdvertisedBandwidth is set to %d bytes/second. "
3358 "For servers, it must be at least %d.",
3359 (int)options->MaxAdvertisedBandwidth,
3360 ROUTER_REQUIRED_MIN_BANDWIDTH/2);
3361 return -1;
3363 if (options->RelayBandwidthRate &&
3364 options->RelayBandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
3365 tor_asprintf(msg,
3366 "RelayBandwidthRate is set to %d bytes/second. "
3367 "For servers, it must be at least %d.",
3368 (int)options->RelayBandwidthRate,
3369 ROUTER_REQUIRED_MIN_BANDWIDTH);
3370 return -1;
3374 if (options->RelayBandwidthRate && !options->RelayBandwidthBurst)
3375 options->RelayBandwidthBurst = options->RelayBandwidthRate;
3377 if (options->RelayBandwidthRate > options->RelayBandwidthBurst)
3378 REJECT("RelayBandwidthBurst must be at least equal "
3379 "to RelayBandwidthRate.");
3381 if (options->BandwidthRate > options->BandwidthBurst)
3382 REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
3384 /* if they set relaybandwidth* really high but left bandwidth*
3385 * at the default, raise the defaults. */
3386 if (options->RelayBandwidthRate > options->BandwidthRate)
3387 options->BandwidthRate = options->RelayBandwidthRate;
3388 if (options->RelayBandwidthBurst > options->BandwidthBurst)
3389 options->BandwidthBurst = options->RelayBandwidthBurst;
3391 if (accounting_parse_options(options, 1)<0)
3392 REJECT("Failed to parse accounting options. See logs for details.");
3394 if (options->HTTPProxy) { /* parse it now */
3395 if (tor_addr_port_parse(options->HTTPProxy,
3396 &options->HTTPProxyAddr, &options->HTTPProxyPort) < 0)
3397 REJECT("HTTPProxy failed to parse or resolve. Please fix.");
3398 if (options->HTTPProxyPort == 0) { /* give it a default */
3399 options->HTTPProxyPort = 80;
3403 if (options->HTTPProxyAuthenticator) {
3404 if (strlen(options->HTTPProxyAuthenticator) >= 48)
3405 REJECT("HTTPProxyAuthenticator is too long (>= 48 chars).");
3408 if (options->HTTPSProxy) { /* parse it now */
3409 if (tor_addr_port_parse(options->HTTPSProxy,
3410 &options->HTTPSProxyAddr, &options->HTTPSProxyPort) <0)
3411 REJECT("HTTPSProxy failed to parse or resolve. Please fix.");
3412 if (options->HTTPSProxyPort == 0) { /* give it a default */
3413 options->HTTPSProxyPort = 443;
3417 if (options->HTTPSProxyAuthenticator) {
3418 if (strlen(options->HTTPSProxyAuthenticator) >= 48)
3419 REJECT("HTTPSProxyAuthenticator is too long (>= 48 chars).");
3422 if (options->Socks4Proxy) { /* parse it now */
3423 if (tor_addr_port_parse(options->Socks4Proxy,
3424 &options->Socks4ProxyAddr,
3425 &options->Socks4ProxyPort) <0)
3426 REJECT("Socks4Proxy failed to parse or resolve. Please fix.");
3427 if (options->Socks4ProxyPort == 0) { /* give it a default */
3428 options->Socks4ProxyPort = 1080;
3432 if (options->Socks5Proxy) { /* parse it now */
3433 if (tor_addr_port_parse(options->Socks5Proxy,
3434 &options->Socks5ProxyAddr,
3435 &options->Socks5ProxyPort) <0)
3436 REJECT("Socks5Proxy failed to parse or resolve. Please fix.");
3437 if (options->Socks5ProxyPort == 0) { /* give it a default */
3438 options->Socks5ProxyPort = 1080;
3442 if (options->Socks4Proxy && options->Socks5Proxy)
3443 REJECT("You cannot specify both Socks4Proxy and SOCKS5Proxy");
3445 if (options->Socks5ProxyUsername) {
3446 size_t len;
3448 len = strlen(options->Socks5ProxyUsername);
3449 if (len < 1 || len > 255)
3450 REJECT("Socks5ProxyUsername must be between 1 and 255 characters.");
3452 if (!options->Socks5ProxyPassword)
3453 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
3455 len = strlen(options->Socks5ProxyPassword);
3456 if (len < 1 || len > 255)
3457 REJECT("Socks5ProxyPassword must be between 1 and 255 characters.");
3458 } else if (options->Socks5ProxyPassword)
3459 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
3461 if (options->HashedControlPassword) {
3462 smartlist_t *sl = decode_hashed_passwords(options->HashedControlPassword);
3463 if (!sl) {
3464 REJECT("Bad HashedControlPassword: wrong length or bad encoding");
3465 } else {
3466 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3467 smartlist_free(sl);
3471 if (options->HashedControlSessionPassword) {
3472 smartlist_t *sl = decode_hashed_passwords(
3473 options->HashedControlSessionPassword);
3474 if (!sl) {
3475 REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
3476 } else {
3477 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3478 smartlist_free(sl);
3482 if (options->ControlListenAddress) {
3483 int all_are_local = 1;
3484 config_line_t *ln;
3485 for (ln = options->ControlListenAddress; ln; ln = ln->next) {
3486 if (strcmpstart(ln->value, "127."))
3487 all_are_local = 0;
3489 if (!all_are_local) {
3490 if (!options->HashedControlPassword &&
3491 !options->HashedControlSessionPassword &&
3492 !options->CookieAuthentication) {
3493 log_warn(LD_CONFIG,
3494 "You have a ControlListenAddress set to accept "
3495 "unauthenticated connections from a non-local address. "
3496 "This means that programs not running on your computer "
3497 "can reconfigure your Tor, without even having to guess a "
3498 "password. That's so bad that I'm closing your ControlPort "
3499 "for you. If you need to control your Tor remotely, try "
3500 "enabling authentication and using a tool like stunnel or "
3501 "ssh to encrypt remote access.");
3502 options->ControlPort = 0;
3503 } else {
3504 log_warn(LD_CONFIG, "You have a ControlListenAddress set to accept "
3505 "connections from a non-local address. This means that "
3506 "programs not running on your computer can reconfigure your "
3507 "Tor. That's pretty bad, since the controller "
3508 "protocol isn't encrypted! Maybe you should just listen on "
3509 "127.0.0.1 and use a tool like stunnel or ssh to encrypt "
3510 "remote connections to your control port.");
3515 if (options->ControlPort && !options->HashedControlPassword &&
3516 !options->HashedControlSessionPassword &&
3517 !options->CookieAuthentication) {
3518 log_warn(LD_CONFIG, "ControlPort is open, but no authentication method "
3519 "has been configured. This means that any program on your "
3520 "computer can reconfigure your Tor. That's bad! You should "
3521 "upgrade your Tor controller as soon as possible.");
3524 if (options->CookieAuthFileGroupReadable && !options->CookieAuthFile) {
3525 log_warn(LD_CONFIG, "You set the CookieAuthFileGroupReadable but did "
3526 "not configure a the path for the cookie file via "
3527 "CookieAuthFile. This means your cookie will not be group "
3528 "readable.");
3531 if (options->UseEntryGuards && ! options->NumEntryGuards)
3532 REJECT("Cannot enable UseEntryGuards with NumEntryGuards set to 0");
3534 if (check_nickname_list(options->MyFamily, "MyFamily", msg))
3535 return -1;
3536 for (cl = options->NodeFamilies; cl; cl = cl->next) {
3537 if (check_nickname_list(cl->value, "NodeFamily", msg))
3538 return -1;
3541 if (validate_addr_policies(options, msg) < 0)
3542 return -1;
3544 if (validate_dir_authorities(options, old_options) < 0)
3545 REJECT("Directory authority line did not parse. See logs for details.");
3547 if (options->UseBridges && !options->Bridges)
3548 REJECT("If you set UseBridges, you must specify at least one bridge.");
3549 if (options->UseBridges && !options->TunnelDirConns)
3550 REJECT("If you set UseBridges, you must set TunnelDirConns.");
3551 if (options->Bridges) {
3552 for (cl = options->Bridges; cl; cl = cl->next) {
3553 if (parse_bridge_line(cl->value, 1)<0)
3554 REJECT("Bridge line did not parse. See logs for details.");
3558 if (options->ConstrainedSockets) {
3559 /* If the user wants to constrain socket buffer use, make sure the desired
3560 * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
3561 if (options->ConstrainedSockSize < MIN_CONSTRAINED_TCP_BUFFER ||
3562 options->ConstrainedSockSize > MAX_CONSTRAINED_TCP_BUFFER ||
3563 options->ConstrainedSockSize % 1024) {
3564 tor_asprintf(msg,
3565 "ConstrainedSockSize is invalid. Must be a value between %d and %d "
3566 "in 1024 byte increments.",
3567 MIN_CONSTRAINED_TCP_BUFFER, MAX_CONSTRAINED_TCP_BUFFER);
3568 return -1;
3570 if (options->DirPort) {
3571 /* Providing cached directory entries while system TCP buffers are scarce
3572 * will exacerbate the socket errors. Suggest that this be disabled. */
3573 COMPLAIN("You have requested constrained socket buffers while also "
3574 "serving directory entries via DirPort. It is strongly "
3575 "suggested that you disable serving directory requests when "
3576 "system TCP buffer resources are scarce.");
3580 if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
3581 options->V3AuthVotingInterval/2) {
3582 REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
3583 "V3AuthVotingInterval");
3585 if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS)
3586 REJECT("V3AuthVoteDelay is way too low.");
3587 if (options->V3AuthDistDelay < MIN_DIST_SECONDS)
3588 REJECT("V3AuthDistDelay is way too low.");
3590 if (options->V3AuthNIntervalsValid < 2)
3591 REJECT("V3AuthNIntervalsValid must be at least 2.");
3593 if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL) {
3594 REJECT("V3AuthVotingInterval is insanely low.");
3595 } else if (options->V3AuthVotingInterval > 24*60*60) {
3596 REJECT("V3AuthVotingInterval is insanely high.");
3597 } else if (((24*60*60) % options->V3AuthVotingInterval) != 0) {
3598 COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
3601 if (rend_config_services(options, 1) < 0)
3602 REJECT("Failed to configure rendezvous options. See logs for details.");
3604 /* Parse client-side authorization for hidden services. */
3605 if (rend_parse_service_authorization(options, 1) < 0)
3606 REJECT("Failed to configure client authorization for hidden services. "
3607 "See logs for details.");
3609 if (parse_virtual_addr_network(options->VirtualAddrNetwork, 1, NULL)<0)
3610 return -1;
3612 if (options->PreferTunneledDirConns && !options->TunnelDirConns)
3613 REJECT("Must set TunnelDirConns if PreferTunneledDirConns is set.");
3615 if ((options->Socks4Proxy || options->Socks5Proxy) &&
3616 !options->HTTPProxy && !options->PreferTunneledDirConns)
3617 REJECT("When Socks4Proxy or Socks5Proxy is configured, "
3618 "PreferTunneledDirConns and TunnelDirConns must both be "
3619 "set to 1, or HTTPProxy must be configured.");
3621 if (options->AutomapHostsSuffixes) {
3622 SMARTLIST_FOREACH(options->AutomapHostsSuffixes, char *, suf,
3624 size_t len = strlen(suf);
3625 if (len && suf[len-1] == '.')
3626 suf[len-1] = '\0';
3630 if (options->TestingTorNetwork && !options->DirServers) {
3631 REJECT("TestingTorNetwork may only be configured in combination with "
3632 "a non-default set of DirServers.");
3635 if (options->AllowSingleHopExits && !options->DirServers) {
3636 COMPLAIN("You have set AllowSingleHopExits; now your relay will allow "
3637 "others to make one-hop exits. However, since by default most "
3638 "clients avoid relays that set this option, most clients will "
3639 "ignore you.");
3642 /*XXXX022 checking for defaults manually like this is a bit fragile.*/
3644 /* Keep changes to hard-coded values synchronous to man page and default
3645 * values table. */
3646 if (options->TestingV3AuthInitialVotingInterval != 30*60 &&
3647 !options->TestingTorNetwork) {
3648 REJECT("TestingV3AuthInitialVotingInterval may only be changed in testing "
3649 "Tor networks!");
3650 } else if (options->TestingV3AuthInitialVotingInterval < MIN_VOTE_INTERVAL) {
3651 REJECT("TestingV3AuthInitialVotingInterval is insanely low.");
3652 } else if (((30*60) % options->TestingV3AuthInitialVotingInterval) != 0) {
3653 REJECT("TestingV3AuthInitialVotingInterval does not divide evenly into "
3654 "30 minutes.");
3657 if (options->TestingV3AuthInitialVoteDelay != 5*60 &&
3658 !options->TestingTorNetwork) {
3659 REJECT("TestingV3AuthInitialVoteDelay may only be changed in testing "
3660 "Tor networks!");
3661 } else if (options->TestingV3AuthInitialVoteDelay < MIN_VOTE_SECONDS) {
3662 REJECT("TestingV3AuthInitialVoteDelay is way too low.");
3665 if (options->TestingV3AuthInitialDistDelay != 5*60 &&
3666 !options->TestingTorNetwork) {
3667 REJECT("TestingV3AuthInitialDistDelay may only be changed in testing "
3668 "Tor networks!");
3669 } else if (options->TestingV3AuthInitialDistDelay < MIN_DIST_SECONDS) {
3670 REJECT("TestingV3AuthInitialDistDelay is way too low.");
3673 if (options->TestingV3AuthInitialVoteDelay +
3674 options->TestingV3AuthInitialDistDelay >=
3675 options->TestingV3AuthInitialVotingInterval/2) {
3676 REJECT("TestingV3AuthInitialVoteDelay plus TestingV3AuthInitialDistDelay "
3677 "must be less than half TestingV3AuthInitialVotingInterval");
3680 if (options->TestingAuthDirTimeToLearnReachability != 30*60 &&
3681 !options->TestingTorNetwork) {
3682 REJECT("TestingAuthDirTimeToLearnReachability may only be changed in "
3683 "testing Tor networks!");
3684 } else if (options->TestingAuthDirTimeToLearnReachability < 0) {
3685 REJECT("TestingAuthDirTimeToLearnReachability must be non-negative.");
3686 } else if (options->TestingAuthDirTimeToLearnReachability > 2*60*60) {
3687 COMPLAIN("TestingAuthDirTimeToLearnReachability is insanely high.");
3690 if (options->TestingEstimatedDescriptorPropagationTime != 10*60 &&
3691 !options->TestingTorNetwork) {
3692 REJECT("TestingEstimatedDescriptorPropagationTime may only be changed in "
3693 "testing Tor networks!");
3694 } else if (options->TestingEstimatedDescriptorPropagationTime < 0) {
3695 REJECT("TestingEstimatedDescriptorPropagationTime must be non-negative.");
3696 } else if (options->TestingEstimatedDescriptorPropagationTime > 60*60) {
3697 COMPLAIN("TestingEstimatedDescriptorPropagationTime is insanely high.");
3700 if (options->TestingTorNetwork) {
3701 log_warn(LD_CONFIG, "TestingTorNetwork is set. This will make your node "
3702 "almost unusable in the public Tor network, and is "
3703 "therefore only advised if you are building a "
3704 "testing Tor network!");
3707 if (options->AccelName && !options->HardwareAccel)
3708 options->HardwareAccel = 1;
3709 if (options->AccelDir && !options->AccelName)
3710 REJECT("Can't use hardware crypto accelerator dir without engine name.");
3712 if (options->PublishServerDescriptor)
3713 SMARTLIST_FOREACH(options->PublishServerDescriptor, const char *, pubdes, {
3714 if (!strcmp(pubdes, "1") || !strcmp(pubdes, "0"))
3715 if (smartlist_len(options->PublishServerDescriptor) > 1) {
3716 COMPLAIN("You have passed a list of multiple arguments to the "
3717 "PublishServerDescriptor option that includes 0 or 1. "
3718 "0 or 1 should only be used as the sole argument. "
3719 "This configuration will be rejected in a future release.");
3720 break;
3724 if (options->BridgeRelay == 1 && options->ORPort == 0)
3725 REJECT("BridgeRelay is 1, ORPort is 0. This is an invalid combination.");
3727 return 0;
3728 #undef REJECT
3729 #undef COMPLAIN
3732 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
3733 * equal strings. */
3734 static int
3735 opt_streq(const char *s1, const char *s2)
3737 if (!s1 && !s2)
3738 return 1;
3739 else if (s1 && s2 && !strcmp(s1,s2))
3740 return 1;
3741 else
3742 return 0;
3745 /** Check if any of the previous options have changed but aren't allowed to. */
3746 static int
3747 options_transition_allowed(or_options_t *old, or_options_t *new_val,
3748 char **msg)
3750 if (!old)
3751 return 0;
3753 if (!opt_streq(old->PidFile, new_val->PidFile)) {
3754 *msg = tor_strdup("PidFile is not allowed to change.");
3755 return -1;
3758 if (old->RunAsDaemon != new_val->RunAsDaemon) {
3759 *msg = tor_strdup("While Tor is running, changing RunAsDaemon "
3760 "is not allowed.");
3761 return -1;
3764 if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
3765 tor_asprintf(msg,
3766 "While Tor is running, changing DataDirectory "
3767 "(\"%s\"->\"%s\") is not allowed.",
3768 old->DataDirectory, new_val->DataDirectory);
3769 return -1;
3772 if (!opt_streq(old->User, new_val->User)) {
3773 *msg = tor_strdup("While Tor is running, changing User is not allowed.");
3774 return -1;
3777 if ((old->HardwareAccel != new_val->HardwareAccel)
3778 || !opt_streq(old->AccelName, new_val->AccelName)
3779 || !opt_streq(old->AccelDir, new_val->AccelDir)) {
3780 *msg = tor_strdup("While Tor is running, changing OpenSSL hardware "
3781 "acceleration engine is not allowed.");
3782 return -1;
3785 if (old->TestingTorNetwork != new_val->TestingTorNetwork) {
3786 *msg = tor_strdup("While Tor is running, changing TestingTorNetwork "
3787 "is not allowed.");
3788 return -1;
3791 if (old->DisableAllSwap != new_val->DisableAllSwap) {
3792 *msg = tor_strdup("While Tor is running, changing DisableAllSwap "
3793 "is not allowed.");
3794 return -1;
3797 return 0;
3800 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3801 * will require us to rotate the CPU and DNS workers; else return 0. */
3802 static int
3803 options_transition_affects_workers(or_options_t *old_options,
3804 or_options_t *new_options)
3806 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
3807 old_options->NumCPUs != new_options->NumCPUs ||
3808 old_options->ORPort != new_options->ORPort ||
3809 old_options->ServerDNSSearchDomains !=
3810 new_options->ServerDNSSearchDomains ||
3811 old_options->SafeLogging != new_options->SafeLogging ||
3812 old_options->ClientOnly != new_options->ClientOnly ||
3813 !config_lines_eq(old_options->Logs, new_options->Logs))
3814 return 1;
3816 /* Check whether log options match. */
3818 /* Nothing that changed matters. */
3819 return 0;
3822 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
3823 * will require us to generate a new descriptor; else return 0. */
3824 static int
3825 options_transition_affects_descriptor(or_options_t *old_options,
3826 or_options_t *new_options)
3828 /* XXX We can be smarter here. If your DirPort isn't being
3829 * published and you just turned it off, no need to republish. Etc. */
3830 if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
3831 !opt_streq(old_options->Nickname,new_options->Nickname) ||
3832 !opt_streq(old_options->Address,new_options->Address) ||
3833 !config_lines_eq(old_options->ExitPolicy,new_options->ExitPolicy) ||
3834 old_options->ExitPolicyRejectPrivate !=
3835 new_options->ExitPolicyRejectPrivate ||
3836 old_options->ORPort != new_options->ORPort ||
3837 old_options->DirPort != new_options->DirPort ||
3838 old_options->ClientOnly != new_options->ClientOnly ||
3839 old_options->_PublishServerDescriptor !=
3840 new_options->_PublishServerDescriptor ||
3841 get_effective_bwrate(old_options) != get_effective_bwrate(new_options) ||
3842 get_effective_bwburst(old_options) !=
3843 get_effective_bwburst(new_options) ||
3844 !opt_streq(old_options->ContactInfo, new_options->ContactInfo) ||
3845 !opt_streq(old_options->MyFamily, new_options->MyFamily) ||
3846 !opt_streq(old_options->AccountingStart, new_options->AccountingStart) ||
3847 old_options->AccountingMax != new_options->AccountingMax)
3848 return 1;
3850 return 0;
3853 #ifdef MS_WINDOWS
3854 /** Return the directory on windows where we expect to find our application
3855 * data. */
3856 static char *
3857 get_windows_conf_root(void)
3859 static int is_set = 0;
3860 static char path[MAX_PATH+1];
3861 TCHAR tpath[MAX_PATH] = {0};
3863 LPITEMIDLIST idl;
3864 IMalloc *m;
3865 HRESULT result;
3867 if (is_set)
3868 return path;
3870 /* Find X:\documents and settings\username\application data\ .
3871 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
3873 #ifdef ENABLE_LOCAL_APPDATA
3874 #define APPDATA_PATH CSIDL_LOCAL_APPDATA
3875 #else
3876 #define APPDATA_PATH CSIDL_APPDATA
3877 #endif
3878 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, APPDATA_PATH, &idl))) {
3879 getcwd(path,MAX_PATH);
3880 is_set = 1;
3881 log_warn(LD_CONFIG,
3882 "I couldn't find your application data folder: are you "
3883 "running an ancient version of Windows 95? Defaulting to \"%s\"",
3884 path);
3885 return path;
3887 /* Convert the path from an "ID List" (whatever that is!) to a path. */
3888 result = SHGetPathFromIDList(idl, tpath);
3889 #ifdef UNICODE
3890 wcstombs(path,tpath,MAX_PATH);
3891 #else
3892 strlcpy(path,tpath,sizeof(path));
3893 #endif
3895 /* Now we need to free the memory that the path-idl was stored in. In
3896 * typical Windows fashion, we can't just call 'free()' on it. */
3897 SHGetMalloc(&m);
3898 if (m) {
3899 m->lpVtbl->Free(m, idl);
3900 m->lpVtbl->Release(m);
3902 if (!SUCCEEDED(result)) {
3903 return NULL;
3905 strlcat(path,"\\tor",MAX_PATH);
3906 is_set = 1;
3907 return path;
3909 #endif
3911 /** Return the default location for our torrc file. */
3912 static const char *
3913 get_default_conf_file(void)
3915 #ifdef MS_WINDOWS
3916 static char path[MAX_PATH+1];
3917 strlcpy(path, get_windows_conf_root(), MAX_PATH);
3918 strlcat(path,"\\torrc",MAX_PATH);
3919 return path;
3920 #else
3921 return (CONFDIR "/torrc");
3922 #endif
3925 /** Verify whether lst is a string containing valid-looking comma-separated
3926 * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
3928 static int
3929 check_nickname_list(const char *lst, const char *name, char **msg)
3931 int r = 0;
3932 smartlist_t *sl;
3934 if (!lst)
3935 return 0;
3936 sl = smartlist_create();
3938 smartlist_split_string(sl, lst, ",",
3939 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK|SPLIT_STRIP_SPACE, 0);
3941 SMARTLIST_FOREACH(sl, const char *, s,
3943 if (!is_legal_nickname_or_hexdigest(s)) {
3944 tor_asprintf(msg, "Invalid nickname '%s' in %s line", s, name);
3945 r = -1;
3946 break;
3949 SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
3950 smartlist_free(sl);
3951 return r;
3954 /** Learn config file name from command line arguments, or use the default */
3955 static char *
3956 find_torrc_filename(int argc, char **argv,
3957 int *using_default_torrc, int *ignore_missing_torrc)
3959 char *fname=NULL;
3960 int i;
3962 for (i = 1; i < argc; ++i) {
3963 if (i < argc-1 && !strcmp(argv[i],"-f")) {
3964 if (fname) {
3965 log(LOG_WARN, LD_CONFIG, "Duplicate -f options on command line.");
3966 tor_free(fname);
3968 fname = expand_filename(argv[i+1]);
3969 *using_default_torrc = 0;
3970 ++i;
3971 } else if (!strcmp(argv[i],"--ignore-missing-torrc")) {
3972 *ignore_missing_torrc = 1;
3976 if (*using_default_torrc) {
3977 /* didn't find one, try CONFDIR */
3978 const char *dflt = get_default_conf_file();
3979 if (dflt && file_status(dflt) == FN_FILE) {
3980 fname = tor_strdup(dflt);
3981 } else {
3982 #ifndef MS_WINDOWS
3983 char *fn;
3984 fn = expand_filename("~/.torrc");
3985 if (fn && file_status(fn) == FN_FILE) {
3986 fname = fn;
3987 } else {
3988 tor_free(fn);
3989 fname = tor_strdup(dflt);
3991 #else
3992 fname = tor_strdup(dflt);
3993 #endif
3996 return fname;
3999 /** Load torrc from disk, setting torrc_fname if successful */
4000 static char *
4001 load_torrc_from_disk(int argc, char **argv)
4003 char *fname=NULL;
4004 char *cf = NULL;
4005 int using_default_torrc = 1;
4006 int ignore_missing_torrc = 0;
4008 fname = find_torrc_filename(argc, argv,
4009 &using_default_torrc, &ignore_missing_torrc);
4010 tor_assert(fname);
4011 log(LOG_DEBUG, LD_CONFIG, "Opening config file \"%s\"", fname);
4013 tor_free(torrc_fname);
4014 torrc_fname = fname;
4016 /* Open config file */
4017 if (file_status(fname) != FN_FILE ||
4018 !(cf = read_file_to_str(fname,0,NULL))) {
4019 if (using_default_torrc == 1 || ignore_missing_torrc ) {
4020 log(LOG_NOTICE, LD_CONFIG, "Configuration file \"%s\" not present, "
4021 "using reasonable defaults.", fname);
4022 tor_free(fname); /* sets fname to NULL */
4023 torrc_fname = NULL;
4024 cf = tor_strdup("");
4025 } else {
4026 log(LOG_WARN, LD_CONFIG,
4027 "Unable to open configuration file \"%s\".", fname);
4028 goto err;
4032 return cf;
4033 err:
4034 tor_free(fname);
4035 torrc_fname = NULL;
4036 return NULL;
4039 /** Read a configuration file into <b>options</b>, finding the configuration
4040 * file location based on the command line. After loading the file
4041 * call options_init_from_string() to load the config.
4042 * Return 0 if success, -1 if failure. */
4044 options_init_from_torrc(int argc, char **argv)
4046 char *cf=NULL;
4047 int i, retval, command;
4048 static char **backup_argv;
4049 static int backup_argc;
4050 char *command_arg = NULL;
4051 char *errmsg=NULL;
4053 if (argv) { /* first time we're called. save command line args */
4054 backup_argv = argv;
4055 backup_argc = argc;
4056 } else { /* we're reloading. need to clean up old options first. */
4057 argv = backup_argv;
4058 argc = backup_argc;
4060 if (argc > 1 && (!strcmp(argv[1], "-h") || !strcmp(argv[1],"--help"))) {
4061 print_usage();
4062 exit(0);
4064 if (argc > 1 && !strcmp(argv[1], "--list-torrc-options")) {
4065 /* For documenting validating whether we've documented everything. */
4066 list_torrc_options();
4067 exit(0);
4070 if (argc > 1 && (!strcmp(argv[1],"--version"))) {
4071 printf("Tor version %s.\n",get_version());
4072 exit(0);
4074 if (argc > 1 && (!strcmp(argv[1],"--digests"))) {
4075 printf("Tor version %s.\n",get_version());
4076 printf("%s", libor_get_digests());
4077 printf("%s", tor_get_digests());
4078 exit(0);
4081 /* Go through command-line variables */
4082 if (!global_cmdline_options) {
4083 /* Or we could redo the list every time we pass this place.
4084 * It does not really matter */
4085 if (config_get_commandlines(argc, argv, &global_cmdline_options) < 0) {
4086 goto err;
4090 command = CMD_RUN_TOR;
4091 for (i = 1; i < argc; ++i) {
4092 if (!strcmp(argv[i],"--list-fingerprint")) {
4093 command = CMD_LIST_FINGERPRINT;
4094 } else if (!strcmp(argv[i],"--hash-password")) {
4095 command = CMD_HASH_PASSWORD;
4096 command_arg = tor_strdup( (i < argc-1) ? argv[i+1] : "");
4097 ++i;
4098 } else if (!strcmp(argv[i],"--verify-config")) {
4099 command = CMD_VERIFY_CONFIG;
4103 if (command == CMD_HASH_PASSWORD) {
4104 cf = tor_strdup("");
4105 } else {
4106 cf = load_torrc_from_disk(argc, argv);
4107 if (!cf)
4108 goto err;
4111 retval = options_init_from_string(cf, command, command_arg, &errmsg);
4112 tor_free(cf);
4113 if (retval < 0)
4114 goto err;
4116 return 0;
4118 err:
4119 if (errmsg) {
4120 log(LOG_WARN,LD_CONFIG,"%s", errmsg);
4121 tor_free(errmsg);
4123 return -1;
4126 /** Load the options from the configuration in <b>cf</b>, validate
4127 * them for consistency and take actions based on them.
4129 * Return 0 if success, negative on error:
4130 * * -1 for general errors.
4131 * * -2 for failure to parse/validate,
4132 * * -3 for transition not allowed
4133 * * -4 for error while setting the new options
4135 setopt_err_t
4136 options_init_from_string(const char *cf,
4137 int command, const char *command_arg,
4138 char **msg)
4140 or_options_t *oldoptions, *newoptions;
4141 config_line_t *cl;
4142 int retval;
4143 setopt_err_t err = SETOPT_ERR_MISC;
4144 tor_assert(msg);
4146 oldoptions = global_options; /* get_options unfortunately asserts if
4147 this is the first time we run*/
4149 newoptions = tor_malloc_zero(sizeof(or_options_t));
4150 newoptions->_magic = OR_OPTIONS_MAGIC;
4151 options_init(newoptions);
4152 newoptions->command = command;
4153 newoptions->command_arg = command_arg;
4155 /* get config lines, assign them */
4156 retval = config_get_lines(cf, &cl);
4157 if (retval < 0) {
4158 err = SETOPT_ERR_PARSE;
4159 goto err;
4161 retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
4162 config_free_lines(cl);
4163 if (retval < 0) {
4164 err = SETOPT_ERR_PARSE;
4165 goto err;
4168 /* Go through command-line variables too */
4169 retval = config_assign(&options_format, newoptions,
4170 global_cmdline_options, 0, 0, msg);
4171 if (retval < 0) {
4172 err = SETOPT_ERR_PARSE;
4173 goto err;
4176 /* If this is a testing network configuration, change defaults
4177 * for a list of dependent config options, re-initialize newoptions
4178 * with the new defaults, and assign all options to it second time. */
4179 if (newoptions->TestingTorNetwork) {
4180 /* XXXX this is a bit of a kludge. perhaps there's a better way to do
4181 * this? We could, for example, make the parsing algorithm do two passes
4182 * over the configuration. If it finds any "suite" options like
4183 * TestingTorNetwork, it could change the defaults before its second pass.
4184 * Not urgent so long as this seems to work, but at any sign of trouble,
4185 * let's clean it up. -NM */
4187 /* Change defaults. */
4188 int i;
4189 for (i = 0; testing_tor_network_defaults[i].name; ++i) {
4190 config_var_t *new_var = &testing_tor_network_defaults[i];
4191 config_var_t *old_var =
4192 config_find_option(&options_format, new_var->name);
4193 tor_assert(new_var);
4194 tor_assert(old_var);
4195 old_var->initvalue = new_var->initvalue;
4198 /* Clear newoptions and re-initialize them with new defaults. */
4199 config_free(&options_format, newoptions);
4200 newoptions = tor_malloc_zero(sizeof(or_options_t));
4201 newoptions->_magic = OR_OPTIONS_MAGIC;
4202 options_init(newoptions);
4203 newoptions->command = command;
4204 newoptions->command_arg = command_arg;
4206 /* Assign all options a second time. */
4207 retval = config_get_lines(cf, &cl);
4208 if (retval < 0) {
4209 err = SETOPT_ERR_PARSE;
4210 goto err;
4212 retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
4213 config_free_lines(cl);
4214 if (retval < 0) {
4215 err = SETOPT_ERR_PARSE;
4216 goto err;
4218 retval = config_assign(&options_format, newoptions,
4219 global_cmdline_options, 0, 0, msg);
4220 if (retval < 0) {
4221 err = SETOPT_ERR_PARSE;
4222 goto err;
4226 /* Validate newoptions */
4227 if (options_validate(oldoptions, newoptions, 0, msg) < 0) {
4228 err = SETOPT_ERR_PARSE; /*XXX make this a separate return value.*/
4229 goto err;
4232 if (options_transition_allowed(oldoptions, newoptions, msg) < 0) {
4233 err = SETOPT_ERR_TRANSITION;
4234 goto err;
4237 if (set_options(newoptions, msg)) {
4238 err = SETOPT_ERR_SETTING;
4239 goto err; /* frees and replaces old options */
4242 return SETOPT_OK;
4244 err:
4245 config_free(&options_format, newoptions);
4246 if (*msg) {
4247 char *old_msg = *msg;
4248 tor_asprintf(msg, "Failed to parse/validate config: %s", old_msg);
4249 tor_free(old_msg);
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 * is 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;
4670 tor_assert(fname);
4672 switch (file_status(fname)) {
4673 case FN_FILE:
4674 old_val = read_file_to_str(fname, 0, NULL);
4675 if (strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
4676 rename_old = 1;
4678 tor_free(old_val);
4679 break;
4680 case FN_NOENT:
4681 break;
4682 case FN_ERROR:
4683 case FN_DIR:
4684 default:
4685 log_warn(LD_CONFIG,
4686 "Config file \"%s\" is not a file? Failing.", fname);
4687 return -1;
4690 if (!(new_conf = options_dump(options, 1))) {
4691 log_warn(LD_BUG, "Couldn't get configuration string");
4692 goto err;
4695 tor_asprintf(&new_val, "%s\n%s\n\n%s",
4696 GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
4698 if (rename_old) {
4699 int i = 1;
4700 size_t fn_tmp_len = strlen(fname)+32;
4701 char *fn_tmp;
4702 tor_assert(fn_tmp_len > strlen(fname)); /*check for overflow*/
4703 fn_tmp = tor_malloc(fn_tmp_len);
4704 while (1) {
4705 if (tor_snprintf(fn_tmp, fn_tmp_len, "%s.orig.%d", fname, i)<0) {
4706 log_warn(LD_BUG, "tor_snprintf failed inexplicably");
4707 tor_free(fn_tmp);
4708 goto err;
4710 if (file_status(fn_tmp) == FN_NOENT)
4711 break;
4712 ++i;
4714 log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
4715 if (rename(fname, fn_tmp) < 0) {
4716 log_warn(LD_FS,
4717 "Couldn't rename configuration file \"%s\" to \"%s\": %s",
4718 fname, fn_tmp, strerror(errno));
4719 tor_free(fn_tmp);
4720 goto err;
4722 tor_free(fn_tmp);
4725 if (write_str_to_file(fname, new_val, 0) < 0)
4726 goto err;
4728 r = 0;
4729 goto done;
4730 err:
4731 r = -1;
4732 done:
4733 tor_free(new_val);
4734 tor_free(new_conf);
4735 return r;
4739 * Save the current configuration file value to disk. Return 0 on
4740 * success, -1 on failure.
4743 options_save_current(void)
4745 /* This fails if we can't write to our configuration file.
4747 * If we try falling back to datadirectory or something, we have a better
4748 * chance of saving the configuration, but a better chance of doing
4749 * something the user never expected. */
4750 return write_configuration_file(get_torrc_fname(), get_options());
4753 /** Mapping from a unit name to a multiplier for converting that unit into a
4754 * base unit. */
4755 struct unit_table_t {
4756 const char *unit;
4757 uint64_t multiplier;
4760 /** Table to map the names of memory units to the number of bytes they
4761 * contain. */
4762 static struct unit_table_t memory_units[] = {
4763 { "", 1 },
4764 { "b", 1<< 0 },
4765 { "byte", 1<< 0 },
4766 { "bytes", 1<< 0 },
4767 { "kb", 1<<10 },
4768 { "kbyte", 1<<10 },
4769 { "kbytes", 1<<10 },
4770 { "kilobyte", 1<<10 },
4771 { "kilobytes", 1<<10 },
4772 { "m", 1<<20 },
4773 { "mb", 1<<20 },
4774 { "mbyte", 1<<20 },
4775 { "mbytes", 1<<20 },
4776 { "megabyte", 1<<20 },
4777 { "megabytes", 1<<20 },
4778 { "gb", 1<<30 },
4779 { "gbyte", 1<<30 },
4780 { "gbytes", 1<<30 },
4781 { "gigabyte", 1<<30 },
4782 { "gigabytes", 1<<30 },
4783 { "tb", U64_LITERAL(1)<<40 },
4784 { "terabyte", U64_LITERAL(1)<<40 },
4785 { "terabytes", U64_LITERAL(1)<<40 },
4786 { NULL, 0 },
4789 /** Table to map the names of time units to the number of seconds they
4790 * contain. */
4791 static struct unit_table_t time_units[] = {
4792 { "", 1 },
4793 { "second", 1 },
4794 { "seconds", 1 },
4795 { "minute", 60 },
4796 { "minutes", 60 },
4797 { "hour", 60*60 },
4798 { "hours", 60*60 },
4799 { "day", 24*60*60 },
4800 { "days", 24*60*60 },
4801 { "week", 7*24*60*60 },
4802 { "weeks", 7*24*60*60 },
4803 { NULL, 0 },
4806 /** Parse a string <b>val</b> containing a number, zero or more
4807 * spaces, and an optional unit string. If the unit appears in the
4808 * table <b>u</b>, then multiply the number by the unit multiplier.
4809 * On success, set *<b>ok</b> to 1 and return this product.
4810 * Otherwise, set *<b>ok</b> to 0.
4812 static uint64_t
4813 config_parse_units(const char *val, struct unit_table_t *u, int *ok)
4815 uint64_t v = 0;
4816 double d = 0;
4817 int use_float = 0;
4818 char *cp;
4820 tor_assert(ok);
4822 v = tor_parse_uint64(val, 10, 0, UINT64_MAX, ok, &cp);
4823 if (!*ok || (cp && *cp == '.')) {
4824 d = tor_parse_double(val, 0, UINT64_MAX, ok, &cp);
4825 if (!*ok)
4826 goto done;
4827 use_float = 1;
4830 if (!cp) {
4831 *ok = 1;
4832 v = use_float ? DBL_TO_U64(d) : v;
4833 goto done;
4836 cp = (char*) eat_whitespace(cp);
4838 for ( ;u->unit;++u) {
4839 if (!strcasecmp(u->unit, cp)) {
4840 if (use_float)
4841 v = u->multiplier * d;
4842 else
4843 v *= u->multiplier;
4844 *ok = 1;
4845 goto done;
4848 log_warn(LD_CONFIG, "Unknown unit '%s'.", cp);
4849 *ok = 0;
4850 done:
4852 if (*ok)
4853 return v;
4854 else
4855 return 0;
4858 /** Parse a string in the format "number unit", where unit is a unit of
4859 * information (byte, KB, M, etc). On success, set *<b>ok</b> to true
4860 * and return the number of bytes specified. Otherwise, set
4861 * *<b>ok</b> to false and return 0. */
4862 static uint64_t
4863 config_parse_memunit(const char *s, int *ok)
4865 uint64_t u = config_parse_units(s, memory_units, ok);
4866 return u;
4869 /** Parse a string in the format "number unit", where unit is a unit of time.
4870 * On success, set *<b>ok</b> to true and return the number of seconds in
4871 * the provided interval. Otherwise, set *<b>ok</b> to 0 and return -1.
4873 static int
4874 config_parse_interval(const char *s, int *ok)
4876 uint64_t r;
4877 r = config_parse_units(s, time_units, ok);
4878 if (!ok)
4879 return -1;
4880 if (r > INT_MAX) {
4881 log_warn(LD_CONFIG, "Interval '%s' is too long", s);
4882 *ok = 0;
4883 return -1;
4885 return (int)r;
4889 * Initialize the libevent library.
4891 static void
4892 init_libevent(void)
4894 const char *badness=NULL;
4896 configure_libevent_logging();
4897 /* If the kernel complains that some method (say, epoll) doesn't
4898 * exist, we don't care about it, since libevent will cope.
4900 suppress_libevent_log_msg("Function not implemented");
4902 tor_check_libevent_header_compatibility();
4904 tor_libevent_initialize();
4906 suppress_libevent_log_msg(NULL);
4908 tor_check_libevent_version(tor_libevent_get_method(),
4909 get_options()->ORPort != 0,
4910 &badness);
4911 if (badness) {
4912 const char *v = tor_libevent_get_version_str();
4913 const char *m = tor_libevent_get_method();
4914 control_event_general_status(LOG_WARN,
4915 "BAD_LIBEVENT VERSION=%s METHOD=%s BADNESS=%s RECOVERED=NO",
4916 v, m, badness);
4920 /** Return the persistent state struct for this Tor. */
4921 or_state_t *
4922 get_or_state(void)
4924 tor_assert(global_state);
4925 return global_state;
4928 /** Return a newly allocated string holding a filename relative to the data
4929 * directory. If <b>sub1</b> is present, it is the first path component after
4930 * the data directory. If <b>sub2</b> is also present, it is the second path
4931 * component after the data directory. If <b>suffix</b> is present, it
4932 * is appended to the filename.
4934 * Examples:
4935 * get_datadir_fname2_suffix("a", NULL, NULL) -> $DATADIR/a
4936 * get_datadir_fname2_suffix("a", NULL, ".tmp") -> $DATADIR/a.tmp
4937 * get_datadir_fname2_suffix("a", "b", ".tmp") -> $DATADIR/a/b/.tmp
4938 * get_datadir_fname2_suffix("a", "b", NULL) -> $DATADIR/a/b
4940 * Note: Consider using the get_datadir_fname* macros in or.h.
4942 char *
4943 options_get_datadir_fname2_suffix(or_options_t *options,
4944 const char *sub1, const char *sub2,
4945 const char *suffix)
4947 char *fname = NULL;
4948 size_t len;
4949 tor_assert(options);
4950 tor_assert(options->DataDirectory);
4951 tor_assert(sub1 || !sub2); /* If sub2 is present, sub1 must be present. */
4952 len = strlen(options->DataDirectory);
4953 if (sub1) {
4954 len += strlen(sub1)+1;
4955 if (sub2)
4956 len += strlen(sub2)+1;
4958 if (suffix)
4959 len += strlen(suffix);
4960 len++;
4961 fname = tor_malloc(len);
4962 if (sub1) {
4963 if (sub2) {
4964 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s",
4965 options->DataDirectory, sub1, sub2);
4966 } else {
4967 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s",
4968 options->DataDirectory, sub1);
4970 } else {
4971 strlcpy(fname, options->DataDirectory, len);
4973 if (suffix)
4974 strlcat(fname, suffix, len);
4975 return fname;
4978 /** Return 0 if every setting in <b>state</b> is reasonable, and a
4979 * permissible transition from <b>old_state</b>. Else warn and return -1.
4980 * Should have no side effects, except for normalizing the contents of
4981 * <b>state</b>.
4983 /* XXX from_setconf is here because of bug 238 */
4984 static int
4985 or_state_validate(or_state_t *old_state, or_state_t *state,
4986 int from_setconf, char **msg)
4988 /* We don't use these; only options do. Still, we need to match that
4989 * signature. */
4990 (void) from_setconf;
4991 (void) old_state;
4993 if (entry_guards_parse_state(state, 0, msg)<0)
4994 return -1;
4996 return 0;
4999 /** Replace the current persistent state with <b>new_state</b> */
5000 static int
5001 or_state_set(or_state_t *new_state)
5003 char *err = NULL;
5004 int ret = 0;
5005 tor_assert(new_state);
5006 config_free(&state_format, global_state);
5007 global_state = new_state;
5008 if (entry_guards_parse_state(global_state, 1, &err)<0) {
5009 log_warn(LD_GENERAL,"%s",err);
5010 tor_free(err);
5011 ret = -1;
5013 if (rep_hist_load_state(global_state, &err)<0) {
5014 log_warn(LD_GENERAL,"Unparseable bandwidth history state: %s",err);
5015 tor_free(err);
5016 ret = -1;
5018 if (circuit_build_times_parse_state(&circ_times, global_state) < 0) {
5019 ret = -1;
5021 return ret;
5025 * Save a broken state file to a backup location.
5027 static void
5028 or_state_save_broken(char *fname)
5030 int i;
5031 file_status_t status;
5032 size_t len = strlen(fname)+16;
5033 char *fname2 = tor_malloc(len);
5034 for (i = 0; i < 100; ++i) {
5035 tor_snprintf(fname2, len, "%s.%d", fname, i);
5036 status = file_status(fname2);
5037 if (status == FN_NOENT)
5038 break;
5040 if (i == 100) {
5041 log_warn(LD_BUG, "Unable to parse state in \"%s\"; too many saved bad "
5042 "state files to move aside. Discarding the old state file.",
5043 fname);
5044 unlink(fname);
5045 } else {
5046 log_warn(LD_BUG, "Unable to parse state in \"%s\". Moving it aside "
5047 "to \"%s\". This could be a bug in Tor; please tell "
5048 "the developers.", fname, fname2);
5049 if (rename(fname, fname2) < 0) {
5050 log_warn(LD_BUG, "Weirdly, I couldn't even move the state aside. The "
5051 "OS gave an error of %s", strerror(errno));
5054 tor_free(fname2);
5057 /** Reload the persistent state from disk, generating a new state as needed.
5058 * Return 0 on success, less than 0 on failure.
5060 static int
5061 or_state_load(void)
5063 or_state_t *new_state = NULL;
5064 char *contents = NULL, *fname;
5065 char *errmsg = NULL;
5066 int r = -1, badstate = 0;
5068 fname = get_datadir_fname("state");
5069 switch (file_status(fname)) {
5070 case FN_FILE:
5071 if (!(contents = read_file_to_str(fname, 0, NULL))) {
5072 log_warn(LD_FS, "Unable to read state file \"%s\"", fname);
5073 goto done;
5075 break;
5076 case FN_NOENT:
5077 break;
5078 case FN_ERROR:
5079 case FN_DIR:
5080 default:
5081 log_warn(LD_GENERAL,"State file \"%s\" is not a file? Failing.", fname);
5082 goto done;
5084 new_state = tor_malloc_zero(sizeof(or_state_t));
5085 new_state->_magic = OR_STATE_MAGIC;
5086 config_init(&state_format, new_state);
5087 if (contents) {
5088 config_line_t *lines=NULL;
5089 int assign_retval;
5090 if (config_get_lines(contents, &lines)<0)
5091 goto done;
5092 assign_retval = config_assign(&state_format, new_state,
5093 lines, 0, 0, &errmsg);
5094 config_free_lines(lines);
5095 if (assign_retval<0)
5096 badstate = 1;
5097 if (errmsg) {
5098 log_warn(LD_GENERAL, "%s", errmsg);
5099 tor_free(errmsg);
5103 if (!badstate && or_state_validate(NULL, new_state, 1, &errmsg) < 0)
5104 badstate = 1;
5106 if (errmsg) {
5107 log_warn(LD_GENERAL, "%s", errmsg);
5108 tor_free(errmsg);
5111 if (badstate && !contents) {
5112 log_warn(LD_BUG, "Uh oh. We couldn't even validate our own default state."
5113 " This is a bug in Tor.");
5114 goto done;
5115 } else if (badstate && contents) {
5116 or_state_save_broken(fname);
5118 tor_free(contents);
5119 config_free(&state_format, new_state);
5121 new_state = tor_malloc_zero(sizeof(or_state_t));
5122 new_state->_magic = OR_STATE_MAGIC;
5123 config_init(&state_format, new_state);
5124 } else if (contents) {
5125 log_info(LD_GENERAL, "Loaded state from \"%s\"", fname);
5126 } else {
5127 log_info(LD_GENERAL, "Initialized state");
5129 if (or_state_set(new_state) == -1) {
5130 or_state_save_broken(fname);
5132 new_state = NULL;
5133 if (!contents) {
5134 global_state->next_write = 0;
5135 or_state_save(time(NULL));
5137 r = 0;
5139 done:
5140 tor_free(fname);
5141 tor_free(contents);
5142 if (new_state)
5143 config_free(&state_format, new_state);
5145 return r;
5148 /** If writing the state to disk fails, try again after this many seconds. */
5149 #define STATE_WRITE_RETRY_INTERVAL 3600
5151 /** Write the persistent state to disk. Return 0 for success, <0 on failure. */
5153 or_state_save(time_t now)
5155 char *state, *contents;
5156 char tbuf[ISO_TIME_LEN+1];
5157 char *fname;
5159 tor_assert(global_state);
5161 if (global_state->next_write > now)
5162 return 0;
5164 /* Call everything else that might dirty the state even more, in order
5165 * to avoid redundant writes. */
5166 entry_guards_update_state(global_state);
5167 rep_hist_update_state(global_state);
5168 circuit_build_times_update_state(&circ_times, global_state);
5169 if (accounting_is_enabled(get_options()))
5170 accounting_run_housekeeping(now);
5172 tor_free(global_state->TorVersion);
5173 tor_asprintf(&global_state->TorVersion, "Tor %s", get_version());
5175 state = config_dump(&state_format, global_state, 1, 0);
5176 format_local_iso_time(tbuf, time(NULL));
5177 tor_asprintf(&contents,
5178 "# Tor state file last generated on %s local time\n"
5179 "# Other times below are in GMT\n"
5180 "# You *do not* need to edit this file.\n\n%s",
5181 tbuf, state);
5182 tor_free(state);
5183 fname = get_datadir_fname("state");
5184 if (write_str_to_file(fname, contents, 0)<0) {
5185 log_warn(LD_FS, "Unable to write state to file \"%s\"; "
5186 "will try again later", fname);
5187 global_state->LastWritten = -1;
5188 tor_free(fname);
5189 tor_free(contents);
5190 /* Try again after STATE_WRITE_RETRY_INTERVAL (or sooner, if the state
5191 * changes sooner). */
5192 global_state->next_write = now + STATE_WRITE_RETRY_INTERVAL;
5193 return -1;
5196 global_state->LastWritten = time(NULL);
5197 log_info(LD_GENERAL, "Saved state to \"%s\"", fname);
5198 tor_free(fname);
5199 tor_free(contents);
5201 global_state->next_write = TIME_MAX;
5202 return 0;
5205 /** Given a file name check to see whether the file exists but has not been
5206 * modified for a very long time. If so, remove it. */
5207 void
5208 remove_file_if_very_old(const char *fname, time_t now)
5210 #define VERY_OLD_FILE_AGE (28*24*60*60)
5211 struct stat st;
5213 if (stat(fname, &st)==0 && st.st_mtime < now-VERY_OLD_FILE_AGE) {
5214 char buf[ISO_TIME_LEN+1];
5215 format_local_iso_time(buf, st.st_mtime);
5216 log_notice(LD_GENERAL, "Obsolete file %s hasn't been modified since %s. "
5217 "Removing it.", fname, buf);
5218 unlink(fname);
5222 /** Helper to implement GETINFO functions about configuration variables (not
5223 * their values). Given a "config/names" question, set *<b>answer</b> to a
5224 * new string describing the supported configuration variables and their
5225 * types. */
5227 getinfo_helper_config(control_connection_t *conn,
5228 const char *question, char **answer,
5229 const char **errmsg)
5231 (void) conn;
5232 (void) errmsg;
5233 if (!strcmp(question, "config/names")) {
5234 smartlist_t *sl = smartlist_create();
5235 int i;
5236 for (i = 0; _option_vars[i].name; ++i) {
5237 config_var_t *var = &_option_vars[i];
5238 const char *type;
5239 char *line;
5240 switch (var->type) {
5241 case CONFIG_TYPE_STRING: type = "String"; break;
5242 case CONFIG_TYPE_FILENAME: type = "Filename"; break;
5243 case CONFIG_TYPE_UINT: type = "Integer"; break;
5244 case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
5245 case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
5246 case CONFIG_TYPE_DOUBLE: type = "Float"; break;
5247 case CONFIG_TYPE_BOOL: type = "Boolean"; break;
5248 case CONFIG_TYPE_ISOTIME: type = "Time"; break;
5249 case CONFIG_TYPE_ROUTERSET: type = "RouterList"; break;
5250 case CONFIG_TYPE_CSV: type = "CommaList"; break;
5251 case CONFIG_TYPE_LINELIST: type = "LineList"; break;
5252 case CONFIG_TYPE_LINELIST_S: type = "Dependant"; break;
5253 case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
5254 default:
5255 case CONFIG_TYPE_OBSOLETE:
5256 type = NULL; break;
5258 if (!type)
5259 continue;
5260 tor_asprintf(&line, "%s %s\n",var->name,type);
5261 smartlist_add(sl, line);
5263 *answer = smartlist_join_strings(sl, "", 0, NULL);
5264 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
5265 smartlist_free(sl);
5267 return 0;