Ticket #24854: config.c

File config.c, 298.4 KB (added by beastr0, 21 months ago)

24854 edit to config.c

Line 
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-2017, The Tor Project, Inc. */
5/* See LICENSE for licensing information */
6
7/**
8 * \file config.c
9 * \brief Code to interpret the user's configuration of Tor.
10 *
11 * This module handles torrc configuration file, including parsing it,
12 * combining it with torrc.defaults and the command line, allowing
13 * user changes to it (via editing and SIGHUP or via the control port),
14 * writing it back to disk (because of SAVECONF from the control port),
15 * and -- most importantly, acting on it.
16 *
17 * The module additionally has some tools for manipulating and
18 * inspecting values that are calculated as a result of the
19 * configured options.
20 *
21 * <h3>How to add new options</h3>
22 *
23 * To add new items to the torrc, there are a minimum of three places to edit:
24 * <ul>
25 *   <li>The or_options_t structure in or.h, where the options are stored.
26 *   <li>The option_vars_ array below in this module, which configures
27 *       the names of the torrc options, their types, their multiplicities,
28 *       and their mappings to fields in or_options_t.
29 *   <li>The manual in doc/tor.1.txt, to document what the new option
30 *       is, and how it works.
31 * </ul>
32 *
33 * Additionally, you might need to edit these places too:
34 * <ul>
35 *   <li>options_validate() below, in case you want to reject some possible
36 *       values of the new configuration option.
37 *   <li>options_transition_allowed() below, in case you need to
38 *       forbid some or all changes in the option while Tor is
39 *       running.
40 *   <li>options_transition_affects_workers(), in case changes in the option
41 *       might require Tor to relaunch or reconfigure its worker threads.
42 *   <li>options_transition_affects_descriptor(), in case changes in the
43 *       option might require a Tor relay to build and publish a new server
44 *       descriptor.
45 *   <li>options_act() and/or options_act_reversible(), in case there's some
46 *       action that needs to be taken immediately based on the option's
47 *       value.
48 * </ul>
49 *
50 * <h3>Changing the value of an option</h3>
51 *
52 * Because of the SAVECONF command from the control port, it's a bad
53 * idea to change the value of any user-configured option in the
54 * or_options_t.  If you want to sometimes do this anyway, we recommend
55 * that you create a secondary field in or_options_t; that you have the
56 * user option linked only to the secondary field; that you use the
57 * secondary field to initialize the one that Tor actually looks at; and that
58 * you use the one Tor looks as the one that you modify.
59 **/
60
61#define CONFIG_PRIVATE
62#include "or.h"
63#include "bridges.h"
64#include "compat.h"
65#include "addressmap.h"
66#include "channel.h"
67#include "circuitbuild.h"
68#include "circuitlist.h"
69#include "circuitmux.h"
70#include "circuitmux_ewma.h"
71#include "circuitstats.h"
72#include "compress.h"
73#include "config.h"
74#include "connection.h"
75#include "connection_edge.h"
76#include "connection_or.h"
77#include "consdiffmgr.h"
78#include "control.h"
79#include "confparse.h"
80#include "cpuworker.h"
81#include "dirserv.h"
82#include "dirvote.h"
83#include "dns.h"
84#include "entrynodes.h"
85#include "git_revision.h"
86#include "geoip.h"
87#include "hibernate.h"
88#include "main.h"
89#include "networkstatus.h"
90#include "nodelist.h"
91#include "policies.h"
92#include "relay.h"
93#include "rendclient.h"
94#include "rendservice.h"
95#include "hs_config.h"
96#include "rephist.h"
97#include "router.h"
98#include "sandbox.h"
99#include "util.h"
100#include "routerlist.h"
101#include "routerset.h"
102#include "scheduler.h"
103#include "statefile.h"
104#include "transports.h"
105#include "ext_orport.h"
106#ifdef _WIN32
107#include <shlobj.h>
108#endif
109
110#include "procmon.h"
111
112#ifdef HAVE_SYSTEMD
113#   if defined(__COVERITY__) && !defined(__INCLUDE_LEVEL__)
114/* Systemd's use of gcc's __INCLUDE_LEVEL__ extension macro appears to confuse
115 * Coverity. Here's a kludge to unconfuse it.
116 */
117#   define __INCLUDE_LEVEL__ 2
118#endif /* defined(__COVERITY__) && !defined(__INCLUDE_LEVEL__) */
119#include <systemd/sd-daemon.h>
120#endif /* defined(HAVE_SYSTEMD) */
121
122/* Prefix used to indicate a Unix socket in a FooPort configuration. */
123static const char unix_socket_prefix[] = "unix:";
124/* Prefix used to indicate a Unix socket with spaces in it, in a FooPort
125 * configuration. */
126static const char unix_q_socket_prefix[] = "unix:\"";
127
128/** A list of abbreviations and aliases to map command-line options, obsolete
129 * option names, or alternative option names, to their current values. */
130static config_abbrev_t option_abbrevs_[] = {
131  PLURAL(AuthDirBadDirCC),
132  PLURAL(AuthDirBadExitCC),
133  PLURAL(AuthDirInvalidCC),
134  PLURAL(AuthDirRejectCC),
135  PLURAL(EntryNode),
136  PLURAL(ExcludeNode),
137  PLURAL(Tor2webRendezvousPoint),
138  PLURAL(FirewallPort),
139  PLURAL(LongLivedPort),
140  PLURAL(HiddenServiceNode),
141  PLURAL(HiddenServiceExcludeNode),
142  PLURAL(NumCPU),
143  PLURAL(RendNode),
144  PLURAL(RecommendedPackage),
145  PLURAL(RendExcludeNode),
146  PLURAL(StrictEntryNode),
147  PLURAL(StrictExitNode),
148  PLURAL(StrictNode),
149  { "l", "Log", 1, 0},
150  { "AllowUnverifiedNodes", "AllowInvalidNodes", 0, 0},
151  { "AutomapHostSuffixes", "AutomapHostsSuffixes", 0, 0},
152  { "AutomapHostOnResolve", "AutomapHostsOnResolve", 0, 0},
153  { "BandwidthRateBytes", "BandwidthRate", 0, 0},
154  { "BandwidthBurstBytes", "BandwidthBurst", 0, 0},
155  { "DirFetchPostPeriod", "StatusFetchPeriod", 0, 0},
156  { "DirServer", "DirAuthority", 0, 0}, /* XXXX later, make this warn? */
157  { "MaxConn", "ConnLimit", 0, 1},
158  { "MaxMemInCellQueues", "MaxMemInQueues", 0, 0},
159  { "ORBindAddress", "ORListenAddress", 0, 0},
160  { "DirBindAddress", "DirListenAddress", 0, 0},
161  { "SocksBindAddress", "SocksListenAddress", 0, 0},
162  { "UseHelperNodes", "UseEntryGuards", 0, 0},
163  { "NumHelperNodes", "NumEntryGuards", 0, 0},
164  { "UseEntryNodes", "UseEntryGuards", 0, 0},
165  { "NumEntryNodes", "NumEntryGuards", 0, 0},
166  { "ResolvConf", "ServerDNSResolvConfFile", 0, 1},
167  { "SearchDomains", "ServerDNSSearchDomains", 0, 1},
168  { "ServerDNSAllowBrokenResolvConf", "ServerDNSAllowBrokenConfig", 0, 0},
169  { "PreferTunnelledDirConns", "PreferTunneledDirConns", 0, 0},
170  { "BridgeAuthoritativeDirectory", "BridgeAuthoritativeDir", 0, 0},
171  { "HashedControlPassword", "__HashedControlSessionPassword", 1, 0},
172  { "VirtualAddrNetwork", "VirtualAddrNetworkIPv4", 0, 0},
173  { NULL, NULL, 0, 0},
174};
175
176/** dummy instance of or_options_t, used for type-checking its
177 * members with CONF_CHECK_VAR_TYPE. */
178DUMMY_TYPECHECK_INSTANCE(or_options_t);
179
180/** An entry for config_vars: "The option <b>name</b> has type
181 * CONFIG_TYPE_<b>conftype</b>, and corresponds to
182 * or_options_t.<b>member</b>"
183 */
184#define VAR(name,conftype,member,initvalue)                             \
185  { name, CONFIG_TYPE_ ## conftype, offsetof(or_options_t, member),     \
186      initvalue CONF_TEST_MEMBERS(or_options_t, conftype, member) }
187/** As VAR, but the option name and member name are the same. */
188#define V(member,conftype,initvalue)                                    \
189  VAR(#member, conftype, member, initvalue)
190/** An entry for config_vars: "The option <b>name</b> is obsolete." */
191#ifdef TOR_UNIT_TESTS
192#define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL, {.INT=NULL} }
193#else
194#define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL }
195#endif
196
197/**
198 * Macro to declare *Port options.  Each one comes in three entries.
199 * For example, most users should use "SocksPort" to configure the
200 * socks port, but TorBrowser wants to use __SocksPort so that it
201 * isn't stored by SAVECONF.  The SocksPortLines virtual option is
202 * used to query both options from the controller.
203 */
204#define VPORT(member)                                           \
205  VAR(#member "Lines", LINELIST_V, member ## _lines, NULL),     \
206  VAR(#member, LINELIST_S, member ## _lines, NULL),             \
207  VAR("__" #member, LINELIST_S, member ## _lines, NULL)
208
209/** Array of configuration options.  Until we disallow nonstandard
210 * abbreviations, order is significant, since the first matching option will
211 * be chosen first.
212 */
213static config_var_t option_vars_[] = {
214  V(AccountingMax,               MEMUNIT,  "0 bytes"),
215  VAR("AccountingRule",          STRING,   AccountingRule_option,  "max"),
216  V(AccountingStart,             STRING,   NULL),
217  V(Address,                     STRING,   NULL),
218  OBSOLETE("AllowDotExit"),
219  OBSOLETE("AllowInvalidNodes"),
220  V(AllowNonRFC953Hostnames,     BOOL,     "0"),
221  OBSOLETE("AllowSingleHopCircuits"),
222  OBSOLETE("AllowSingleHopExits"),
223  V(AlternateBridgeAuthority,    LINELIST, NULL),
224  V(AlternateDirAuthority,       LINELIST, NULL),
225  OBSOLETE("AlternateHSAuthority"),
226  V(AssumeReachable,             BOOL,     "0"),
227  OBSOLETE("AuthDirBadDir"),
228  OBSOLETE("AuthDirBadDirCCs"),
229  V(AuthDirBadExit,              LINELIST, NULL),
230  V(AuthDirBadExitCCs,           CSV,      ""),
231  V(AuthDirInvalid,              LINELIST, NULL),
232  V(AuthDirInvalidCCs,           CSV,      ""),
233  V(AuthDirFastGuarantee,        MEMUNIT,  "100 KB"),
234  V(AuthDirGuardBWGuarantee,     MEMUNIT,  "2 MB"),
235  V(AuthDirPinKeys,              BOOL,     "1"),
236  V(AuthDirReject,               LINELIST, NULL),
237  V(AuthDirRejectCCs,            CSV,      ""),
238  OBSOLETE("AuthDirRejectUnlisted"),
239  OBSOLETE("AuthDirListBadDirs"),
240  V(AuthDirListBadExits,         BOOL,     "0"),
241  V(AuthDirMaxServersPerAddr,    UINT,     "2"),
242  OBSOLETE("AuthDirMaxServersPerAuthAddr"),
243  V(AuthDirHasIPv6Connectivity,  BOOL,     "0"),
244  VAR("AuthoritativeDirectory",  BOOL, AuthoritativeDir,    "0"),
245  V(AutomapHostsOnResolve,       BOOL,     "0"),
246  V(AutomapHostsSuffixes,        CSV,      ".onion,.exit"),
247  V(AvoidDiskWrites,             BOOL,     "0"),
248  V(BandwidthBurst,              MEMUNIT,  "1 GB"),
249  V(BandwidthRate,               MEMUNIT,  "1 GB"),
250  V(BridgeAuthoritativeDir,      BOOL,     "0"),
251  VAR("Bridge",                  LINELIST, Bridges,    NULL),
252  V(BridgePassword,              STRING,   NULL),
253  V(BridgeRecordUsageByCountry,  BOOL,     "1"),
254  V(BridgeRelay,                 BOOL,     "0"),
255  V(BridgeDistribution,          STRING,   NULL),
256  VAR("CacheDirectory",          FILENAME, CacheDirectory_option, NULL),
257  V(CacheDirectoryGroupReadable, BOOL,     "0"),
258  V(CellStatistics,              BOOL,     "0"),
259  V(PaddingStatistics,           BOOL,     "1"),
260  V(LearnCircuitBuildTimeout,    BOOL,     "1"),
261  V(CircuitBuildTimeout,         INTERVAL, "0"),
262  OBSOLETE("CircuitIdleTimeout"),
263  V(CircuitsAvailableTimeout,    INTERVAL, "0"),
264  V(CircuitStreamTimeout,        INTERVAL, "0"),
265  V(CircuitPriorityHalflife,     DOUBLE,  "-100.0"), /*negative:'Use default'*/
266  V(ClientDNSRejectInternalAddresses, BOOL,"1"),
267  V(ClientOnly,                  BOOL,     "0"),
268  V(ClientPreferIPv6ORPort,      AUTOBOOL, "auto"),
269  V(ClientPreferIPv6DirPort,     AUTOBOOL, "auto"),
270  V(ClientRejectInternalAddresses, BOOL,   "1"),
271  V(ClientTransportPlugin,       LINELIST, NULL),
272  V(ClientUseIPv6,               BOOL,     "0"),
273  V(ClientUseIPv4,               BOOL,     "1"),
274  V(ConsensusParams,             STRING,   NULL),
275  V(ConnLimit,                   UINT,     "1000"),
276  V(ConnDirectionStatistics,     BOOL,     "0"),
277  V(ConstrainedSockets,          BOOL,     "0"),
278  V(ConstrainedSockSize,         MEMUNIT,  "8192"),
279  V(ContactInfo,                 STRING,   NULL),
280  OBSOLETE("ControlListenAddress"),
281  VPORT(ControlPort),
282  V(ControlPortFileGroupReadable,BOOL,     "0"),
283  V(ControlPortWriteToFile,      FILENAME, NULL),
284  V(ControlSocket,               LINELIST, NULL),
285  V(ControlSocketsGroupWritable, BOOL,     "0"),
286  V(SocksSocketsGroupWritable,   BOOL,     "0"),
287  V(CookieAuthentication,        BOOL,     "0"),
288  V(CookieAuthFileGroupReadable, BOOL,     "0"),
289  V(CookieAuthFile,              STRING,   NULL),
290  V(CountPrivateBandwidth,       BOOL,     "0"),
291  VAR("DataDirectory",           FILENAME, DataDirectory_option, NULL),
292  V(DataDirectoryGroupReadable,  BOOL,     "0"),
293  V(DisableOOSCheck,             BOOL,     "1"),
294  V(DisableNetwork,              BOOL,     "0"),
295  V(DirAllowPrivateAddresses,    BOOL,     "0"),
296  V(TestingAuthDirTimeToLearnReachability, INTERVAL, "30 minutes"),
297  OBSOLETE("DirListenAddress"),
298  V(DirPolicy,                   LINELIST, NULL),
299  VPORT(DirPort),
300  V(DirPortFrontPage,            FILENAME, NULL),
301  VAR("DirReqStatistics",        BOOL,     DirReqStatistics_option, "1"),
302  VAR("DirAuthority",            LINELIST, DirAuthorities, NULL),
303  V(DirCache,                    BOOL,     "1"),
304  /* A DirAuthorityFallbackRate of 0.1 means that 0.5% of clients try an
305   * authority when all fallbacks are up, and 2% try an authority when 25% of
306   * fallbacks are down. (We rebuild the list when 25% of fallbacks are down).
307   *
308   * We want to reduce load on authorities, but keep these two figures within
309   * an order of magnitude, so there isn't too much load shifting to
310   * authorities when fallbacks go down. */
311  V(DirAuthorityFallbackRate,    DOUBLE,   "0.1"),
312  V(DisableAllSwap,              BOOL,     "0"),
313  V(DisableDebuggerAttachment,   BOOL,     "1"),
314  OBSOLETE("DisableIOCP"),
315  OBSOLETE("DisableV2DirectoryInfo_"),
316  OBSOLETE("DynamicDHGroups"),
317  VPORT(DNSPort),
318  OBSOLETE("DNSListenAddress"),
319  V(DownloadExtraInfo,           BOOL,     "0"),
320  V(TestingEnableConnBwEvent,    BOOL,     "0"),
321  V(TestingEnableCellStatsEvent, BOOL,     "0"),
322  V(TestingEnableTbEmptyEvent,   BOOL,     "0"),
323  V(EnforceDistinctSubnets,      BOOL,     "1"),
324  V(EntryNodes,                  ROUTERSET,   NULL),
325  V(EntryStatistics,             BOOL,     "0"),
326  V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "10 minutes"),
327  V(ExcludeNodes,                ROUTERSET, NULL),
328  V(ExcludeExitNodes,            ROUTERSET, NULL),
329  OBSOLETE("ExcludeSingleHopRelays"),
330  V(ExitNodes,                   ROUTERSET, NULL),
331  V(ExitPolicy,                  LINELIST, NULL),
332  V(ExitPolicyRejectPrivate,     BOOL,     "1"),
333  V(ExitPolicyRejectLocalInterfaces, BOOL, "0"),
334  V(ExitPortStatistics,          BOOL,     "0"),
335  V(ExtendAllowPrivateAddresses, BOOL,     "0"),
336  V(ExitRelay,                   AUTOBOOL, "auto"),
337  VPORT(ExtORPort),
338  V(ExtORPortCookieAuthFile,     STRING,   NULL),
339  V(ExtORPortCookieAuthFileGroupReadable, BOOL, "0"),
340  V(ExtraInfoStatistics,         BOOL,     "1"),
341  V(ExtendByEd25519ID,           AUTOBOOL, "auto"),
342  V(FallbackDir,                 LINELIST, NULL),
343
344  V(UseDefaultFallbackDirs,      BOOL,     "1"),
345
346  OBSOLETE("FallbackNetworkstatusFile"),
347  V(FascistFirewall,             BOOL,     "0"),
348  V(FirewallPorts,               CSV,      ""),
349  OBSOLETE("FastFirstHopPK"),
350  V(FetchDirInfoEarly,           BOOL,     "0"),
351  V(FetchDirInfoExtraEarly,      BOOL,     "0"),
352  V(FetchServerDescriptors,      BOOL,     "1"),
353  V(FetchHidServDescriptors,     BOOL,     "1"),
354  V(FetchUselessDescriptors,     BOOL,     "0"),
355  OBSOLETE("FetchV2Networkstatus"),
356  V(GeoIPExcludeUnknown,         AUTOBOOL, "auto"),
357#ifdef _WIN32
358  V(GeoIPFile,                   FILENAME, "<default>"),
359  V(GeoIPv6File,                 FILENAME, "<default>"),
360#else
361  V(GeoIPFile,                   FILENAME,
362    SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip"),
363  V(GeoIPv6File,                 FILENAME,
364    SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip6"),
365#endif /* defined(_WIN32) */
366  OBSOLETE("Group"),
367  V(GuardLifetime,               INTERVAL, "0 minutes"),
368  V(HardwareAccel,               BOOL,     "0"),
369  V(HeartbeatPeriod,             INTERVAL, "6 hours"),
370  V(MainloopStats,               BOOL,     "0"),
371  V(AccelName,                   STRING,   NULL),
372  V(AccelDir,                    FILENAME, NULL),
373  V(HashedControlPassword,       LINELIST, NULL),
374  OBSOLETE("HidServDirectoryV2"),
375  VAR("HiddenServiceDir",    LINELIST_S, RendConfigLines,    NULL),
376  VAR("HiddenServiceDirGroupReadable",  LINELIST_S, RendConfigLines, NULL),
377  VAR("HiddenServiceOptions",LINELIST_V, RendConfigLines,    NULL),
378  VAR("HiddenServicePort",   LINELIST_S, RendConfigLines,    NULL),
379  VAR("HiddenServiceVersion",LINELIST_S, RendConfigLines,    NULL),
380  VAR("HiddenServiceAuthorizeClient",LINELIST_S,RendConfigLines, NULL),
381  VAR("HiddenServiceAllowUnknownPorts",LINELIST_S, RendConfigLines, NULL),
382  VAR("HiddenServiceMaxStreams",LINELIST_S, RendConfigLines, NULL),
383  VAR("HiddenServiceMaxStreamsCloseCircuit",LINELIST_S, RendConfigLines, NULL),
384  VAR("HiddenServiceNumIntroductionPoints", LINELIST_S, RendConfigLines, NULL),
385  VAR("HiddenServiceStatistics", BOOL, HiddenServiceStatistics_option, "1"),
386  V(HidServAuth,                 LINELIST, NULL),
387  OBSOLETE("CloseHSClientCircuitsImmediatelyOnTimeout"),
388  OBSOLETE("CloseHSServiceRendCircuitsImmediatelyOnTimeout"),
389  V(HiddenServiceSingleHopMode,  BOOL,     "0"),
390  V(HiddenServiceNonAnonymousMode,BOOL,    "0"),
391  V(HTTPProxy,                   STRING,   NULL),
392  V(HTTPProxyAuthenticator,      STRING,   NULL),
393  V(HTTPSProxy,                  STRING,   NULL),
394  V(HTTPSProxyAuthenticator,     STRING,   NULL),
395  VPORT(HTTPTunnelPort),
396  V(IPv6Exit,                    BOOL,     "0"),
397  VAR("ServerTransportPlugin",   LINELIST, ServerTransportPlugin,  NULL),
398  V(ServerTransportListenAddr,   LINELIST, NULL),
399  V(ServerTransportOptions,      LINELIST, NULL),
400  V(SigningKeyLifetime,          INTERVAL, "30 days"),
401  V(Socks4Proxy,                 STRING,   NULL),
402  V(Socks5Proxy,                 STRING,   NULL),
403  V(Socks5ProxyUsername,         STRING,   NULL),
404  V(Socks5ProxyPassword,         STRING,   NULL),
405  VAR("KeyDirectory",            FILENAME, KeyDirectory_option, NULL),
406  V(KeyDirectoryGroupReadable,   BOOL,     "0"),
407  V(KeepalivePeriod,             INTERVAL, "5 minutes"),
408  V(KeepBindCapabilities,            AUTOBOOL, "auto"),
409  VAR("Log",                     LINELIST, Logs,             NULL),
410  V(LogMessageDomains,           BOOL,     "0"),
411  V(LogTimeGranularity,          MSEC_INTERVAL, "1 second"),
412  V(TruncateLogFile,             BOOL,     "0"),
413  V(SyslogIdentityTag,           STRING,   NULL),
414  V(AndroidIdentityTag,          STRING,   NULL),
415  V(LongLivedPorts,              CSV,
416        "21,22,706,1863,5050,5190,5222,5223,6523,6667,6697,8300"),
417  VAR("MapAddress",              LINELIST, AddressMap,           NULL),
418  V(MaxAdvertisedBandwidth,      MEMUNIT,  "1 GB"),
419  V(MaxCircuitDirtiness,         INTERVAL, "10 minutes"),
420  V(MaxClientCircuitsPending,    UINT,     "32"),
421  V(MaxConsensusAgeForDiffs,     INTERVAL, "0 seconds"),
422  VAR("MaxMemInQueues",          MEMUNIT,   MaxMemInQueues_raw, "0"),
423  OBSOLETE("MaxOnionsPending"),
424  V(MaxOnionQueueDelay,          MSEC_INTERVAL, "1750 msec"),
425  V(MaxUnparseableDescSizeToLog, MEMUNIT, "10 MB"),
426  V(MinMeasuredBWsForAuthToIgnoreAdvertised, INT, "500"),
427  VAR("MyFamily",                LINELIST, MyFamily_lines,       NULL),
428  V(NewCircuitPeriod,            INTERVAL, "30 seconds"),
429  OBSOLETE("NamingAuthoritativeDirectory"),
430  OBSOLETE("NATDListenAddress"),
431  VPORT(NATDPort),
432  V(Nickname,                    STRING,   NULL),
433  OBSOLETE("PredictedPortsRelevanceTime"),
434  OBSOLETE("WarnUnsafeSocks"),
435  VAR("NodeFamily",              LINELIST, NodeFamilies,         NULL),
436  V(NoExec,                      BOOL,     "0"),
437  V(NumCPUs,                     UINT,     "0"),
438  V(NumDirectoryGuards,          UINT,     "0"),
439  V(NumEntryGuards,              UINT,     "0"),
440  V(OfflineMasterKey,            BOOL,     "0"),
441  OBSOLETE("ORListenAddress"),
442  VPORT(ORPort),
443  V(OutboundBindAddress,         LINELIST,   NULL),
444  V(OutboundBindAddressOR,       LINELIST,   NULL),
445  V(OutboundBindAddressExit,     LINELIST,   NULL),
446
447  OBSOLETE("PathBiasDisableRate"),
448  V(PathBiasCircThreshold,       INT,      "-1"),
449  V(PathBiasNoticeRate,          DOUBLE,   "-1"),
450  V(PathBiasWarnRate,            DOUBLE,   "-1"),
451  V(PathBiasExtremeRate,         DOUBLE,   "-1"),
452  V(PathBiasScaleThreshold,      INT,      "-1"),
453  OBSOLETE("PathBiasScaleFactor"),
454  OBSOLETE("PathBiasMultFactor"),
455  V(PathBiasDropGuards,          AUTOBOOL, "0"),
456  OBSOLETE("PathBiasUseCloseCounts"),
457
458  V(PathBiasUseThreshold,       INT,      "-1"),
459  V(PathBiasNoticeUseRate,          DOUBLE,   "-1"),
460  V(PathBiasExtremeUseRate,         DOUBLE,   "-1"),
461  V(PathBiasScaleUseThreshold,      INT,      "-1"),
462
463  V(PathsNeededToBuildCircuits,  DOUBLE,   "-1"),
464  V(PerConnBWBurst,              MEMUNIT,  "0"),
465  V(PerConnBWRate,               MEMUNIT,  "0"),
466  V(PidFile,                     STRING,   NULL),
467  V(TestingTorNetwork,           BOOL,     "0"),
468  V(TestingMinExitFlagThreshold, MEMUNIT,  "0"),
469  V(TestingMinFastFlagThreshold, MEMUNIT,  "0"),
470
471  V(TestingLinkCertLifetime,          INTERVAL, "2 days"),
472  V(TestingAuthKeyLifetime,          INTERVAL, "2 days"),
473  V(TestingLinkKeySlop,              INTERVAL, "3 hours"),
474  V(TestingAuthKeySlop,              INTERVAL, "3 hours"),
475  V(TestingSigningKeySlop,           INTERVAL, "1 day"),
476
477  V(OptimisticData,              AUTOBOOL, "auto"),
478  V(PortForwarding,              BOOL,     "0"),
479  V(PortForwardingHelper,        FILENAME, "tor-fw-helper"),
480  OBSOLETE("PreferTunneledDirConns"),
481  V(ProtocolWarnings,            BOOL,     "0"),
482  V(PublishServerDescriptor,     CSV,      "1"),
483  V(PublishHidServDescriptors,   BOOL,     "1"),
484  V(ReachableAddresses,          LINELIST, NULL),
485  V(ReachableDirAddresses,       LINELIST, NULL),
486  V(ReachableORAddresses,        LINELIST, NULL),
487  V(RecommendedVersions,         LINELIST, NULL),
488  V(RecommendedClientVersions,   LINELIST, NULL),
489  V(RecommendedServerVersions,   LINELIST, NULL),
490  V(RecommendedPackages,         LINELIST, NULL),
491  V(ReducedConnectionPadding,    BOOL,     "0"),
492  V(ConnectionPadding,           AUTOBOOL, "auto"),
493  V(RefuseUnknownExits,          AUTOBOOL, "auto"),
494  V(RejectPlaintextPorts,        CSV,      ""),
495  V(RelayBandwidthBurst,         MEMUNIT,  "0"),
496  V(RelayBandwidthRate,          MEMUNIT,  "0"),
497  V(RendPostPeriod,              INTERVAL, "1 hour"),
498  V(RephistTrackTime,            INTERVAL, "24 hours"),
499  V(RunAsDaemon,                 BOOL,     "0"),
500  V(ReducedExitPolicy,           BOOL,     "0"),
501  OBSOLETE("RunTesting"), // currently unused
502  V(Sandbox,                     BOOL,     "0"),
503  V(SafeLogging,                 STRING,   "1"),
504  V(SafeSocks,                   BOOL,     "0"),
505  V(ServerDNSAllowBrokenConfig,  BOOL,     "1"),
506  V(ServerDNSAllowNonRFC953Hostnames, BOOL,"0"),
507  V(ServerDNSDetectHijacking,    BOOL,     "1"),
508  V(ServerDNSRandomizeCase,      BOOL,     "1"),
509  V(ServerDNSResolvConfFile,     STRING,   NULL),
510  V(ServerDNSSearchDomains,      BOOL,     "0"),
511  V(ServerDNSTestAddresses,      CSV,
512      "www.google.com,www.mit.edu,www.yahoo.com,www.slashdot.org"),
513  OBSOLETE("SchedulerLowWaterMark__"),
514  OBSOLETE("SchedulerHighWaterMark__"),
515  OBSOLETE("SchedulerMaxFlushCells__"),
516  V(KISTSchedRunInterval,        MSEC_INTERVAL, "0 msec"),
517  V(KISTSockBufSizeFactor,       DOUBLE,   "1.0"),
518  V(Schedulers,                  CSV,      "KIST,KISTLite,Vanilla"),
519  V(ShutdownWaitLength,          INTERVAL, "30 seconds"),
520  OBSOLETE("SocksListenAddress"),
521  V(SocksPolicy,                 LINELIST, NULL),
522  VPORT(SocksPort),
523  V(SocksTimeout,                INTERVAL, "2 minutes"),
524  V(SSLKeyLifetime,              INTERVAL, "0"),
525  OBSOLETE("StrictEntryNodes"),
526  OBSOLETE("StrictExitNodes"),
527  V(StrictNodes,                 BOOL,     "0"),
528  OBSOLETE("Support022HiddenServices"),
529  V(TestSocks,                   BOOL,     "0"),
530  V(TokenBucketRefillInterval,   MSEC_INTERVAL, "100 msec"),
531  V(Tor2webMode,                 BOOL,     "0"),
532  V(Tor2webRendezvousPoints,      ROUTERSET, NULL),
533  OBSOLETE("TLSECGroup"),
534  V(TrackHostExits,              CSV,      NULL),
535  V(TrackHostExitsExpire,        INTERVAL, "30 minutes"),
536  OBSOLETE("TransListenAddress"),
537  VPORT(TransPort),
538  V(TransProxyType,              STRING,   "default"),
539  OBSOLETE("TunnelDirConns"),
540  V(UpdateBridgesFromAuthority,  BOOL,     "0"),
541  V(UseBridges,                  BOOL,     "0"),
542  VAR("UseEntryGuards",          BOOL,     UseEntryGuards_option, "1"),
543  OBSOLETE("UseEntryGuardsAsDirGuards"),
544  V(UseGuardFraction,            AUTOBOOL, "auto"),
545  V(UseMicrodescriptors,         AUTOBOOL, "auto"),
546  OBSOLETE("UseNTorHandshake"),
547  V(User,                        STRING,   NULL),
548  OBSOLETE("UserspaceIOCPBuffers"),
549  V(AuthDirSharedRandomness,     BOOL,     "1"),
550  V(AuthDirTestEd25519LinkKeys,  BOOL,     "1"),
551  OBSOLETE("V1AuthoritativeDirectory"),
552  OBSOLETE("V2AuthoritativeDirectory"),
553  VAR("V3AuthoritativeDirectory",BOOL, V3AuthoritativeDir,   "0"),
554  V(TestingV3AuthInitialVotingInterval, INTERVAL, "30 minutes"),
555  V(TestingV3AuthInitialVoteDelay, INTERVAL, "5 minutes"),
556  V(TestingV3AuthInitialDistDelay, INTERVAL, "5 minutes"),
557  V(TestingV3AuthVotingStartOffset, INTERVAL, "0"),
558  V(V3AuthVotingInterval,        INTERVAL, "1 hour"),
559  V(V3AuthVoteDelay,             INTERVAL, "5 minutes"),
560  V(V3AuthDistDelay,             INTERVAL, "5 minutes"),
561  V(V3AuthNIntervalsValid,       UINT,     "3"),
562  V(V3AuthUseLegacyKey,          BOOL,     "0"),
563  V(V3BandwidthsFile,            FILENAME, NULL),
564  V(GuardfractionFile,           FILENAME, NULL),
565  VAR("VersioningAuthoritativeDirectory",BOOL,VersioningAuthoritativeDir, "0"),
566  OBSOLETE("VoteOnHidServDirectoriesV2"),
567  V(VirtualAddrNetworkIPv4,      STRING,   "127.192.0.0/10"),
568  V(VirtualAddrNetworkIPv6,      STRING,   "[FE80::]/10"),
569  V(WarnPlaintextPorts,          CSV,      "23,109,110,143"),
570  OBSOLETE("UseFilteringSSLBufferevents"),
571  OBSOLETE("__UseFilteringSSLBufferevents"),
572  VAR("__ReloadTorrcOnSIGHUP",   BOOL,  ReloadTorrcOnSIGHUP,      "1"),
573  VAR("__AllDirActionsPrivate",  BOOL,  AllDirActionsPrivate,     "0"),
574  VAR("__DisablePredictedCircuits",BOOL,DisablePredictedCircuits, "0"),
575  VAR("__LeaveStreamsUnattached",BOOL,  LeaveStreamsUnattached,   "0"),
576  VAR("__HashedControlSessionPassword", LINELIST, HashedControlSessionPassword,
577      NULL),
578  VAR("__OwningControllerProcess",STRING,OwningControllerProcess, NULL),
579  VAR("__OwningControllerFD",INT,OwningControllerFD, "-1"),
580  V(MinUptimeHidServDirectoryV2, INTERVAL, "96 hours"),
581  V(TestingServerDownloadSchedule, CSV_INTERVAL, "0, 0, 0, 60, 60, 120, "
582                                 "300, 900, 2147483647"),
583  V(TestingClientDownloadSchedule, CSV_INTERVAL, "0, 0, 60, 300, 600, "
584                                 "2147483647"),
585  V(TestingServerConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 60, "
586                                 "300, 600, 1800, 1800, 1800, 1800, "
587                                 "1800, 3600, 7200"),
588  V(TestingClientConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 60, "
589                                 "300, 600, 1800, 3600, 3600, 3600, "
590                                 "10800, 21600, 43200"),
591  /* With the ClientBootstrapConsensus*Download* below:
592   * Clients with only authorities will try:
593   *  - at least 3 authorities over 10 seconds, then exponentially backoff,
594   *    with the next attempt 3-21 seconds later,
595   * Clients with authorities and fallbacks will try:
596   *  - at least 2 authorities and 4 fallbacks over 21 seconds, then
597   *    exponentially backoff, with the next attempts 4-33 seconds later,
598   * Clients will also retry when an application request arrives.
599   * After a number of failed requests, clients retry every 3 days + 1 hour.
600   *
601   * Clients used to try 2 authorities over 10 seconds, then wait for
602   * 60 minutes or an application request.
603   *
604   * When clients have authorities and fallbacks available, they use these
605   * schedules: (we stagger the times to avoid thundering herds) */
606  V(ClientBootstrapConsensusAuthorityDownloadSchedule, CSV_INTERVAL,
607    "6, 11, 3600, 10800, 25200, 54000, 111600, 262800" /* 3 days + 1 hour */),
608  V(ClientBootstrapConsensusFallbackDownloadSchedule, CSV_INTERVAL,
609    "0, 1, 4, 11, 3600, 10800, 25200, 54000, 111600, 262800"),
610  /* When clients only have authorities available, they use this schedule: */
611  V(ClientBootstrapConsensusAuthorityOnlyDownloadSchedule, CSV_INTERVAL,
612    "0, 3, 7, 3600, 10800, 25200, 54000, 111600, 262800"),
613  /* We don't want to overwhelm slow networks (or mirrors whose replies are
614   * blocked), but we also don't want to fail if only some mirrors are
615   * blackholed. Clients will try 3 directories simultaneously.
616   * (Relays never use simultaneous connections.) */
617  V(ClientBootstrapConsensusMaxInProgressTries, UINT, "3"),
618  /* When a client has any running bridges, check each bridge occasionally,
619    * whether or not that bridge is actually up. */
620  V(TestingBridgeDownloadSchedule, CSV_INTERVAL,
621    "10800, 25200, 54000, 111600, 262800"),
622  /* When a client is just starting, or has no running bridges, check each
623   * bridge a few times quickly, and then try again later. These schedules
624   * are much longer than the other schedules, because we try each and every
625   * configured bridge with this schedule. */
626  V(TestingBridgeBootstrapDownloadSchedule, CSV_INTERVAL,
627    "0, 30, 90, 600, 3600, 10800, 25200, 54000, 111600, 262800"),
628  V(TestingClientMaxIntervalWithoutRequest, INTERVAL, "10 minutes"),
629  V(TestingDirConnectionMaxStall, INTERVAL, "5 minutes"),
630  V(TestingConsensusMaxDownloadTries, UINT, "8"),
631  /* Since we try connections rapidly and simultaneously, we can afford
632   * to give up earlier. (This protects against overloading directories.) */
633  V(ClientBootstrapConsensusMaxDownloadTries, UINT, "7"),
634  /* We want to give up much earlier if we're only using authorities. */
635  V(ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries, UINT, "4"),
636  V(TestingDescriptorMaxDownloadTries, UINT, "8"),
637  V(TestingMicrodescMaxDownloadTries, UINT, "8"),
638  V(TestingCertMaxDownloadTries, UINT, "8"),
639  V(TestingDirAuthVoteExit, ROUTERSET, NULL),
640  V(TestingDirAuthVoteExitIsStrict,  BOOL,     "0"),
641  V(TestingDirAuthVoteGuard, ROUTERSET, NULL),
642  V(TestingDirAuthVoteGuardIsStrict,  BOOL,     "0"),
643  V(TestingDirAuthVoteHSDir, ROUTERSET, NULL),
644  V(TestingDirAuthVoteHSDirIsStrict,  BOOL,     "0"),
645  VAR("___UsingTestNetworkDefaults", BOOL, UsingTestNetworkDefaults_, "0"),
646
647  END_OF_CONFIG_VARS
648};
649
650/** Override default values with these if the user sets the TestingTorNetwork
651 * option. */
652static const config_var_t testing_tor_network_defaults[] = {
653  V(DirAllowPrivateAddresses,    BOOL,     "1"),
654  V(EnforceDistinctSubnets,      BOOL,     "0"),
655  V(AssumeReachable,             BOOL,     "1"),
656  V(AuthDirMaxServersPerAddr,    UINT,     "0"),
657  V(ClientBootstrapConsensusAuthorityDownloadSchedule, CSV_INTERVAL,
658    "0, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 8, 16, 32, 60"),
659  V(ClientBootstrapConsensusFallbackDownloadSchedule, CSV_INTERVAL,
660    "0, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 8, 16, 32, 60"),
661  V(ClientBootstrapConsensusAuthorityOnlyDownloadSchedule, CSV_INTERVAL,
662    "0, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 8, 16, 32, 60"),
663  V(ClientBootstrapConsensusMaxDownloadTries, UINT, "80"),
664  V(ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries, UINT, "80"),
665  V(ClientDNSRejectInternalAddresses, BOOL,"0"),
666  V(ClientRejectInternalAddresses, BOOL,   "0"),
667  V(CountPrivateBandwidth,       BOOL,     "1"),
668  V(ExitPolicyRejectPrivate,     BOOL,     "0"),
669  V(ExtendAllowPrivateAddresses, BOOL,     "1"),
670  V(V3AuthVotingInterval,        INTERVAL, "5 minutes"),
671  V(V3AuthVoteDelay,             INTERVAL, "20 seconds"),
672  V(V3AuthDistDelay,             INTERVAL, "20 seconds"),
673  V(TestingV3AuthInitialVotingInterval, INTERVAL, "150 seconds"),
674  V(TestingV3AuthInitialVoteDelay, INTERVAL, "20 seconds"),
675  V(TestingV3AuthInitialDistDelay, INTERVAL, "20 seconds"),
676  V(TestingAuthDirTimeToLearnReachability, INTERVAL, "0 minutes"),
677  V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "0 minutes"),
678  V(MinUptimeHidServDirectoryV2, INTERVAL, "0 minutes"),
679  V(TestingServerDownloadSchedule, CSV_INTERVAL, "0, 0, 0, 5, 10, 15, "
680                                 "20, 30, 60"),
681  V(TestingClientDownloadSchedule, CSV_INTERVAL, "0, 0, 5, 10, 15, 20, "
682                                 "30, 60"),
683  V(TestingServerConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 5, 10, "
684                                 "15, 20, 30, 60"),
685  V(TestingClientConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 5, 10, "
686                                 "15, 20, 30, 60"),
687  V(TestingBridgeDownloadSchedule, CSV_INTERVAL, "10, 30, 60"),
688  V(TestingBridgeBootstrapDownloadSchedule, CSV_INTERVAL, "0, 0, 5, 10, "
689                                 "15, 20, 30, 60"),
690  V(TestingClientMaxIntervalWithoutRequest, INTERVAL, "5 seconds"),
691  V(TestingDirConnectionMaxStall, INTERVAL, "30 seconds"),
692  V(TestingConsensusMaxDownloadTries, UINT, "80"),
693  V(TestingDescriptorMaxDownloadTries, UINT, "80"),
694  V(TestingMicrodescMaxDownloadTries, UINT, "80"),
695  V(TestingCertMaxDownloadTries, UINT, "80"),
696  V(TestingEnableConnBwEvent,    BOOL,     "1"),
697  V(TestingEnableCellStatsEvent, BOOL,     "1"),
698  V(TestingEnableTbEmptyEvent,   BOOL,     "1"),
699  VAR("___UsingTestNetworkDefaults", BOOL, UsingTestNetworkDefaults_, "1"),
700  V(RendPostPeriod,              INTERVAL, "2 minutes"),
701
702  END_OF_CONFIG_VARS
703};
704
705#undef VAR
706#undef V
707#undef OBSOLETE
708
709static const config_deprecation_t option_deprecation_notes_[] = {
710  /* Deprecated since 0.3.2.0-alpha. */
711  { "HTTPProxy", "It only applies to direct unencrypted HTTP connections "
712    "to your directory server, which your Tor probably wasn't using." },
713  { "HTTPProxyAuthenticator", "HTTPProxy is deprecated in favor of HTTPSProxy "
714    "which should be used with HTTPSProxyAuthenticator." },
715  /* End of options deprecated since 0.3.2.1-alpha */
716
717  /* Options deprecated since 0.3.2.2-alpha */
718  { "ReachableDirAddresses", "It has no effect on relays, and has had no "
719    "effect on clients since 0.2.8." },
720  { "ClientPreferIPv6DirPort", "It has no effect on relays, and has had no "
721    "effect on clients since 0.2.8." },
722  /* End of options deprecated since 0.3.2.2-alpha. */
723
724  { NULL, NULL }
725};
726
727#ifdef _WIN32
728static char *get_windows_conf_root(void);
729#endif
730static int options_act_reversible(const or_options_t *old_options, char **msg);
731static int options_transition_allowed(const or_options_t *old,
732                                      const or_options_t *new,
733                                      char **msg);
734static int options_transition_affects_workers(
735      const or_options_t *old_options, const or_options_t *new_options);
736static int options_transition_affects_descriptor(
737      const or_options_t *old_options, const or_options_t *new_options);
738static int normalize_nickname_list(config_line_t **normalized_out,
739                                   const config_line_t *lst, const char *name,
740                                   char **msg);
741static char *get_bindaddr_from_transport_listen_line(const char *line,
742                                                     const char *transport);
743static int parse_ports(or_options_t *options, int validate_only,
744                              char **msg_out, int *n_ports_out,
745                              int *world_writable_control_socket);
746static int check_server_ports(const smartlist_t *ports,
747                              const or_options_t *options,
748                              int *num_low_ports_out);
749static int validate_data_directories(or_options_t *options);
750static int write_configuration_file(const char *fname,
751                                    const or_options_t *options);
752static int options_init_logs(const or_options_t *old_options,
753                             or_options_t *options, int validate_only);
754
755static void init_libevent(const or_options_t *options);
756static int opt_streq(const char *s1, const char *s2);
757static int parse_outbound_addresses(or_options_t *options, int validate_only,
758                                    char **msg);
759static void config_maybe_load_geoip_files_(const or_options_t *options,
760                                           const or_options_t *old_options);
761static int options_validate_cb(void *old_options, void *options,
762                               void *default_options,
763                               int from_setconf, char **msg);
764static uint64_t compute_real_max_mem_in_queues(const uint64_t val,
765                                               int log_guess);
766
767/** Magic value for or_options_t. */
768#define OR_OPTIONS_MAGIC 9090909
769
770/** Configuration format for or_options_t. */
771STATIC config_format_t options_format = {
772  sizeof(or_options_t),
773  OR_OPTIONS_MAGIC,
774  offsetof(or_options_t, magic_),
775  option_abbrevs_,
776  option_deprecation_notes_,
777  option_vars_,
778  options_validate_cb,
779  NULL
780};
781
782/*
783 * Functions to read and write the global options pointer.
784 */
785
786/** Command-line and config-file options. */
787static or_options_t *global_options = NULL;
788/** The fallback options_t object; this is where we look for options not
789 * in torrc before we fall back to Tor's defaults. */
790static or_options_t *global_default_options = NULL;
791/** Name of most recently read torrc file. */
792static char *torrc_fname = NULL;
793/** Name of the most recently read torrc-defaults file.*/
794static char *torrc_defaults_fname = NULL;
795/** Configuration options set by command line. */
796static config_line_t *global_cmdline_options = NULL;
797/** Non-configuration options set by the command line */
798static config_line_t *global_cmdline_only_options = NULL;
799/** Boolean: Have we parsed the command line? */
800static int have_parsed_cmdline = 0;
801/** Contents of most recently read DirPortFrontPage file. */
802static char *global_dirfrontpagecontents = NULL;
803/** List of port_cfg_t for all configured ports. */
804static smartlist_t *configured_ports = NULL;
805/** True iff we're currently validating options, and any calls to
806 * get_options() are likely to be bugs. */
807static int in_option_validation = 0;
808
809/** Return the contents of our frontpage string, or NULL if not configured. */
810MOCK_IMPL(const char*,
811get_dirportfrontpage, (void))
812{
813  return global_dirfrontpagecontents;
814}
815
816/** Returns the currently configured options. */
817MOCK_IMPL(or_options_t *,
818get_options_mutable, (void))
819{
820  tor_assert(global_options);
821  tor_assert_nonfatal(! in_option_validation);
822  return global_options;
823}
824
825/** Returns the currently configured options */
826MOCK_IMPL(const or_options_t *,
827get_options,(void))
828{
829  return get_options_mutable();
830}
831
832/** Change the current global options to contain <b>new_val</b> instead of
833 * their current value; take action based on the new value; free the old value
834 * as necessary.  Returns 0 on success, -1 on failure.
835 */
836int
837set_options(or_options_t *new_val, char **msg)
838{
839  int i;
840  smartlist_t *elements;
841  config_line_t *line;
842  or_options_t *old_options = global_options;
843  global_options = new_val;
844  /* Note that we pass the *old* options below, for comparison. It
845   * pulls the new options directly out of global_options. */
846  if (options_act_reversible(old_options, msg)<0) {
847    tor_assert(*msg);
848    global_options = old_options;
849    return -1;
850  }
851  if (options_act(old_options) < 0) { /* acting on the options failed. die. */
852    if (! tor_event_loop_shutdown_is_pending()) {
853      log_err(LD_BUG,
854              "Acting on config options left us in a broken state. Dying.");
855      tor_shutdown_event_loop_and_exit(1);
856    }
857    return -1;
858  }
859  /* Issues a CONF_CHANGED event to notify controller of the change. If Tor is
860   * just starting up then the old_options will be undefined. */
861  if (old_options && old_options != global_options) {
862    elements = smartlist_new();
863    for (i=0; options_format.vars[i].name; ++i) {
864      const config_var_t *var = &options_format.vars[i];
865      const char *var_name = var->name;
866      if (var->type == CONFIG_TYPE_LINELIST_S ||
867          var->type == CONFIG_TYPE_OBSOLETE) {
868        continue;
869      }
870      if (!config_is_same(&options_format, new_val, old_options, var_name)) {
871        line = config_get_assigned_option(&options_format, new_val,
872                                          var_name, 1);
873
874        if (line) {
875          config_line_t *next;
876          for (; line; line = next) {
877            next = line->next;
878            smartlist_add(elements, line->key);
879            smartlist_add(elements, line->value);
880            tor_free(line);
881          }
882        } else {
883          smartlist_add_strdup(elements, options_format.vars[i].name);
884          smartlist_add(elements, NULL);
885        }
886      }
887    }
888    control_event_conf_changed(elements);
889    SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
890    smartlist_free(elements);
891  }
892
893  if (old_options != global_options)
894    or_options_free(old_options);
895
896  return 0;
897}
898
899/** The version of this Tor process, as parsed. */
900static char *the_tor_version = NULL;
901/** A shorter version of this Tor process's version, for export in our router
902 *  descriptor.  (Does not include the git version, if any.) */
903static char *the_short_tor_version = NULL;
904
905/** Return the current Tor version. */
906const char *
907get_version(void)
908{
909  if (the_tor_version == NULL) {
910    if (strlen(tor_git_revision)) {
911      tor_asprintf(&the_tor_version, "%s (git-%s)", get_short_version(),
912                   tor_git_revision);
913    } else {
914      the_tor_version = tor_strdup(get_short_version());
915    }
916  }
917  return the_tor_version;
918}
919
920/** Return the current Tor version, without any git tag. */
921const char *
922get_short_version(void)
923{
924
925  if (the_short_tor_version == NULL) {
926#ifdef TOR_BUILD_TAG
927    tor_asprintf(&the_short_tor_version, "%s (%s)", VERSION, TOR_BUILD_TAG);
928#else
929    the_short_tor_version = tor_strdup(VERSION);
930#endif
931  }
932  return the_short_tor_version;
933}
934
935/** Release additional memory allocated in options
936 */
937STATIC void
938or_options_free_(or_options_t *options)
939{
940  if (!options)
941    return;
942
943  routerset_free(options->ExcludeExitNodesUnion_);
944  if (options->NodeFamilySets) {
945    SMARTLIST_FOREACH(options->NodeFamilySets, routerset_t *,
946                      rs, routerset_free(rs));
947    smartlist_free(options->NodeFamilySets);
948  }
949  if (options->SchedulerTypes_) {
950    SMARTLIST_FOREACH(options->SchedulerTypes_, int *, i, tor_free(i));
951    smartlist_free(options->SchedulerTypes_);
952  }
953  if (options->FilesOpenedByIncludes) {
954    SMARTLIST_FOREACH(options->FilesOpenedByIncludes, char *, f, tor_free(f));
955    smartlist_free(options->FilesOpenedByIncludes);
956  }
957  tor_free(options->DataDirectory);
958  tor_free(options->CacheDirectory);
959  tor_free(options->KeyDirectory);
960  tor_free(options->BridgePassword_AuthDigest_);
961  tor_free(options->command_arg);
962  tor_free(options->master_key_fname);
963  config_free_lines(options->MyFamily);
964  config_free(&options_format, options);
965}
966
967/** Release all memory and resources held by global configuration structures.
968 */
969void
970config_free_all(void)
971{
972  or_options_free(global_options);
973  global_options = NULL;
974  or_options_free(global_default_options);
975  global_default_options = NULL;
976
977  config_free_lines(global_cmdline_options);
978  global_cmdline_options = NULL;
979
980  config_free_lines(global_cmdline_only_options);
981  global_cmdline_only_options = NULL;
982
983  if (configured_ports) {
984    SMARTLIST_FOREACH(configured_ports,
985                      port_cfg_t *, p, port_cfg_free(p));
986    smartlist_free(configured_ports);
987    configured_ports = NULL;
988  }
989
990  tor_free(torrc_fname);
991  tor_free(torrc_defaults_fname);
992  tor_free(global_dirfrontpagecontents);
993
994  tor_free(the_short_tor_version);
995  tor_free(the_tor_version);
996
997  have_parsed_cmdline = 0;
998}
999
1000/** Make <b>address</b> -- a piece of information related to our operation as
1001 * a client -- safe to log according to the settings in options->SafeLogging,
1002 * and return it.
1003 *
1004 * (We return "[scrubbed]" if SafeLogging is "1", and address otherwise.)
1005 */
1006const char *
1007safe_str_client(const char *address)
1008{
1009  tor_assert(address);
1010  if (get_options()->SafeLogging_ == SAFELOG_SCRUB_ALL)
1011    return "[scrubbed]";
1012  else
1013    return address;
1014}
1015
1016/** Make <b>address</b> -- a piece of information of unspecified sensitivity
1017 * -- safe to log according to the settings in options->SafeLogging, and
1018 * return it.
1019 *
1020 * (We return "[scrubbed]" if SafeLogging is anything besides "0", and address
1021 * otherwise.)
1022 */
1023const char *
1024safe_str(const char *address)
1025{
1026  tor_assert(address);
1027  if (get_options()->SafeLogging_ != SAFELOG_SCRUB_NONE)
1028    return "[scrubbed]";
1029  else
1030    return address;
1031}
1032
1033/** Equivalent to escaped(safe_str_client(address)).  See reentrancy note on
1034 * escaped(): don't use this outside the main thread, or twice in the same
1035 * log statement. */
1036const char *
1037escaped_safe_str_client(const char *address)
1038{
1039  if (get_options()->SafeLogging_ == SAFELOG_SCRUB_ALL)
1040    return "[scrubbed]";
1041  else
1042    return escaped(address);
1043}
1044
1045/** Equivalent to escaped(safe_str(address)).  See reentrancy note on
1046 * escaped(): don't use this outside the main thread, or twice in the same
1047 * log statement. */
1048const char *
1049escaped_safe_str(const char *address)
1050{
1051  if (get_options()->SafeLogging_ != SAFELOG_SCRUB_NONE)
1052    return "[scrubbed]";
1053  else
1054    return escaped(address);
1055}
1056
1057/**
1058 * The severity level that should be used for warnings of severity
1059 * LOG_PROTOCOL_WARN.
1060 *
1061 * We keep this outside the options, in case somebody needs to use
1062 * LOG_PROTOCOL_WARN while an option transition is happening.
1063 */
1064static int protocol_warning_severity_level = LOG_WARN;
1065
1066/** Return the severity level that should be used for warnings of severity
1067 * LOG_PROTOCOL_WARN. */
1068int
1069get_protocol_warning_severity_level(void)
1070{
1071  return protocol_warning_severity_level;
1072}
1073
1074/** List of default directory authorities */
1075
1076static const char *default_authorities[] = {
1077#include "auth_dirs.inc"
1078  NULL
1079};
1080
1081/** List of fallback directory authorities. The list is generated by opt-in of
1082 * relays that meet certain stability criteria.
1083 */
1084static const char *default_fallbacks[] = {
1085#include "fallback_dirs.inc"
1086  NULL
1087};
1088
1089/** Add the default directory authorities directly into the trusted dir list,
1090 * but only add them insofar as they share bits with <b>type</b>.
1091 * Each authority's bits are restricted to the bits shared with <b>type</b>.
1092 * If <b>type</b> is ALL_DIRINFO or NO_DIRINFO (zero), add all authorities. */
1093STATIC void
1094add_default_trusted_dir_authorities(dirinfo_type_t type)
1095{
1096  int i;
1097  for (i=0; default_authorities[i]; i++) {
1098    if (parse_dir_authority_line(default_authorities[i], type, 0)<0) {
1099      log_err(LD_BUG, "Couldn't parse internal DirAuthority line %s",
1100              default_authorities[i]);
1101    }
1102  }
1103}
1104
1105/** Add the default fallback directory servers into the fallback directory
1106 * server list. */
1107MOCK_IMPL(void,
1108add_default_fallback_dir_servers,(void))
1109{
1110  int i;
1111  for (i=0; default_fallbacks[i]; i++) {
1112    if (parse_dir_fallback_line(default_fallbacks[i], 0)<0) {
1113      log_err(LD_BUG, "Couldn't parse internal FallbackDir line %s",
1114              default_fallbacks[i]);
1115    }
1116  }
1117}
1118
1119/** Look at all the config options for using alternate directory
1120 * authorities, and make sure none of them are broken. Also, warn the
1121 * user if we changed any dangerous ones.
1122 */
1123static int
1124validate_dir_servers(or_options_t *options, or_options_t *old_options)
1125{
1126  config_line_t *cl;
1127
1128  if (options->DirAuthorities &&
1129      (options->AlternateDirAuthority || options->AlternateBridgeAuthority)) {
1130    log_warn(LD_CONFIG,
1131             "You cannot set both DirAuthority and Alternate*Authority.");
1132    return -1;
1133  }
1134
1135  /* do we want to complain to the user about being partitionable? */
1136  if ((options->DirAuthorities &&
1137       (!old_options ||
1138        !config_lines_eq(options->DirAuthorities,
1139                         old_options->DirAuthorities))) ||
1140      (options->AlternateDirAuthority &&
1141       (!old_options ||
1142        !config_lines_eq(options->AlternateDirAuthority,
1143                         old_options->AlternateDirAuthority)))) {
1144    log_warn(LD_CONFIG,
1145             "You have used DirAuthority or AlternateDirAuthority to "
1146             "specify alternate directory authorities in "
1147             "your configuration. This is potentially dangerous: it can "
1148             "make you look different from all other Tor users, and hurt "
1149             "your anonymity. Even if you've specified the same "
1150             "authorities as Tor uses by default, the defaults could "
1151             "change in the future. Be sure you know what you're doing.");
1152  }
1153
1154  /* Now go through the four ways you can configure an alternate
1155   * set of directory authorities, and make sure none are broken. */
1156  for (cl = options->DirAuthorities; cl; cl = cl->next)
1157    if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
1158      return -1;
1159  for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
1160    if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
1161      return -1;
1162  for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
1163    if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
1164      return -1;
1165  for (cl = options->FallbackDir; cl; cl = cl->next)
1166    if (parse_dir_fallback_line(cl->value, 1)<0)
1167      return -1;
1168  return 0;
1169}
1170
1171/** Look at all the config options and assign new dir authorities
1172 * as appropriate.
1173 */
1174int
1175consider_adding_dir_servers(const or_options_t *options,
1176                            const or_options_t *old_options)
1177{
1178  config_line_t *cl;
1179  int need_to_update =
1180    !smartlist_len(router_get_trusted_dir_servers()) ||
1181    !smartlist_len(router_get_fallback_dir_servers()) || !old_options ||
1182    !config_lines_eq(options->DirAuthorities, old_options->DirAuthorities) ||
1183    !config_lines_eq(options->FallbackDir, old_options->FallbackDir) ||
1184    (options->UseDefaultFallbackDirs != old_options->UseDefaultFallbackDirs) ||
1185    !config_lines_eq(options->AlternateBridgeAuthority,
1186                     old_options->AlternateBridgeAuthority) ||
1187    !config_lines_eq(options->AlternateDirAuthority,
1188                     old_options->AlternateDirAuthority);
1189
1190  if (!need_to_update)
1191    return 0; /* all done */
1192
1193  /* "You cannot set both DirAuthority and Alternate*Authority."
1194   * Checking that this restriction holds allows us to simplify
1195   * the unit tests. */
1196  tor_assert(!(options->DirAuthorities &&
1197               (options->AlternateDirAuthority
1198                || options->AlternateBridgeAuthority)));
1199
1200  /* Start from a clean slate. */
1201  clear_dir_servers();
1202
1203  if (!options->DirAuthorities) {
1204    /* then we may want some of the defaults */
1205    dirinfo_type_t type = NO_DIRINFO;
1206    if (!options->AlternateBridgeAuthority) {
1207      type |= BRIDGE_DIRINFO;
1208    }
1209    if (!options->AlternateDirAuthority) {
1210      type |= V3_DIRINFO | EXTRAINFO_DIRINFO | MICRODESC_DIRINFO;
1211      /* Only add the default fallback directories when the DirAuthorities,
1212       * AlternateDirAuthority, and FallbackDir directory config options
1213       * are set to their defaults, and when UseDefaultFallbackDirs is 1. */
1214      if (!options->FallbackDir && options->UseDefaultFallbackDirs) {
1215        add_default_fallback_dir_servers();
1216      }
1217    }
1218    /* if type == NO_DIRINFO, we don't want to add any of the
1219     * default authorities, because we've replaced them all */
1220    if (type != NO_DIRINFO)
1221      add_default_trusted_dir_authorities(type);
1222  }
1223
1224  for (cl = options->DirAuthorities; cl; cl = cl->next)
1225    if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
1226      return -1;
1227  for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
1228    if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
1229      return -1;
1230  for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
1231    if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
1232      return -1;
1233  for (cl = options->FallbackDir; cl; cl = cl->next)
1234    if (parse_dir_fallback_line(cl->value, 0)<0)
1235      return -1;
1236  return 0;
1237}
1238
1239/**
1240 * Make sure that <b>directory</b> exists, with appropriate ownership and
1241 * permissions (as modified by <b>group_readable</b>). If <b>create</b>,
1242 * create the directory if it is missing. Return 0 on success.
1243 * On failure, return -1 and set *<b>msg_out</b>.
1244 */
1245static int
1246check_and_create_data_directory(int create,
1247                                const char *directory,
1248                                int group_readable,
1249                                const char *owner,
1250                                char **msg_out)
1251{
1252  cpd_check_t cpd_opts = create ? CPD_CREATE : CPD_CHECK;
1253  if (group_readable)
1254      cpd_opts |= CPD_GROUP_READ;
1255  if (check_private_dir(directory,
1256                        cpd_opts,
1257                        owner) < 0) {
1258    tor_asprintf(msg_out,
1259                 "Couldn't %s private data directory \"%s\"",
1260                 create ? "create" : "access",
1261                 directory);
1262    return -1;
1263  }
1264
1265#ifndef _WIN32
1266  if (group_readable) {
1267    /* Only new dirs created get new opts, also enforce group read. */
1268    if (chmod(directory, 0750)) {
1269      log_warn(LD_FS,"Unable to make %s group-readable: %s",
1270               directory, strerror(errno));
1271    }
1272  }
1273#endif /* !defined(_WIN32) */
1274
1275  return 0;
1276}
1277
1278/**
1279 * Ensure that our keys directory exists, with appropriate permissions.
1280 * Return 0 on success, -1 on failure.
1281 */
1282int
1283create_keys_directory(const or_options_t *options)
1284{
1285  /* Make sure DataDirectory exists, and is private. */
1286  cpd_check_t cpd_opts = CPD_CREATE;
1287  if (options->DataDirectoryGroupReadable)
1288    cpd_opts |= CPD_GROUP_READ;
1289  if (check_private_dir(options->DataDirectory, cpd_opts, options->User)) {
1290    log_err(LD_OR, "Can't create/check datadirectory %s",
1291            options->DataDirectory);
1292    return -1;
1293  }
1294
1295  /* Check the key directory. */
1296  if (check_private_dir(options->KeyDirectory, CPD_CREATE, options->User)) {
1297    return -1;
1298  }
1299  return 0;
1300}
1301
1302/* Helps determine flags to pass to switch_id. */
1303static int have_low_ports = -1;
1304
1305/** Fetch the active option list, and take actions based on it. All of the
1306 * things we do should survive being done repeatedly.  If present,
1307 * <b>old_options</b> contains the previous value of the options.
1308 *
1309 * Return 0 if all goes well, return -1 if things went badly.
1310 */
1311static int
1312options_act_reversible(const or_options_t *old_options, char **msg)
1313{
1314  smartlist_t *new_listeners = smartlist_new();
1315  smartlist_t *replaced_listeners = smartlist_new();
1316  static int libevent_initialized = 0;
1317  or_options_t *options = get_options_mutable();
1318  int running_tor = options->command == CMD_RUN_TOR;
1319  int set_conn_limit = 0;
1320  int r = -1;
1321  int logs_marked = 0, logs_initialized = 0;
1322  int old_min_log_level = get_min_log_level();
1323
1324  /* Daemonize _first_, since we only want to open most of this stuff in
1325   * the subprocess.  Libevent bases can't be reliably inherited across
1326   * processes. */
1327  if (running_tor && options->RunAsDaemon) {
1328    /* No need to roll back, since you can't change the value. */
1329    start_daemon();
1330  }
1331
1332#ifdef HAVE_SYSTEMD
1333  /* Our PID may have changed, inform supervisor */
1334  sd_notifyf(0, "MAINPID=%ld\n", (long int)getpid());
1335#endif
1336
1337#ifndef HAVE_SYS_UN_H
1338  if (options->ControlSocket || options->ControlSocketsGroupWritable) {
1339    *msg = tor_strdup("Unix domain sockets (ControlSocket) not supported "
1340                      "on this OS/with this build.");
1341    goto rollback;
1342  }
1343#else /* !(!defined(HAVE_SYS_UN_H)) */
1344  if (options->ControlSocketsGroupWritable && !options->ControlSocket) {
1345    *msg = tor_strdup("Setting ControlSocketGroupWritable without setting"
1346                      "a ControlSocket makes no sense.");
1347    goto rollback;
1348  }
1349#endif /* !defined(HAVE_SYS_UN_H) */
1350
1351  if (running_tor) {
1352    int n_ports=0;
1353    /* We need to set the connection limit before we can open the listeners. */
1354    if (! sandbox_is_active()) {
1355      if (set_max_file_descriptors((unsigned)options->ConnLimit,
1356                                   &options->ConnLimit_) < 0) {
1357        *msg = tor_strdup("Problem with ConnLimit value. "
1358                          "See logs for details.");
1359        goto rollback;
1360      }
1361      set_conn_limit = 1;
1362    } else {
1363      tor_assert(old_options);
1364      options->ConnLimit_ = old_options->ConnLimit_;
1365    }
1366
1367    /* Set up libevent.  (We need to do this before we can register the
1368     * listeners as listeners.) */
1369    if (running_tor && !libevent_initialized) {
1370      init_libevent(options);
1371      libevent_initialized = 1;
1372
1373      /* This has to come up after libevent is initialized. */
1374      control_initialize_event_queue();
1375
1376      /*
1377       * Initialize the scheduler - this has to come after
1378       * options_init_from_torrc() sets up libevent - why yes, that seems
1379       * completely sensible to hide the libevent setup in the option parsing
1380       * code!  It also needs to happen before init_keys(), so it needs to
1381       * happen here too.  How yucky. */
1382      scheduler_init();
1383    }
1384
1385    /* Adjust the port configuration so we can launch listeners. */
1386    if (parse_ports(options, 0, msg, &n_ports, NULL)) {
1387      if (!*msg)
1388        *msg = tor_strdup("Unexpected problem parsing port config");
1389      goto rollback;
1390    }
1391
1392    /* Set the hibernation state appropriately.*/
1393    consider_hibernation(time(NULL));
1394
1395    /* Launch the listeners.  (We do this before we setuid, so we can bind to
1396     * ports under 1024.)  We don't want to rebind if we're hibernating. If
1397     * networking is disabled, this will close all but the control listeners,
1398     * but disable those. */
1399    if (!we_are_hibernating()) {
1400      if (retry_all_listeners(replaced_listeners, new_listeners,
1401                              options->DisableNetwork) < 0) {
1402        *msg = tor_strdup("Failed to bind one of the listener ports.");
1403        goto rollback;
1404      }
1405    }
1406    if (options->DisableNetwork) {
1407      /* Aggressively close non-controller stuff, NOW */
1408      log_notice(LD_NET, "DisableNetwork is set. Tor will not make or accept "
1409                 "non-control network connections. Shutting down all existing "
1410                 "connections.");
1411      connection_mark_all_noncontrol_connections();
1412      /* We can't complete circuits until the network is re-enabled. */
1413      note_that_we_maybe_cant_complete_circuits();
1414    }
1415  }
1416
1417#if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
1418  /* Open /dev/pf before dropping privileges. */
1419  if (options->TransPort_set &&
1420      options->TransProxyType_parsed == TPT_DEFAULT) {
1421    if (get_pf_socket() < 0) {
1422      *msg = tor_strdup("Unable to open /dev/pf for transparent proxy.");
1423      goto rollback;
1424    }
1425  }
1426#endif /* defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H) */
1427
1428  /* Attempt to lock all current and future memory with mlockall() only once */
1429  if (options->DisableAllSwap) {
1430    if (tor_mlockall() == -1) {
1431      *msg = tor_strdup("DisableAllSwap failure. Do you have proper "
1432                        "permissions?");
1433      goto done;
1434    }
1435  }
1436
1437  /* Setuid/setgid as appropriate */
1438  if (options->User) {
1439    tor_assert(have_low_ports != -1);
1440    unsigned switch_id_flags = 0;
1441    if (options->KeepBindCapabilities == 1) {
1442      switch_id_flags |= SWITCH_ID_KEEP_BINDLOW;
1443      switch_id_flags |= SWITCH_ID_WARN_IF_NO_CAPS;
1444    }
1445    if (options->KeepBindCapabilities == -1 && have_low_ports) {
1446      switch_id_flags |= SWITCH_ID_KEEP_BINDLOW;
1447    }
1448    if (switch_id(options->User, switch_id_flags) != 0) {
1449      /* No need to roll back, since you can't change the value. */
1450      *msg = tor_strdup("Problem with User value. See logs for details.");
1451      goto done;
1452    }
1453  }
1454
1455  /* Ensure data directory is private; create if possible. */
1456  /* It's okay to do this in "options_act_reversible()" even though it isn't
1457   * actually reversible, since you can't change the DataDirectory while
1458   * Tor is running. */
1459  if (check_and_create_data_directory(running_tor /* create */,
1460                                      options->DataDirectory,
1461                                      options->DataDirectoryGroupReadable,
1462                                      options->User,
1463                                      msg) < 0) {
1464    goto done;
1465  }
1466  if (check_and_create_data_directory(running_tor /* create */,
1467                                      options->KeyDirectory,
1468                                      options->KeyDirectoryGroupReadable,
1469                                      options->User,
1470                                      msg) < 0) {
1471    goto done;
1472  }
1473  if (check_and_create_data_directory(running_tor /* create */,
1474                                      options->CacheDirectory,
1475                                      options->CacheDirectoryGroupReadable,
1476                                      options->User,
1477                                      msg) < 0) {
1478    goto done;
1479  }
1480
1481  /* Bail out at this point if we're not going to be a client or server:
1482   * we don't run Tor itself. */
1483  if (!running_tor)
1484    goto commit;
1485
1486  mark_logs_temp(); /* Close current logs once new logs are open. */
1487  logs_marked = 1;
1488  /* Configure the tor_log(s) */
1489  if (options_init_logs(old_options, options, 0)<0) {
1490    *msg = tor_strdup("Failed to init Log options. See logs for details.");
1491    goto rollback;
1492  }
1493  logs_initialized = 1;
1494
1495 commit:
1496  r = 0;
1497  if (logs_marked) {
1498    log_severity_list_t *severity =
1499      tor_malloc_zero(sizeof(log_severity_list_t));
1500    close_temp_logs();
1501    add_callback_log(severity, control_event_logmsg);
1502    control_adjust_event_log_severity();
1503    tor_free(severity);
1504    tor_log_update_sigsafe_err_fds();
1505  }
1506  if (logs_initialized) {
1507    flush_log_messages_from_startup();
1508  }
1509
1510  {
1511    const char *badness = NULL;
1512    int bad_safelog = 0, bad_severity = 0, new_badness = 0;
1513    if (options->SafeLogging_ != SAFELOG_SCRUB_ALL) {
1514      bad_safelog = 1;
1515      if (!old_options || old_options->SafeLogging_ != options->SafeLogging_)
1516        new_badness = 1;
1517    }
1518    if (get_min_log_level() >= LOG_INFO) {
1519      bad_severity = 1;
1520      if (get_min_log_level() != old_min_log_level)
1521        new_badness = 1;
1522    }
1523    if (bad_safelog && bad_severity)
1524      badness = "you disabled SafeLogging, and "
1525        "you're logging more than \"notice\"";
1526    else if (bad_safelog)
1527      badness = "you disabled SafeLogging";
1528    else
1529      badness = "you're logging more than \"notice\"";
1530    if (new_badness)
1531      log_warn(LD_GENERAL, "Your log may contain sensitive information - %s. "
1532               "Don't log unless it serves an important reason. "
1533               "Overwrite the log afterwards.", badness);
1534  }
1535
1536  SMARTLIST_FOREACH(replaced_listeners, connection_t *, conn,
1537  {
1538    int marked = conn->marked_for_close;
1539    log_notice(LD_NET, "Closing old %s on %s:%d",
1540               conn_type_to_string(conn->type), conn->address, conn->port);
1541    connection_close_immediate(conn);
1542    if (!marked) {
1543      connection_mark_for_close(conn);
1544    }
1545  });
1546
1547  if (set_conn_limit) {
1548    /*
1549     * If we adjusted the conn limit, recompute the OOS threshold too
1550     *
1551     * How many possible sockets to keep in reserve?  If we have lots of
1552     * possible sockets, keep this below a limit and set ConnLimit_high_thresh
1553     * very close to ConnLimit_, but if ConnLimit_ is low, shrink it in
1554     * proportion.
1555     *
1556     * Somewhat arbitrarily, set socks_in_reserve to 5% of ConnLimit_, but
1557     * cap it at 64.
1558     */
1559    int socks_in_reserve = options->ConnLimit_ / 20;
1560    if (socks_in_reserve > 64) socks_in_reserve = 64;
1561
1562    options->ConnLimit_high_thresh = options->ConnLimit_ - socks_in_reserve;
1563    options->ConnLimit_low_thresh = (options->ConnLimit_ / 4) * 3;
1564    log_info(LD_GENERAL,
1565             "Recomputed OOS thresholds: ConnLimit %d, ConnLimit_ %d, "
1566             "ConnLimit_high_thresh %d, ConnLimit_low_thresh %d",
1567             options->ConnLimit, options->ConnLimit_,
1568             options->ConnLimit_high_thresh,
1569             options->ConnLimit_low_thresh);
1570
1571    /* Give the OOS handler a chance with the new thresholds */
1572    connection_check_oos(get_n_open_sockets(), 0);
1573  }
1574
1575  goto done;
1576
1577 rollback:
1578  r = -1;
1579  tor_assert(*msg);
1580
1581  if (logs_marked) {
1582    rollback_log_changes();
1583    control_adjust_event_log_severity();
1584  }
1585
1586  if (set_conn_limit && old_options)
1587    set_max_file_descriptors((unsigned)old_options->ConnLimit,
1588                             &options->ConnLimit_);
1589
1590  SMARTLIST_FOREACH(new_listeners, connection_t *, conn,
1591  {
1592    log_notice(LD_NET, "Closing partially-constructed %s on %s:%d",
1593               conn_type_to_string(conn->type), conn->address, conn->port);
1594    connection_close_immediate(conn);
1595    connection_mark_for_close(conn);
1596  });
1597
1598 done:
1599  smartlist_free(new_listeners);
1600  smartlist_free(replaced_listeners);
1601  return r;
1602}
1603
1604/** If we need to have a GEOIP ip-to-country map to run with our configured
1605 * options, return 1 and set *<b>reason_out</b> to a description of why. */
1606int
1607options_need_geoip_info(const or_options_t *options, const char **reason_out)
1608{
1609  int bridge_usage =
1610    options->BridgeRelay && options->BridgeRecordUsageByCountry;
1611  int routerset_usage =
1612    routerset_needs_geoip(options->EntryNodes) ||
1613    routerset_needs_geoip(options->ExitNodes) ||
1614    routerset_needs_geoip(options->ExcludeExitNodes) ||
1615    routerset_needs_geoip(options->ExcludeNodes) ||
1616    routerset_needs_geoip(options->Tor2webRendezvousPoints);
1617
1618  if (routerset_usage && reason_out) {
1619    *reason_out = "We've been configured to use (or avoid) nodes in certain "
1620      "countries, and we need GEOIP information to figure out which ones they "
1621      "are.";
1622  } else if (bridge_usage && reason_out) {
1623    *reason_out = "We've been configured to see which countries can access "
1624      "us as a bridge, and we need GEOIP information to tell which countries "
1625      "clients are in.";
1626  }
1627  return bridge_usage || routerset_usage;
1628}
1629
1630/** Return the bandwidthrate that we are going to report to the authorities
1631 * based on the config options. */
1632uint32_t
1633get_effective_bwrate(const or_options_t *options)
1634{
1635  uint64_t bw = options->BandwidthRate;
1636  if (bw > options->MaxAdvertisedBandwidth)
1637    bw = options->MaxAdvertisedBandwidth;
1638  if (options->RelayBandwidthRate > 0 && bw > options->RelayBandwidthRate)
1639    bw = options->RelayBandwidthRate;
1640  /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1641  return (uint32_t)bw;
1642}
1643
1644/** Return the bandwidthburst that we are going to report to the authorities
1645 * based on the config options. */
1646uint32_t
1647get_effective_bwburst(const or_options_t *options)
1648{
1649  uint64_t bw = options->BandwidthBurst;
1650  if (options->RelayBandwidthBurst > 0 && bw > options->RelayBandwidthBurst)
1651    bw = options->RelayBandwidthBurst;
1652  /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1653  return (uint32_t)bw;
1654}
1655
1656/**
1657 * Return true if changing the configuration from <b>old</b> to <b>new</b>
1658 * affects the guard susbsystem.
1659 */
1660static int
1661options_transition_affects_guards(const or_options_t *old,
1662                                  const or_options_t *new)
1663{
1664  /* NOTE: Make sure this function stays in sync with
1665   * node_passes_guard_filter */
1666
1667  tor_assert(old);
1668  tor_assert(new);
1669
1670  return
1671    (old->UseEntryGuards != new->UseEntryGuards ||
1672     old->UseBridges != new->UseBridges ||
1673     old->ClientUseIPv4 != new->ClientUseIPv4 ||
1674     old->ClientUseIPv6 != new->ClientUseIPv6 ||
1675     old->FascistFirewall != new->FascistFirewall ||
1676     !routerset_equal(old->ExcludeNodes, new->ExcludeNodes) ||
1677     !routerset_equal(old->EntryNodes, new->EntryNodes) ||
1678     !smartlist_strings_eq(old->FirewallPorts, new->FirewallPorts) ||
1679     !config_lines_eq(old->Bridges, new->Bridges) ||
1680     !config_lines_eq(old->ReachableORAddresses, new->ReachableORAddresses) ||
1681     !config_lines_eq(old->ReachableDirAddresses, new->ReachableDirAddresses));
1682}
1683
1684/** Fetch the active option list, and take actions based on it. All of the
1685 * things we do should survive being done repeatedly.  If present,
1686 * <b>old_options</b> contains the previous value of the options.
1687 *
1688 * Return 0 if all goes well, return -1 if it's time to die.
1689 *
1690 * Note: We haven't moved all the "act on new configuration" logic
1691 * here yet.  Some is still in do_hup() and other places.
1692 */
1693STATIC int
1694options_act(const or_options_t *old_options)
1695{
1696  config_line_t *cl;
1697  or_options_t *options = get_options_mutable();
1698  int running_tor = options->command == CMD_RUN_TOR;
1699  char *msg=NULL;
1700  const int transition_affects_workers =
1701    old_options && options_transition_affects_workers(old_options, options);
1702  int old_ewma_enabled;
1703  const int transition_affects_guards =
1704    old_options && options_transition_affects_guards(old_options, options);
1705
1706  if (options->NoExec || options->Sandbox) {
1707    tor_disable_spawning_background_processes();
1708  }
1709
1710  /* disable ptrace and later, other basic debugging techniques */
1711  {
1712    /* Remember if we already disabled debugger attachment */
1713    static int disabled_debugger_attach = 0;
1714    /* Remember if we already warned about being configured not to disable
1715     * debugger attachment */
1716    static int warned_debugger_attach = 0;
1717    /* Don't disable debugger attachment when we're running the unit tests. */
1718    if (options->DisableDebuggerAttachment && !disabled_debugger_attach &&
1719        running_tor) {
1720      int ok = tor_disable_debugger_attach();
1721      /* LCOV_EXCL_START the warned_debugger_attach is 0 can't reach inside. */
1722      if (warned_debugger_attach && ok == 1) {
1723        log_notice(LD_CONFIG, "Disabled attaching debuggers for unprivileged "
1724                   "users.");
1725      }
1726      /* LCOV_EXCL_STOP */
1727      disabled_debugger_attach = (ok == 1);
1728    } else if (!options->DisableDebuggerAttachment &&
1729               !warned_debugger_attach) {
1730      log_notice(LD_CONFIG, "Not disabling debugger attaching for "
1731                 "unprivileged users.");
1732      warned_debugger_attach = 1;
1733    }
1734  }
1735
1736  /* Write control ports to disk as appropriate */
1737  control_ports_write_to_file();
1738
1739  if (running_tor && !have_lockfile()) {
1740    if (try_locking(options, 1) < 0)
1741      return -1;
1742  }
1743
1744  if (options->ProtocolWarnings)
1745    protocol_warning_severity_level = LOG_WARN;
1746  else
1747    protocol_warning_severity_level = LOG_INFO;
1748
1749  if (consider_adding_dir_servers(options, old_options) < 0) {
1750    // XXXX This should get validated earlier, and committed here, to
1751    // XXXX lower opportunities for reaching an error case.
1752    return -1;
1753  }
1754
1755  if (rend_non_anonymous_mode_enabled(options)) {
1756    log_warn(LD_GENERAL, "This copy of Tor was compiled or configured to run "
1757             "in a non-anonymous mode. It will provide NO ANONYMITY.");
1758  }
1759
1760#ifdef ENABLE_TOR2WEB_MODE
1761/* LCOV_EXCL_START */
1762  // XXXX This should move into options_validate()
1763  if (!options->Tor2webMode) {
1764    log_err(LD_CONFIG, "This copy of Tor was compiled to run in "
1765            "'tor2web mode'. It can only be run with the Tor2webMode torrc "
1766            "option enabled.");
1767    return -1;
1768  }
1769/* LCOV_EXCL_STOP */
1770#else /* !(defined(ENABLE_TOR2WEB_MODE)) */
1771  // XXXX This should move into options_validate()
1772  if (options->Tor2webMode) {
1773    log_err(LD_CONFIG, "This copy of Tor was not compiled to run in "
1774            "'tor2web mode'. It cannot be run with the Tor2webMode torrc "
1775            "option enabled. To enable Tor2webMode recompile with the "
1776            "--enable-tor2web-mode option.");
1777    return -1;
1778  }
1779#endif /* defined(ENABLE_TOR2WEB_MODE) */
1780
1781  /* If we are a bridge with a pluggable transport proxy but no
1782     Extended ORPort, inform the user that they are missing out. */
1783  if (server_mode(options) && options->ServerTransportPlugin &&
1784      !options->ExtORPort_lines) {
1785    log_notice(LD_CONFIG, "We use pluggable transports but the Extended "
1786               "ORPort is disabled. Tor and your pluggable transports proxy "
1787               "communicate with each other via the Extended ORPort so it "
1788               "is suggested you enable it: it will also allow your Bridge "
1789               "to collect statistics about its clients that use pluggable "
1790               "transports. Please enable it using the ExtORPort torrc option "
1791               "(e.g. set 'ExtORPort auto').");
1792  }
1793
1794  if (options->Bridges) {
1795    mark_bridge_list();
1796    for (cl = options->Bridges; cl; cl = cl->next) {
1797      bridge_line_t *bridge_line = parse_bridge_line(cl->value);
1798      if (!bridge_line) {
1799        // LCOV_EXCL_START
1800        log_warn(LD_BUG,
1801                 "Previously validated Bridge line could not be added!");
1802        return -1;
1803        // LCOV_EXCL_STOP
1804      }
1805      bridge_add_from_config(bridge_line);
1806    }
1807    sweep_bridge_list();
1808  }
1809
1810  if (running_tor && hs_config_service_all(options, 0)<0) {
1811    // LCOV_EXCL_START
1812    log_warn(LD_BUG,
1813       "Previously validated hidden services line could not be added!");
1814    return -1;
1815    // LCOV_EXCL_STOP
1816  }
1817
1818  if (running_tor && rend_parse_service_authorization(options, 0) < 0) {
1819    // LCOV_EXCL_START
1820    log_warn(LD_BUG, "Previously validated client authorization for "
1821                     "hidden services could not be added!");
1822    return -1;
1823    // LCOV_EXCL_STOP
1824  }
1825
1826  if (running_tor && !old_options && options->OwningControllerFD != -1) {
1827#ifdef _WIN32
1828    log_warn(LD_CONFIG, "OwningControllerFD is not supported on Windows. "
1829             "If you need it, tell the Tor developers.");
1830    return -1;
1831#else
1832    const unsigned ctrl_flags =
1833      CC_LOCAL_FD_IS_OWNER |
1834      CC_LOCAL_FD_IS_AUTHENTICATED;
1835    tor_socket_t ctrl_sock = (tor_socket_t)options->OwningControllerFD;
1836    if (control_connection_add_local_fd(ctrl_sock, ctrl_flags) < 0) {
1837      log_warn(LD_CONFIG, "Could not add local controller connection with "
1838               "given FD.");
1839      return -1;
1840    }
1841#endif /* defined(_WIN32) */
1842  }
1843
1844  /* Load state */
1845  if (! or_state_loaded() && running_tor) {
1846    if (or_state_load())
1847      return -1;
1848    rep_hist_load_mtbf_data(time(NULL));
1849  }
1850
1851  /* If we have an ExtORPort, initialize its auth cookie. */
1852  if (running_tor &&
1853      init_ext_or_cookie_authentication(!!options->ExtORPort_lines) < 0) {
1854    log_warn(LD_CONFIG,"Error creating Extended ORPort cookie file.");
1855    return -1;
1856  }
1857
1858  mark_transport_list();
1859  pt_prepare_proxy_list_for_config_read();
1860  if (!options->DisableNetwork) {
1861    if (options->ClientTransportPlugin) {
1862      for (cl = options->ClientTransportPlugin; cl; cl = cl->next) {
1863        if (parse_transport_line(options, cl->value, 0, 0) < 0) {
1864          // LCOV_EXCL_START
1865          log_warn(LD_BUG,
1866                   "Previously validated ClientTransportPlugin line "
1867                   "could not be added!");
1868          return -1;
1869          // LCOV_EXCL_STOP
1870        }
1871      }
1872    }
1873
1874    if (options->ServerTransportPlugin && server_mode(options)) {
1875      for (cl = options->ServerTransportPlugin; cl; cl = cl->next) {
1876        if (parse_transport_line(options, cl->value, 0, 1) < 0) {
1877          // LCOV_EXCL_START
1878          log_warn(LD_BUG,
1879                   "Previously validated ServerTransportPlugin line "
1880                   "could not be added!");
1881          return -1;
1882          // LCOV_EXCL_STOP
1883        }
1884      }
1885    }
1886  }
1887  sweep_transport_list();
1888  sweep_proxy_list();
1889
1890  /* Start the PT proxy configuration. By doing this configuration
1891     here, we also figure out which proxies need to be restarted and
1892     which not. */
1893  if (pt_proxies_configuration_pending() && !net_is_disabled())
1894    pt_configure_remaining_proxies();
1895
1896  /* Bail out at this point if we're not going to be a client or server:
1897   * we want to not fork, and to log stuff to stderr. */
1898  if (!running_tor)
1899    return 0;
1900
1901  /* Finish backgrounding the process */
1902  if (options->RunAsDaemon) {
1903    /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
1904    finish_daemon(options->DataDirectory);
1905  }
1906
1907  /* We want to reinit keys as needed before we do much of anything else:
1908     keys are important, and other things can depend on them. */
1909  if (transition_affects_workers ||
1910      (options->V3AuthoritativeDir && (!old_options ||
1911                                       !old_options->V3AuthoritativeDir))) {
1912    if (init_keys() < 0) {
1913      log_warn(LD_BUG,"Error initializing keys; exiting");
1914      return -1;
1915    }
1916  }
1917
1918  /* Write our PID to the PID file. If we do not have write permissions we
1919   * will log a warning and exit. */
1920  if (options->PidFile && !sandbox_is_active()) {
1921    if (write_pidfile(options->PidFile) < 0) {
1922      log_err(LD_CONFIG, "Unable to write PIDFile %s",
1923              escaped(options->PidFile));
1924      return -1;
1925    }
1926  }
1927
1928  /* Register addressmap directives */
1929  config_register_addressmaps(options);
1930  parse_virtual_addr_network(options->VirtualAddrNetworkIPv4, AF_INET,0,NULL);
1931  parse_virtual_addr_network(options->VirtualAddrNetworkIPv6, AF_INET6,0,NULL);
1932
1933  /* Update address policies. */
1934  if (policies_parse_from_options(options) < 0) {
1935    /* This should be impossible, but let's be sure. */
1936    log_warn(LD_BUG,"Error parsing already-validated policy options.");
1937    return -1;
1938  }
1939
1940  if (server_mode(options)) {
1941    static int cdm_initialized = 0;
1942    if (cdm_initialized == 0) {
1943      cdm_initialized = 1;
1944      consdiffmgr_configure(NULL);
1945      consdiffmgr_validate();
1946    }
1947  }
1948
1949  if (init_control_cookie_authentication(options->CookieAuthentication) < 0) {
1950    log_warn(LD_CONFIG,"Error creating control cookie authentication file.");
1951    return -1;
1952  }
1953
1954  monitor_owning_controller_process(options->OwningControllerProcess);
1955
1956  /* reload keys as needed for rendezvous services. */
1957  if (hs_service_load_all_keys() < 0) {
1958    log_warn(LD_GENERAL,"Error loading rendezvous service keys");
1959    return -1;
1960  }
1961
1962  /* Inform the scheduler subsystem that a configuration changed happened. It
1963   * might be a change of scheduler or parameter. */
1964  scheduler_conf_changed();
1965
1966  /* Set up accounting */
1967  if (accounting_parse_options(options, 0)<0) {
1968    // LCOV_EXCL_START
1969    log_warn(LD_BUG,"Error in previously validated accounting options");
1970    return -1;
1971    // LCOV_EXCL_STOP
1972  }
1973  if (accounting_is_enabled(options))
1974    configure_accounting(time(NULL));
1975
1976  old_ewma_enabled = cell_ewma_enabled();
1977  /* Change the cell EWMA settings */
1978  cell_ewma_set_scale_factor(options, networkstatus_get_latest_consensus());
1979  /* If we just enabled ewma, set the cmux policy on all active channels */
1980  if (cell_ewma_enabled() && !old_ewma_enabled) {
1981    channel_set_cmux_policy_everywhere(&ewma_policy);
1982  } else if (!cell_ewma_enabled() && old_ewma_enabled) {
1983    /* Turn it off everywhere */
1984    channel_set_cmux_policy_everywhere(NULL);
1985  }
1986
1987  /* Update the BridgePassword's hashed version as needed.  We store this as a
1988   * digest so that we can do side-channel-proof comparisons on it.
1989   */
1990  if (options->BridgePassword) {
1991    char *http_authenticator;
1992    http_authenticator = alloc_http_authenticator(options->BridgePassword);
1993    if (!http_authenticator) {
1994      // XXXX This should get validated in options_validate().
1995      log_warn(LD_BUG, "Unable to allocate HTTP authenticator. Not setting "
1996               "BridgePassword.");
1997      return -1;
1998    }
1999    options->BridgePassword_AuthDigest_ = tor_malloc(DIGEST256_LEN);
2000    crypto_digest256(options->BridgePassword_AuthDigest_,
2001                     http_authenticator, strlen(http_authenticator),
2002                     DIGEST_SHA256);
2003    tor_free(http_authenticator);
2004  }
2005
2006  if (parse_outbound_addresses(options, 0, &msg) < 0) {
2007    // LCOV_EXCL_START
2008    log_warn(LD_BUG, "Failed parsing previously validated outbound "
2009             "bind addresses: %s", msg);
2010    tor_free(msg);
2011    return -1;
2012    // LCOV_EXCL_STOP
2013  }
2014
2015  config_maybe_load_geoip_files_(options, old_options);
2016
2017  if (geoip_is_loaded(AF_INET) && options->GeoIPExcludeUnknown) {
2018    /* ExcludeUnknown is true or "auto" */
2019    const int is_auto = options->GeoIPExcludeUnknown == -1;
2020    int changed;
2021
2022    changed  = routerset_add_unknown_ccs(&options->ExcludeNodes, is_auto);
2023    changed += routerset_add_unknown_ccs(&options->ExcludeExitNodes, is_auto);
2024
2025    if (changed)
2026      routerset_add_unknown_ccs(&options->ExcludeExitNodesUnion_, is_auto);
2027  }
2028
2029  /* Check for transitions that need action. */
2030  if (old_options) {
2031    int revise_trackexithosts = 0;
2032    int revise_automap_entries = 0;
2033    int abandon_circuits = 0;
2034    if ((options->UseEntryGuards && !old_options->UseEntryGuards) ||
2035        options->UseBridges != old_options->UseBridges ||
2036        (options->UseBridges &&
2037         !config_lines_eq(options->Bridges, old_options->Bridges)) ||
2038        !routerset_equal(old_options->ExcludeNodes,options->ExcludeNodes) ||
2039        !routerset_equal(old_options->ExcludeExitNodes,
2040                         options->ExcludeExitNodes) ||
2041        !routerset_equal(old_options->EntryNodes, options->EntryNodes) ||
2042        !routerset_equal(old_options->ExitNodes, options->ExitNodes) ||
2043        !routerset_equal(old_options->Tor2webRendezvousPoints,
2044                         options->Tor2webRendezvousPoints) ||
2045        options->StrictNodes != old_options->StrictNodes) {
2046      log_info(LD_CIRC,
2047               "Changed to using entry guards or bridges, or changed "
2048               "preferred or excluded node lists. "
2049               "Abandoning previous circuits.");
2050      abandon_circuits = 1;
2051    }
2052
2053    if (transition_affects_guards) {
2054      if (guards_update_all()) {
2055        abandon_circuits = 1;
2056      }
2057    }
2058
2059    if (abandon_circuits) {
2060      circuit_mark_all_unused_circs();
2061      circuit_mark_all_dirty_circs_as_unusable();
2062      revise_trackexithosts = 1;
2063    }
2064
2065    if (!smartlist_strings_eq(old_options->TrackHostExits,
2066                              options->TrackHostExits))
2067      revise_trackexithosts = 1;
2068
2069    if (revise_trackexithosts)
2070      addressmap_clear_excluded_trackexithosts(options);
2071
2072    if (!options->AutomapHostsOnResolve &&
2073        old_options->AutomapHostsOnResolve) {
2074        revise_automap_entries = 1;
2075    } else {
2076      if (!smartlist_strings_eq(old_options->AutomapHostsSuffixes,
2077                                options->AutomapHostsSuffixes))
2078        revise_automap_entries = 1;
2079      else if (!opt_streq(old_options->VirtualAddrNetworkIPv4,
2080                          options->VirtualAddrNetworkIPv4) ||
2081               !opt_streq(old_options->VirtualAddrNetworkIPv6,
2082                          options->VirtualAddrNetworkIPv6))
2083        revise_automap_entries = 1;
2084    }
2085
2086    if (revise_automap_entries)
2087      addressmap_clear_invalid_automaps(options);
2088
2089/* How long should we delay counting bridge stats after becoming a bridge?
2090 * We use this so we don't count clients who used our bridge thinking it is
2091 * a relay. If you change this, don't forget to change the log message
2092 * below. It's 4 hours (the time it takes to stop being used by clients)
2093 * plus some extra time for clock skew. */
2094#define RELAY_BRIDGE_STATS_DELAY (6 * 60 * 60)
2095
2096    if (! bool_eq(options->BridgeRelay, old_options->BridgeRelay)) {
2097      int was_relay = 0;
2098      if (options->BridgeRelay) {
2099        time_t int_start = time(NULL);
2100        if (config_lines_eq(old_options->ORPort_lines,options->ORPort_lines)) {
2101          int_start += RELAY_BRIDGE_STATS_DELAY;
2102          was_relay = 1;
2103        }
2104        geoip_bridge_stats_init(int_start);
2105        log_info(LD_CONFIG, "We are acting as a bridge now.  Starting new "
2106                 "GeoIP stats interval%s.", was_relay ? " in 6 "
2107                 "hours from now" : "");
2108      } else {
2109        geoip_bridge_stats_term();
2110        log_info(LD_GENERAL, "We are no longer acting as a bridge.  "
2111                 "Forgetting GeoIP stats.");
2112      }
2113    }
2114
2115    if (transition_affects_workers) {
2116      log_info(LD_GENERAL,
2117               "Worker-related options changed. Rotating workers.");
2118
2119      if (server_mode(options) && !server_mode(old_options)) {
2120        cpu_init();
2121        ip_address_changed(0);
2122        if (have_completed_a_circuit() || !any_predicted_circuits(time(NULL)))
2123          inform_testing_reachability();
2124      }
2125      cpuworkers_rotate_keyinfo();
2126      if (dns_reset())
2127        return -1;
2128    } else {
2129      if (dns_reset())
2130        return -1;
2131    }
2132
2133    if (options->PerConnBWRate != old_options->PerConnBWRate ||
2134        options->PerConnBWBurst != old_options->PerConnBWBurst)
2135      connection_or_update_token_buckets(get_connection_array(), options);
2136
2137    if (options->MainloopStats != old_options->MainloopStats) {
2138      reset_main_loop_counters();
2139    }
2140  }
2141
2142  /* Only collect directory-request statistics on relays and bridges. */
2143  options->DirReqStatistics = options->DirReqStatistics_option &&
2144    server_mode(options);
2145  options->HiddenServiceStatistics =
2146    options->HiddenServiceStatistics_option && server_mode(options);
2147
2148  if (options->CellStatistics || options->DirReqStatistics ||
2149      options->EntryStatistics || options->ExitPortStatistics ||
2150      options->ConnDirectionStatistics ||
2151      options->HiddenServiceStatistics ||
2152      options->BridgeAuthoritativeDir) {
2153    time_t now = time(NULL);
2154    int print_notice = 0;
2155
2156    /* Only collect other relay-only statistics on relays. */
2157    if (!public_server_mode(options)) {
2158      options->CellStatistics = 0;
2159      options->EntryStatistics = 0;
2160      options->ConnDirectionStatistics = 0;
2161      options->ExitPortStatistics = 0;
2162    }
2163
2164    if ((!old_options || !old_options->CellStatistics) &&
2165        options->CellStatistics) {
2166      rep_hist_buffer_stats_init(now);
2167      print_notice = 1;
2168    }
2169    if ((!old_options || !old_options->DirReqStatistics) &&
2170        options->DirReqStatistics) {
2171      if (geoip_is_loaded(AF_INET)) {
2172        geoip_dirreq_stats_init(now);
2173        print_notice = 1;
2174      } else {
2175        /* disable statistics collection since we have no geoip file */
2176        options->DirReqStatistics = 0;
2177        if (options->ORPort_set)
2178          log_notice(LD_CONFIG, "Configured to measure directory request "
2179                                "statistics, but no GeoIP database found. "
2180                                "Please specify a GeoIP database using the "
2181                                "GeoIPFile option.");
2182      }
2183    }
2184    if ((!old_options || !old_options->EntryStatistics) &&
2185        options->EntryStatistics && !should_record_bridge_info(options)) {
2186      if (geoip_is_loaded(AF_INET) || geoip_is_loaded(AF_INET6)) {
2187        geoip_entry_stats_init(now);
2188        print_notice = 1;
2189      } else {
2190        options->EntryStatistics = 0;
2191        log_notice(LD_CONFIG, "Configured to measure entry node "
2192                              "statistics, but no GeoIP database found. "
2193                              "Please specify a GeoIP database using the "
2194                              "GeoIPFile option.");
2195      }
2196    }
2197    if ((!old_options || !old_options->ExitPortStatistics) &&
2198        options->ExitPortStatistics) {
2199      rep_hist_exit_stats_init(now);
2200      print_notice = 1;
2201    }
2202    if ((!old_options || !old_options->ConnDirectionStatistics) &&
2203        options->ConnDirectionStatistics) {
2204      rep_hist_conn_stats_init(now);
2205    }
2206    if ((!old_options || !old_options->HiddenServiceStatistics) &&
2207        options->HiddenServiceStatistics) {
2208      log_info(LD_CONFIG, "Configured to measure hidden service statistics.");
2209      rep_hist_hs_stats_init(now);
2210    }
2211    if ((!old_options || !old_options->BridgeAuthoritativeDir) &&
2212        options->BridgeAuthoritativeDir) {
2213      rep_hist_desc_stats_init(now);
2214      print_notice = 1;
2215    }
2216    if (print_notice)
2217        log_notice(LD_CONFIG, "Configured to measure statistics. Look for "
2218                "the *-stats files that will first be written to the "
2219                 "data directory in 24 hours from now.");
2220  }
2221
2222  /* If we used to have statistics enabled but we just disabled them,
2223     stop gathering them.  */
2224  if (old_options && old_options->CellStatistics &&
2225      !options->CellStatistics)
2226    rep_hist_buffer_stats_term();
2227  if (old_options && old_options->DirReqStatistics &&
2228      !options->DirReqStatistics)
2229    geoip_dirreq_stats_term();
2230  if (old_options && old_options->EntryStatistics &&
2231      !options->EntryStatistics)
2232    geoip_entry_stats_term();
2233  if (old_options && old_options->HiddenServiceStatistics &&
2234      !options->HiddenServiceStatistics)
2235    rep_hist_hs_stats_term();
2236  if (old_options && old_options->ExitPortStatistics &&
2237      !options->ExitPortStatistics)
2238    rep_hist_exit_stats_term();
2239  if (old_options && old_options->ConnDirectionStatistics &&
2240      !options->ConnDirectionStatistics)
2241    rep_hist_conn_stats_term();
2242  if (old_options && old_options->BridgeAuthoritativeDir &&
2243      !options->BridgeAuthoritativeDir)
2244    rep_hist_desc_stats_term();
2245
2246  /* Since our options changed, we might need to regenerate and upload our
2247   * server descriptor.
2248   */
2249  if (!old_options ||
2250      options_transition_affects_descriptor(old_options, options))
2251    mark_my_descriptor_dirty("config change");
2252
2253  /* We may need to reschedule some directory stuff if our status changed. */
2254  if (old_options) {
2255    if (authdir_mode_v3(options) && !authdir_mode_v3(old_options))
2256      dirvote_recalculate_timing(options, time(NULL));
2257    if (!bool_eq(directory_fetches_dir_info_early(options),
2258                 directory_fetches_dir_info_early(old_options)) ||
2259        !bool_eq(directory_fetches_dir_info_later(options),
2260                 directory_fetches_dir_info_later(old_options))) {
2261      /* Make sure update_router_have_minimum_dir_info() gets called. */
2262      router_dir_info_changed();
2263      /* We might need to download a new consensus status later or sooner than
2264       * we had expected. */
2265      update_consensus_networkstatus_fetch_time(time(NULL));
2266    }
2267  }
2268
2269  /* Load the webpage we're going to serve every time someone asks for '/' on
2270     our DirPort. */
2271  tor_free(global_dirfrontpagecontents);
2272  if (options->DirPortFrontPage) {
2273    global_dirfrontpagecontents =
2274      read_file_to_str(options->DirPortFrontPage, 0, NULL);
2275    if (!global_dirfrontpagecontents) {
2276      log_warn(LD_CONFIG,
2277               "DirPortFrontPage file '%s' not found. Continuing anyway.",
2278               options->DirPortFrontPage);
2279    }
2280  }
2281
2282  return 0;
2283}
2284
2285typedef enum {
2286  TAKES_NO_ARGUMENT = 0,
2287  ARGUMENT_NECESSARY = 1,
2288  ARGUMENT_OPTIONAL = 2
2289} takes_argument_t;
2290
2291static const struct {
2292  const char *name;
2293  takes_argument_t takes_argument;
2294} CMDLINE_ONLY_OPTIONS[] = {
2295  { "-f",                     ARGUMENT_NECESSARY },
2296  { "--allow-missing-torrc",  TAKES_NO_ARGUMENT },
2297  { "--defaults-torrc",       ARGUMENT_NECESSARY },
2298  { "--hash-password",        ARGUMENT_NECESSARY },
2299  { "--dump-config",          ARGUMENT_OPTIONAL },
2300  { "--list-fingerprint",     TAKES_NO_ARGUMENT },
2301  { "--keygen",               TAKES_NO_ARGUMENT },
2302  { "--key-expiration",       ARGUMENT_OPTIONAL },
2303  { "--newpass",              TAKES_NO_ARGUMENT },
2304  { "--no-passphrase",        TAKES_NO_ARGUMENT },
2305  { "--passphrase-fd",        ARGUMENT_NECESSARY },
2306  { "--verify-config",        TAKES_NO_ARGUMENT },
2307  { "--ignore-missing-torrc", TAKES_NO_ARGUMENT },
2308  { "--quiet",                TAKES_NO_ARGUMENT },
2309  { "--hush",                 TAKES_NO_ARGUMENT },
2310  { "--version",              TAKES_NO_ARGUMENT },
2311  { "--library-versions",     TAKES_NO_ARGUMENT },
2312  { "-h",                     TAKES_NO_ARGUMENT },
2313  { "--help",                 TAKES_NO_ARGUMENT },
2314  { "--list-torrc-options",   TAKES_NO_ARGUMENT },
2315  { "--list-deprecated-options",TAKES_NO_ARGUMENT },
2316  { "--nt-service",           TAKES_NO_ARGUMENT },
2317  { "-nt-service",            TAKES_NO_ARGUMENT },
2318  { NULL, 0 },
2319};
2320
2321/** Helper: Read a list of configuration options from the command line.  If
2322 * successful, or if ignore_errors is set, put them in *<b>result</b>, put the
2323 * commandline-only options in *<b>cmdline_result</b>, and return 0;
2324 * otherwise, return -1 and leave *<b>result</b> and <b>cmdline_result</b>
2325 * alone. */
2326int
2327config_parse_commandline(int argc, char **argv, int ignore_errors,
2328                         config_line_t **result,
2329                         config_line_t **cmdline_result)
2330{
2331  config_line_t *param = NULL;
2332
2333  config_line_t *front = NULL;
2334  config_line_t **new = &front;
2335
2336  config_line_t *front_cmdline = NULL;
2337  config_line_t **new_cmdline = &front_cmdline;
2338
2339  char *s, *arg;
2340  int i = 1;
2341
2342  while (i < argc) {
2343    unsigned command = CONFIG_LINE_NORMAL;
2344    takes_argument_t want_arg = ARGUMENT_NECESSARY;
2345    int is_cmdline = 0;
2346    int j;
2347
2348    for (j = 0; CMDLINE_ONLY_OPTIONS[j].name != NULL; ++j) {
2349      if (!strcmp(argv[i], CMDLINE_ONLY_OPTIONS[j].name)) {
2350        is_cmdline = 1;
2351        want_arg = CMDLINE_ONLY_OPTIONS[j].takes_argument;
2352        break;
2353      }
2354    }
2355
2356    s = argv[i];
2357
2358    /* Each keyword may be prefixed with one or two dashes. */
2359    if (*s == '-')
2360      s++;
2361    if (*s == '-')
2362      s++;
2363    /* Figure out the command, if any. */
2364    if (*s == '+') {
2365      s++;
2366      command = CONFIG_LINE_APPEND;
2367    } else if (*s == '/') {
2368      s++;
2369      command = CONFIG_LINE_CLEAR;
2370      /* A 'clear' command has no argument. */
2371      want_arg = 0;
2372    }
2373
2374    const int is_last = (i == argc-1);
2375
2376    if (want_arg == ARGUMENT_NECESSARY && is_last) {
2377      if (ignore_errors) {
2378        arg = tor_strdup("");
2379      } else {
2380        log_warn(LD_CONFIG,"Command-line option '%s' with no value. Failing.",
2381            argv[i]);
2382        config_free_lines(front);
2383        config_free_lines(front_cmdline);
2384        return -1;
2385      }
2386    } else if (want_arg == ARGUMENT_OPTIONAL && is_last) {
2387      arg = tor_strdup("");
2388    } else {
2389      arg = (want_arg != TAKES_NO_ARGUMENT) ? tor_strdup(argv[i+1]) :
2390                                              tor_strdup("");
2391    }
2392
2393    param = tor_malloc_zero(sizeof(config_line_t));
2394    param->key = is_cmdline ? tor_strdup(argv[i]) :
2395                   tor_strdup(config_expand_abbrev(&options_format, s, 1, 1));
2396    param->value = arg;
2397    param->command = command;
2398    param->next = NULL;
2399    log_debug(LD_CONFIG, "command line: parsed keyword '%s', value '%s'",
2400        param->key, param->value);
2401
2402    if (is_cmdline) {
2403      *new_cmdline = param;
2404      new_cmdline = &((*new_cmdline)->next);
2405    } else {
2406      *new = param;
2407      new = &((*new)->next);
2408    }
2409
2410    i += want_arg ? 2 : 1;
2411  }
2412  *cmdline_result = front_cmdline;
2413  *result = front;
2414  return 0;
2415}
2416
2417/** Return true iff key is a valid configuration option. */
2418int
2419option_is_recognized(const char *key)
2420{
2421  const config_var_t *var = config_find_option(&options_format, key);
2422  return (var != NULL);
2423}
2424
2425/** Return the canonical name of a configuration option, or NULL
2426 * if no such option exists. */
2427const char *
2428option_get_canonical_name(const char *key)
2429{
2430  const config_var_t *var = config_find_option(&options_format, key);
2431  return var ? var->name : NULL;
2432}
2433
2434/** Return a canonical list of the options assigned for key.
2435 */
2436config_line_t *
2437option_get_assignment(const or_options_t *options, const char *key)
2438{
2439  return config_get_assigned_option(&options_format, options, key, 1);
2440}
2441
2442/** Try assigning <b>list</b> to the global options. You do this by duping
2443 * options, assigning list to the new one, then validating it. If it's
2444 * ok, then throw out the old one and stick with the new one. Else,
2445 * revert to old and return failure.  Return SETOPT_OK on success, or
2446 * a setopt_err_t on failure.
2447 *
2448 * If not success, point *<b>msg</b> to a newly allocated string describing
2449 * what went wrong.
2450 */
2451setopt_err_t
2452options_trial_assign(config_line_t *list, unsigned flags, char **msg)
2453{
2454  int r;
2455  or_options_t *trial_options = config_dup(&options_format, get_options());
2456
2457  if ((r=config_assign(&options_format, trial_options,
2458                       list, flags, msg)) < 0) {
2459    or_options_free(trial_options);
2460    return r;
2461  }
2462
2463  setopt_err_t rv;
2464  or_options_t *cur_options = get_options_mutable();
2465
2466  in_option_validation = 1;
2467
2468  if (options_validate(cur_options, trial_options,
2469                       global_default_options, 1, msg) < 0) {
2470    or_options_free(trial_options);
2471    rv = SETOPT_ERR_PARSE; /*XXX make this a separate return value. */
2472    goto done;
2473  }
2474
2475  if (options_transition_allowed(cur_options, trial_options, msg) < 0) {
2476    or_options_free(trial_options);
2477    rv = SETOPT_ERR_TRANSITION;
2478    goto done;
2479  }
2480  in_option_validation = 0;
2481
2482  if (set_options(trial_options, msg)<0) {
2483    or_options_free(trial_options);
2484    rv = SETOPT_ERR_SETTING;
2485    goto done;
2486  }
2487
2488  /* we liked it. put it in place. */
2489  rv = SETOPT_OK;
2490 done:
2491  in_option_validation = 0;
2492  return rv;
2493}
2494
2495/** Print a usage message for tor. */
2496static void
2497print_usage(void)
2498{
2499  printf(
2500"Copyright (c) 2001-2004, Roger Dingledine\n"
2501"Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
2502"Copyright (c) 2007-2017, The Tor Project, Inc.\n\n"
2503"tor -f <torrc> [args]\n"
2504"See man page for options, or https://www.torproject.org/ for "
2505"documentation.\n");
2506}
2507
2508/** Print all non-obsolete torrc options. */
2509static void
2510list_torrc_options(void)
2511{
2512  int i;
2513  for (i = 0; option_vars_[i].name; ++i) {
2514    const config_var_t *var = &option_vars_[i];
2515    if (var->type == CONFIG_TYPE_OBSOLETE ||
2516        var->type == CONFIG_TYPE_LINELIST_V)
2517      continue;
2518    printf("%s\n", var->name);
2519  }
2520}
2521
2522/** Print all deprecated but non-obsolete torrc options. */
2523static void
2524list_deprecated_options(void)
2525{
2526  const config_deprecation_t *d;
2527  for (d = option_deprecation_notes_; d->name; ++d) {
2528    printf("%s\n", d->name);
2529  }
2530}
2531
2532/** Last value actually set by resolve_my_address. */
2533static uint32_t last_resolved_addr = 0;
2534
2535/** Accessor for last_resolved_addr from outside this file. */
2536uint32_t
2537get_last_resolved_addr(void)
2538{
2539  return last_resolved_addr;
2540}
2541
2542/** Reset last_resolved_addr from outside this file. */
2543void
2544reset_last_resolved_addr(void)
2545{
2546  last_resolved_addr = 0;
2547}
2548
2549/* Return true if <b>options</b> is using the default authorities, and false
2550 * if any authority-related option has been overridden. */
2551int
2552using_default_dir_authorities(const or_options_t *options)
2553{
2554  return (!options->DirAuthorities && !options->AlternateDirAuthority);
2555}
2556
2557/**
2558 * Attempt getting our non-local (as judged by tor_addr_is_internal()
2559 * function) IP address using following techniques, listed in
2560 * order from best (most desirable, try first) to worst (least
2561 * desirable, try if everything else fails).
2562 *
2563 * First, attempt using <b>options-\>Address</b> to get our
2564 * non-local IP address.
2565 *
2566 * If <b>options-\>Address</b> represents a non-local IP address,
2567 * consider it ours.
2568 *
2569 * If <b>options-\>Address</b> is a DNS name that resolves to
2570 * a non-local IP address, consider this IP address ours.
2571 *
2572 * If <b>options-\>Address</b> is NULL, fall back to getting local
2573 * hostname and using it in above-described ways to try and
2574 * get our IP address.
2575 *
2576 * In case local hostname cannot be resolved to a non-local IP
2577 * address, try getting an IP address of network interface
2578 * in hopes it will be non-local one.
2579 *
2580 * Fail if one or more of the following is true:
2581 *   - DNS name in <b>options-\>Address</b> cannot be resolved.
2582 *   - <b>options-\>Address</b> is a local host address.
2583 *   - Attempt at getting local hostname fails.
2584 *   - Attempt at getting network interface address fails.
2585 *
2586 * Return 0 if all is well, or -1 if we can't find a suitable
2587 * public IP address.
2588 *
2589 * If we are returning 0:
2590 *   - Put our public IP address (in host order) into *<b>addr_out</b>.
2591 *   - If <b>method_out</b> is non-NULL, set *<b>method_out</b> to a static
2592 *     string describing how we arrived at our answer.
2593 *      - "CONFIGURED" - parsed from IP address string in
2594 *        <b>options-\>Address</b>
2595 *      - "RESOLVED" - resolved from DNS name in <b>options-\>Address</b>
2596 *      - "GETHOSTNAME" - resolved from a local hostname.
2597 *      - "INTERFACE" - retrieved from a network interface.
2598 *   - If <b>hostname_out</b> is non-NULL, and we resolved a hostname to
2599 *     get our address, set *<b>hostname_out</b> to a newly allocated string
2600 *     holding that hostname. (If we didn't get our address by resolving a
2601 *     hostname, set *<b>hostname_out</b> to NULL.)
2602 *
2603 * XXXX ipv6
2604 */
2605int
2606resolve_my_address(int warn_severity, const or_options_t *options,
2607                   uint32_t *addr_out,
2608                   const char **method_out, char **hostname_out)
2609{
2610  struct in_addr in;
2611  uint32_t addr; /* host order */
2612  char hostname[256];
2613  const char *method_used;
2614  const char *hostname_used;
2615  int explicit_ip=1;
2616  int explicit_hostname=1;
2617  int from_interface=0;
2618  char *addr_string = NULL;
2619  const char *address = options->Address;
2620  int notice_severity = warn_severity <= LOG_NOTICE ?
2621                          LOG_NOTICE : warn_severity;
2622
2623  tor_addr_t myaddr;
2624  tor_assert(addr_out);
2625
2626  /*
2627   * Step one: Fill in 'hostname' to be our best guess.
2628   */
2629
2630  if (address && *address) {
2631    strlcpy(hostname, address, sizeof(hostname));
2632  } else { /* then we need to guess our address */
2633    explicit_ip = 0; /* it's implicit */
2634    explicit_hostname = 0; /* it's implicit */
2635
2636    if (tor_gethostname(hostname, sizeof(hostname)) < 0) {
2637      log_fn(warn_severity, LD_NET,"Error obtaining local hostname");
2638      return -1;
2639    }
2640    log_debug(LD_CONFIG, "Guessed local host name as '%s'", hostname);
2641  }
2642
2643  /*
2644   * Step two: Now that we know 'hostname', parse it or resolve it. If
2645   * it doesn't parse or resolve, look at the interface address. Set 'addr'
2646   * to be our (host-order) 32-bit answer.
2647   */
2648
2649  if (tor_inet_aton(hostname, &in) == 0) {
2650    /* then we have to resolve it */
2651    explicit_ip = 0;
2652    if (tor_lookup_hostname(hostname, &addr)) { /* failed to resolve */
2653      uint32_t interface_ip; /* host order */
2654
2655      if (explicit_hostname) {
2656        log_fn(warn_severity, LD_CONFIG,
2657               "Could not resolve local Address '%s'. Failing.", hostname);
2658        return -1;
2659      }
2660      log_fn(notice_severity, LD_CONFIG,
2661             "Could not resolve guessed local hostname '%s'. "
2662             "Trying something else.", hostname);
2663      if (get_interface_address(warn_severity, &interface_ip)) {
2664        log_fn(warn_severity, LD_CONFIG,
2665               "Could not get local interface IP address. Failing.");
2666        return -1;
2667      }
2668      from_interface = 1;
2669      addr = interface_ip;
2670      log_fn(notice_severity, LD_CONFIG, "Learned IP address '%s' for "
2671             "local interface. Using that.", fmt_addr32(addr));
2672      strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2673    } else { /* resolved hostname into addr */
2674      tor_addr_from_ipv4h(&myaddr, addr);
2675
2676      if (!explicit_hostname &&
2677          tor_addr_is_internal(&myaddr, 0)) {
2678        tor_addr_t interface_ip;
2679
2680        log_fn(notice_severity, LD_CONFIG, "Guessed local hostname '%s' "
2681               "resolves to a private IP address (%s). Trying something "
2682               "else.", hostname, fmt_addr32(addr));
2683
2684        if (get_interface_address6(warn_severity, AF_INET, &interface_ip)<0) {
2685          log_fn(warn_severity, LD_CONFIG,
2686                 "Could not get local interface IP address. Too bad.");
2687        } else if (tor_addr_is_internal(&interface_ip, 0)) {
2688          log_fn(notice_severity, LD_CONFIG,
2689                 "Interface IP address '%s' is a private address too. "
2690                 "Ignoring.", fmt_addr(&interface_ip));
2691        } else {
2692          from_interface = 1;
2693          addr = tor_addr_to_ipv4h(&interface_ip);
2694          log_fn(notice_severity, LD_CONFIG,
2695                 "Learned IP address '%s' for local interface."
2696                 " Using that.", fmt_addr32(addr));
2697          strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2698        }
2699      }
2700    }
2701  } else {
2702    addr = ntohl(in.s_addr); /* set addr so that addr_string is not
2703                              * illformed */
2704  }
2705
2706  /*
2707   * Step three: Check whether 'addr' is an internal IP address, and error
2708   * out if it is and we don't want that.
2709   */
2710
2711  tor_addr_from_ipv4h(&myaddr,addr);
2712
2713  addr_string = tor_dup_ip(addr);
2714  if (tor_addr_is_internal(&myaddr, 0)) {
2715    /* make sure we're ok with publishing an internal IP */
2716    if (using_default_dir_authorities(options)) {
2717      /* if they are using the default authorities, disallow internal IPs
2718       * always. */
2719      log_fn(warn_severity, LD_CONFIG,
2720             "Address '%s' resolves to private IP address '%s'. "
2721             "Tor servers that use the default DirAuthorities must have "
2722             "public IP addresses.", hostname, addr_string);
2723      tor_free(addr_string);
2724      return -1;
2725    }
2726    if (!explicit_ip) {
2727      /* even if they've set their own authorities, require an explicit IP if
2728       * they're using an internal address. */
2729      log_fn(warn_severity, LD_CONFIG, "Address '%s' resolves to private "
2730             "IP address '%s'. Please set the Address config option to be "
2731             "the IP address you want to use.", hostname, addr_string);
2732      tor_free(addr_string);
2733      return -1;
2734    }
2735  }
2736
2737  /*
2738   * Step four: We have a winner! 'addr' is our answer for sure, and
2739   * 'addr_string' is its string form. Fill out the various fields to
2740   * say how we decided it.
2741   */
2742
2743  log_debug(LD_CONFIG, "Resolved Address to '%s'.", addr_string);
2744
2745  if (explicit_ip) {
2746    method_used = "CONFIGURED";
2747    hostname_used = NULL;
2748  } else if (explicit_hostname) {
2749    method_used = "RESOLVED";
2750    hostname_used = hostname;
2751  } else if (from_interface) {
2752    method_used = "INTERFACE";
2753    hostname_used = NULL;
2754  } else {
2755    method_used = "GETHOSTNAME";
2756    hostname_used = hostname;
2757  }
2758
2759  *addr_out = addr;
2760  if (method_out)
2761    *method_out = method_used;
2762  if (hostname_out)
2763    *hostname_out = hostname_used ? tor_strdup(hostname_used) : NULL;
2764
2765  /*
2766   * Step five: Check if the answer has changed since last time (or if
2767   * there was no last time), and if so call various functions to keep
2768   * us up-to-date.
2769   */
2770
2771  if (last_resolved_addr && last_resolved_addr != *addr_out) {
2772    /* Leave this as a notice, regardless of the requested severity,
2773     * at least until dynamic IP address support becomes bulletproof. */
2774    log_notice(LD_NET,
2775               "Your IP address seems to have changed to %s "
2776               "(METHOD=%s%s%s). Updating.",
2777               addr_string, method_used,
2778               hostname_used ? " HOSTNAME=" : "",
2779               hostname_used ? hostname_used : "");
2780    ip_address_changed(0);
2781  }
2782
2783  if (last_resolved_addr != *addr_out) {
2784    control_event_server_status(LOG_NOTICE,
2785                                "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s%s%s",
2786                                addr_string, method_used,
2787                                hostname_used ? " HOSTNAME=" : "",
2788                                hostname_used ? hostname_used : "");
2789  }
2790  last_resolved_addr = *addr_out;
2791
2792  /*
2793   * And finally, clean up and return success.
2794   */
2795
2796  tor_free(addr_string);
2797  return 0;
2798}
2799
2800/** Return true iff <b>addr</b> is judged to be on the same network as us, or
2801 * on a private network.
2802 */
2803MOCK_IMPL(int,
2804is_local_addr, (const tor_addr_t *addr))
2805{
2806  if (tor_addr_is_internal(addr, 0))
2807    return 1;
2808  /* Check whether ip is on the same /24 as we are. */
2809  if (get_options()->EnforceDistinctSubnets == 0)
2810    return 0;
2811  if (tor_addr_family(addr) == AF_INET) {
2812    uint32_t ip = tor_addr_to_ipv4h(addr);
2813
2814    /* It's possible that this next check will hit before the first time
2815     * resolve_my_address actually succeeds.  (For clients, it is likely that
2816     * resolve_my_address will never be called at all).  In those cases,
2817     * last_resolved_addr will be 0, and so checking to see whether ip is on
2818     * the same /24 as last_resolved_addr will be the same as checking whether
2819     * it was on net 0, which is already done by tor_addr_is_internal.
2820     */
2821    if ((last_resolved_addr & (uint32_t)0xffffff00ul)
2822        == (ip & (uint32_t)0xffffff00ul))
2823      return 1;
2824  }
2825  return 0;
2826}
2827
2828/** Return a new empty or_options_t.  Used for testing. */
2829or_options_t *
2830options_new(void)
2831{
2832  return config_new(&options_format);
2833}
2834
2835/** Set <b>options</b> to hold reasonable defaults for most options.
2836 * Each option defaults to zero. */
2837void
2838options_init(or_options_t *options)
2839{
2840  config_init(&options_format, options);
2841}
2842
2843/** Return a string containing a possible configuration file that would give
2844 * the configuration in <b>options</b>.  If <b>minimal</b> is true, do not
2845 * include options that are the same as Tor's defaults.
2846 */
2847char *
2848options_dump(const or_options_t *options, int how_to_dump)
2849{
2850  const or_options_t *use_defaults;
2851  int minimal;
2852  switch (how_to_dump) {
2853    case OPTIONS_DUMP_MINIMAL:
2854      use_defaults = global_default_options;
2855      minimal = 1;
2856      break;
2857    case OPTIONS_DUMP_DEFAULTS:
2858      use_defaults = NULL;
2859      minimal = 1;
2860      break;
2861    case OPTIONS_DUMP_ALL:
2862      use_defaults = NULL;
2863      minimal = 0;
2864      break;
2865    default:
2866      log_warn(LD_BUG, "Bogus value for how_to_dump==%d", how_to_dump);
2867      return NULL;
2868  }
2869
2870  return config_dump(&options_format, use_defaults, options, minimal, 0);
2871}
2872
2873/** Return 0 if every element of sl is a string holding a decimal
2874 * representation of a port number, or if sl is NULL.
2875 * Otherwise set *msg and return -1. */
2876static int
2877validate_ports_csv(smartlist_t *sl, const char *name, char **msg)
2878{
2879  int i;
2880  tor_assert(name);
2881
2882  if (!sl)
2883    return 0;
2884
2885  SMARTLIST_FOREACH(sl, const char *, cp,
2886  {
2887    i = atoi(cp);
2888    if (i < 1 || i > 65535) {
2889      tor_asprintf(msg, "Port '%s' out of range in %s", cp, name);
2890      return -1;
2891    }
2892  });
2893  return 0;
2894}
2895
2896/** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
2897 * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
2898 * Else return 0.
2899 */
2900static int
2901ensure_bandwidth_cap(uint64_t *value, const char *desc, char **msg)
2902{
2903  if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2904    /* This handles an understandable special case where somebody says "2gb"
2905     * whereas our actual maximum is 2gb-1 (INT_MAX) */
2906    --*value;
2907  }
2908  if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
2909    tor_asprintf(msg, "%s ("U64_FORMAT") must be at most %d",
2910                 desc, U64_PRINTF_ARG(*value),
2911                 ROUTER_MAX_DECLARED_BANDWIDTH);
2912    return -1;
2913  }
2914  return 0;
2915}
2916
2917/** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
2918 * and write it to <b>options</b>-\>PublishServerDescriptor_. Treat "1"
2919 * as "v3" unless BridgeRelay is 1, in which case treat it as "bridge".
2920 * Treat "0" as "".
2921 * Return 0 on success or -1 if not a recognized authority type (in which
2922 * case the value of PublishServerDescriptor_ is undefined). */
2923static int
2924compute_publishserverdescriptor(or_options_t *options)
2925{
2926  smartlist_t *list = options->PublishServerDescriptor;
2927  dirinfo_type_t *auth = &options->PublishServerDescriptor_;
2928  *auth = NO_DIRINFO;
2929  if (!list) /* empty list, answer is none */
2930    return 0;
2931  SMARTLIST_FOREACH_BEGIN(list, const char *, string) {
2932    if (!strcasecmp(string, "v1"))
2933      log_warn(LD_CONFIG, "PublishServerDescriptor v1 has no effect, because "
2934                          "there are no v1 directory authorities anymore.");
2935    else if (!strcmp(string, "1"))
2936      if (options->BridgeRelay)
2937        *auth |= BRIDGE_DIRINFO;
2938      else
2939        *auth |= V3_DIRINFO;
2940    else if (!strcasecmp(string, "v2"))
2941      log_warn(LD_CONFIG, "PublishServerDescriptor v2 has no effect, because "
2942                          "there are no v2 directory authorities anymore.");
2943    else if (!strcasecmp(string, "v3"))
2944      *auth |= V3_DIRINFO;
2945    else if (!strcasecmp(string, "bridge"))
2946      *auth |= BRIDGE_DIRINFO;
2947    else if (!strcasecmp(string, "hidserv"))
2948      log_warn(LD_CONFIG,
2949               "PublishServerDescriptor hidserv is invalid. See "
2950               "PublishHidServDescriptors.");
2951    else if (!strcasecmp(string, "") || !strcmp(string, "0"))
2952      /* no authority */;
2953    else
2954      return -1;
2955  } SMARTLIST_FOREACH_END(string);
2956  return 0;
2957}
2958
2959/** Lowest allowable value for RendPostPeriod; if this is too low, hidden
2960 * services can overload the directory system. */
2961#define MIN_REND_POST_PERIOD (10*60)
2962#define MIN_REND_POST_PERIOD_TESTING (5)
2963
2964/** Highest allowable value for CircuitsAvailableTimeout.
2965 * If this is too large, client connections will stay open for too long,
2966 * incurring extra padding overhead. */
2967#define MAX_CIRCS_AVAILABLE_TIME (24*60*60)
2968
2969/** Highest allowable value for RendPostPeriod. */
2970#define MAX_DIR_PERIOD ((7*24*60*60)/2)
2971
2972/** Lowest allowable value for MaxCircuitDirtiness; if this is too low, Tor
2973 * will generate too many circuits and potentially overload the network. */
2974#define MIN_MAX_CIRCUIT_DIRTINESS 10
2975
2976/** Highest allowable value for MaxCircuitDirtiness: prevents time_t
2977 * overflows. */
2978#define MAX_MAX_CIRCUIT_DIRTINESS (30*24*60*60)
2979
2980/** Lowest allowable value for CircuitStreamTimeout; if this is too low, Tor
2981 * will generate too many circuits and potentially overload the network. */
2982#define MIN_CIRCUIT_STREAM_TIMEOUT 10
2983
2984/** Lowest recommended value for CircuitBuildTimeout; if it is set too low
2985 * and LearnCircuitBuildTimeout is off, the failure rate for circuit
2986 * construction may be very high.  In that case, if it is set below this
2987 * threshold emit a warning.
2988 * */
2989#define RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT (10)
2990
2991static int
2992options_validate_cb(void *old_options, void *options, void *default_options,
2993                    int from_setconf, char **msg)
2994{
2995  in_option_validation = 1;
2996  int rv = options_validate(old_options, options, default_options,
2997                          from_setconf, msg);
2998  in_option_validation = 0;
2999  return rv;
3000}
3001
3002#define REJECT(arg) \
3003  STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
3004#if defined(__GNUC__) && __GNUC__ <= 3
3005#define COMPLAIN(args...) \
3006  STMT_BEGIN log_warn(LD_CONFIG, args); STMT_END
3007#else
3008#define COMPLAIN(args, ...)                                     \
3009  STMT_BEGIN log_warn(LD_CONFIG, args, ##__VA_ARGS__); STMT_END
3010#endif /* defined(__GNUC__) && __GNUC__ <= 3 */
3011
3012/** Log a warning message iff <b>filepath</b> is not absolute.
3013 * Warning message must contain option name <b>option</b> and
3014 * an absolute path that <b>filepath</b> will resolve to.
3015 *
3016 * In case <b>filepath</b> is absolute, do nothing.
3017 *
3018 * Return 1 if there were relative paths; 0 otherwise.
3019 */
3020static int
3021warn_if_option_path_is_relative(const char *option,
3022                                char *filepath)
3023{
3024  if (filepath && path_is_relative(filepath)) {
3025    char *abs_path = make_path_absolute(filepath);
3026    COMPLAIN("Path for %s (%s) is relative and will resolve to %s."
3027             " Is this what you wanted?", option, filepath, abs_path);
3028    tor_free(abs_path);
3029    return 1;
3030  }
3031  return 0;
3032}
3033
3034/** Scan <b>options</b> for occurances of relative file/directory
3035 * path and log a warning whenever it is found.
3036 *
3037 * Return 1 if there were relative paths; 0 otherwise.
3038 */
3039static int
3040warn_about_relative_paths(or_options_t *options)
3041{
3042  tor_assert(options);
3043  int n = 0;
3044
3045  n += warn_if_option_path_is_relative("CookieAuthFile",
3046                                       options->CookieAuthFile);
3047  n += warn_if_option_path_is_relative("ExtORPortCookieAuthFile",
3048                                       options->ExtORPortCookieAuthFile);
3049  n += warn_if_option_path_is_relative("DirPortFrontPage",
3050                                       options->DirPortFrontPage);
3051  n += warn_if_option_path_is_relative("V3BandwidthsFile",
3052                                       options->V3BandwidthsFile);
3053  n += warn_if_option_path_is_relative("ControlPortWriteToFile",
3054                                       options->ControlPortWriteToFile);
3055  n += warn_if_option_path_is_relative("GeoIPFile",options->GeoIPFile);
3056  n += warn_if_option_path_is_relative("GeoIPv6File",options->GeoIPv6File);
3057  n += warn_if_option_path_is_relative("Log",options->DebugLogFile);
3058  n += warn_if_option_path_is_relative("AccelDir",options->AccelDir);
3059  n += warn_if_option_path_is_relative("DataDirectory",options->DataDirectory);
3060  n += warn_if_option_path_is_relative("PidFile",options->PidFile);
3061
3062  for (config_line_t *hs_line = options->RendConfigLines; hs_line;
3063       hs_line = hs_line->next) {
3064    if (!strcasecmp(hs_line->key, "HiddenServiceDir"))
3065      n += warn_if_option_path_is_relative("HiddenServiceDir",hs_line->value);
3066  }
3067  return n != 0;
3068}
3069
3070/* Validate options related to the scheduler. From the Schedulers list, the
3071 * SchedulerTypes_ list is created with int values so once we select the
3072 * scheduler, which can happen anytime at runtime, we don't have to parse
3073 * strings and thus be quick.
3074 *
3075 * Return 0 on success else -1 and msg is set with an error message. */
3076static int
3077options_validate_scheduler(or_options_t *options, char **msg)
3078{
3079  tor_assert(options);
3080  tor_assert(msg);
3081
3082  if (!options->Schedulers || smartlist_len(options->Schedulers) == 0) {
3083    REJECT("Empty Schedulers list. Either remove the option so the defaults "
3084           "can be used or set at least one value.");
3085  }
3086  /* Ok, we do have scheduler types, validate them. */
3087  options->SchedulerTypes_ = smartlist_new();
3088  SMARTLIST_FOREACH_BEGIN(options->Schedulers, const char *, type) {
3089    int *sched_type;
3090    if (!strcasecmp("KISTLite", type)) {
3091      sched_type = tor_malloc_zero(sizeof(int));
3092      *sched_type = SCHEDULER_KIST_LITE;
3093      smartlist_add(options->SchedulerTypes_, sched_type);
3094    } else if (!strcasecmp("KIST", type)) {
3095      sched_type = tor_malloc_zero(sizeof(int));
3096      *sched_type = SCHEDULER_KIST;
3097      smartlist_add(options->SchedulerTypes_, sched_type);
3098    } else if (!strcasecmp("Vanilla", type)) {
3099      sched_type = tor_malloc_zero(sizeof(int));
3100      *sched_type = SCHEDULER_VANILLA;
3101      smartlist_add(options->SchedulerTypes_, sched_type);
3102    } else {
3103      tor_asprintf(msg, "Unknown type %s in option Schedulers. "
3104                        "Possible values are KIST, KISTLite and Vanilla.",
3105                   escaped(type));
3106      return -1;
3107    }
3108  } SMARTLIST_FOREACH_END(type);
3109
3110  if (options->KISTSockBufSizeFactor < 0) {
3111    REJECT("KISTSockBufSizeFactor must be at least 0");
3112  }
3113
3114  /* Don't need to validate that the Interval is less than anything because
3115   * zero is valid and all negative values are valid. */
3116  if (options->KISTSchedRunInterval > KIST_SCHED_RUN_INTERVAL_MAX) {
3117    tor_asprintf(msg, "KISTSchedRunInterval must not be more than %d (ms)",
3118                 KIST_SCHED_RUN_INTERVAL_MAX);
3119    return -1;
3120  }
3121
3122  return 0;
3123}
3124
3125/* Validate options related to single onion services.
3126 * Modifies some options that are incompatible with single onion services.
3127 * On failure returns -1, and sets *msg to an error string.
3128 * Returns 0 on success. */
3129STATIC int
3130options_validate_single_onion(or_options_t *options, char **msg)
3131{
3132  /* The two single onion service options must have matching values. */
3133  if (options->HiddenServiceSingleHopMode &&
3134      !options->HiddenServiceNonAnonymousMode) {
3135    REJECT("HiddenServiceSingleHopMode does not provide any server anonymity. "
3136           "It must be used with HiddenServiceNonAnonymousMode set to 1.");
3137  }
3138  if (options->HiddenServiceNonAnonymousMode &&
3139      !options->HiddenServiceSingleHopMode) {
3140    REJECT("HiddenServiceNonAnonymousMode does not provide any server "
3141           "anonymity. It must be used with HiddenServiceSingleHopMode set to "
3142           "1.");
3143  }
3144
3145  /* Now that we've checked that the two options are consistent, we can safely
3146   * call the rend_service_* functions that abstract these options. */
3147
3148  /* If you run an anonymous client with an active Single Onion service, the
3149   * client loses anonymity. */
3150  const int client_port_set = (options->SocksPort_set ||
3151                               options->TransPort_set ||
3152                               options->NATDPort_set ||
3153                               options->DNSPort_set ||
3154                               options->HTTPTunnelPort_set);
3155  if (rend_service_non_anonymous_mode_enabled(options) && client_port_set &&
3156      !options->Tor2webMode) {
3157    REJECT("HiddenServiceNonAnonymousMode is incompatible with using Tor as "
3158           "an anonymous client. Please set Socks/Trans/NATD/DNSPort to 0, or "
3159           "revert HiddenServiceNonAnonymousMode to 0.");
3160  }
3161
3162  /* If you run a hidden service in non-anonymous mode, the hidden service
3163   * loses anonymity, even if SOCKSPort / Tor2web mode isn't used. */
3164  if (!rend_service_non_anonymous_mode_enabled(options) &&
3165      options->RendConfigLines && options->Tor2webMode) {
3166    REJECT("Non-anonymous (Tor2web) mode is incompatible with using Tor as a "
3167           "hidden service. Please remove all HiddenServiceDir lines, or use "
3168           "a version of tor compiled without --enable-tor2web-mode, or use "
3169           "HiddenServiceNonAnonymousMode.");
3170  }
3171
3172  if (rend_service_allow_non_anonymous_connection(options)
3173      && options->UseEntryGuards) {
3174    /* Single Onion services only use entry guards when uploading descriptors;
3175     * all other connections are one-hop. Further, Single Onions causes the
3176     * hidden service code to do things which break the path bias
3177     * detector, and it's far easier to turn off entry guards (and
3178     * thus the path bias detector with it) than to figure out how to
3179     * make path bias compatible with single onions.
3180     */
3181    log_notice(LD_CONFIG,
3182               "HiddenServiceSingleHopMode is enabled; disabling "
3183               "UseEntryGuards.");
3184    options->UseEntryGuards = 0;
3185  }
3186
3187  return 0;
3188}
3189
3190/** Return 0 if every setting in <b>options</b> is reasonable, is a
3191 * permissible transition from <b>old_options</b>, and none of the
3192 * testing-only settings differ from <b>default_options</b> unless in
3193 * testing mode.  Else return -1.  Should have no side effects, except for
3194 * normalizing the contents of <b>options</b>.
3195 *
3196 * On error, tor_strdup an error explanation into *<b>msg</b>.
3197 *
3198 * XXX
3199 * If <b>from_setconf</b>, we were called by the controller, and our
3200 * Log line should stay empty. If it's 0, then give us a default log
3201 * if there are no logs defined.
3202 */
3203STATIC int
3204options_validate(or_options_t *old_options, or_options_t *options,
3205                 or_options_t *default_options, int from_setconf, char **msg)
3206{
3207  int i;
3208  config_line_t *cl;
3209  const char *uname = get_uname();
3210  int n_ports=0;
3211  int world_writable_control_socket=0;
3212
3213  tor_assert(msg);
3214  *msg = NULL;
3215
3216  if (parse_ports(options, 1, msg, &n_ports,
3217                  &world_writable_control_socket) < 0)
3218    return -1;
3219
3220  /* Set UseEntryGuards from the configured value, before we check it below.
3221   * We change UseEntryGuards when it's incompatible with other options,
3222   * but leave UseEntryGuards_option with the original value.
3223   * Always use the value of UseEntryGuards, not UseEntryGuards_option. */
3224  options->UseEntryGuards = options->UseEntryGuards_option;
3225
3226  if (warn_about_relative_paths(options) && options->RunAsDaemon) {
3227    REJECT("You have specified at least one relative path (see above) "
3228           "with the RunAsDaemon option. RunAsDaemon is not compatible "
3229           "with relative paths.");
3230  }
3231
3232  if (server_mode(options) &&
3233      (!strcmpstart(uname, "Windows 95") ||
3234       !strcmpstart(uname, "Windows 98") ||
3235       !strcmpstart(uname, "Windows Me"))) {
3236    log_warn(LD_CONFIG, "Tor is running as a server, but you are "
3237        "running %s; this probably won't work. See "
3238        "https://www.torproject.org/docs/faq.html#BestOSForRelay "
3239        "for details.", uname);
3240  }
3241
3242  if (parse_outbound_addresses(options, 1, msg) < 0)
3243    return -1;
3244
3245  if (validate_data_directories(options)<0)
3246    REJECT("Invalid DataDirectory");
3247
3248  if (options->Nickname == NULL) {
3249    if (server_mode(options)) {
3250      options->Nickname = tor_strdup(UNNAMED_ROUTER_NICKNAME);
3251    }
3252  } else {
3253    if (!is_legal_nickname(options->Nickname)) {
3254      tor_asprintf(msg,
3255          "Nickname '%s', nicknames must be between 1 and 19 characters "
3256          "inclusive, and must contain only the characters [a-zA-Z0-9].",
3257          options->Nickname);
3258      return -1;
3259    }
3260  }
3261
3262  if (server_mode(options) && !options->ContactInfo)
3263    log_notice(LD_CONFIG, "Your ContactInfo config option is not set. "
3264        "Please consider setting it, so we can contact you if your server is "
3265        "misconfigured or something else goes wrong.");
3266
3267  /* Special case on first boot if no Log options are given. */
3268  if (!options->Logs && !options->RunAsDaemon && !from_setconf) {
3269    if (quiet_level == 0)
3270      config_line_append(&options->Logs, "Log", "notice stdout");
3271    else if (quiet_level == 1)
3272      config_line_append(&options->Logs, "Log", "warn stdout");
3273  }
3274
3275  /* Validate the tor_log(s) */
3276  if (options_init_logs(old_options, options, 1)<0)
3277    REJECT("Failed to validate Log options. See logs for details.");
3278
3279  if (authdir_mode(options)) {
3280    /* confirm that our address isn't broken, so we can complain now */
3281    uint32_t tmp;
3282    if (resolve_my_address(LOG_WARN, options, &tmp, NULL, NULL) < 0)
3283      REJECT("Failed to resolve/guess local address. See logs for details.");
3284  }
3285
3286  if (server_mode(options) && options->RendConfigLines)
3287    log_warn(LD_CONFIG,
3288        "Tor is currently configured as a relay and a hidden service. "
3289        "That's not very secure: you should probably run your hidden service "
3290        "in a separate Tor process, at least -- see "
3291        "https://trac.torproject.org/8742");
3292
3293  /* XXXX require that the only port not be DirPort? */
3294  /* XXXX require that at least one port be listened-upon. */
3295  if (n_ports == 0 && !options->RendConfigLines)
3296    log_warn(LD_CONFIG,
3297        "SocksPort, TransPort, NATDPort, DNSPort, and ORPort are all "
3298        "undefined, and there aren't any hidden services configured.  "
3299        "Tor will still run, but probably won't do anything.");
3300
3301  options->TransProxyType_parsed = TPT_DEFAULT;
3302#ifdef USE_TRANSPARENT
3303  if (options->TransProxyType) {
3304    if (!strcasecmp(options->TransProxyType, "default")) {
3305      options->TransProxyType_parsed = TPT_DEFAULT;
3306    } else if (!strcasecmp(options->TransProxyType, "pf-divert")) {
3307#if !defined(OpenBSD) && !defined( DARWIN )
3308      /* Later versions of OS X have pf */
3309      REJECT("pf-divert is a OpenBSD-specific "
3310             "and OS X/Darwin-specific feature.");
3311#else
3312      options->TransProxyType_parsed = TPT_PF_DIVERT;
3313#endif /* !defined(OpenBSD) && !defined( DARWIN ) */
3314    } else if (!strcasecmp(options->TransProxyType, "tproxy")) {
3315#if !defined(__linux__)
3316      REJECT("TPROXY is a Linux-specific feature.");
3317#else
3318      options->TransProxyType_parsed = TPT_TPROXY;
3319#endif
3320    } else if (!strcasecmp(options->TransProxyType, "ipfw")) {
3321#ifndef KERNEL_MAY_SUPPORT_IPFW
3322      /* Earlier versions of OS X have ipfw */
3323      REJECT("ipfw is a FreeBSD-specific "
3324             "and OS X/Darwin-specific feature.");
3325#else
3326      options->TransProxyType_parsed = TPT_IPFW;
3327#endif /* !defined(KERNEL_MAY_SUPPORT_IPFW) */
3328    } else {
3329      REJECT("Unrecognized value for TransProxyType");
3330    }
3331
3332    if (strcasecmp(options->TransProxyType, "default") &&
3333        !options->TransPort_set) {
3334      REJECT("Cannot use TransProxyType without any valid TransPort.");
3335    }
3336  }
3337#else /* !(defined(USE_TRANSPARENT)) */
3338  if (options->TransPort_set)
3339    REJECT("TransPort is disabled in this build.");
3340#endif /* defined(USE_TRANSPARENT) */
3341
3342  if (options->TokenBucketRefillInterval <= 0
3343      || options->TokenBucketRefillInterval > 1000) {
3344    REJECT("TokenBucketRefillInterval must be between 1 and 1000 inclusive.");
3345  }
3346
3347  if (options->ExcludeExitNodes || options->ExcludeNodes) {
3348    options->ExcludeExitNodesUnion_ = routerset_new();
3349    routerset_union(options->ExcludeExitNodesUnion_,options->ExcludeExitNodes);
3350    routerset_union(options->ExcludeExitNodesUnion_,options->ExcludeNodes);
3351  }
3352
3353  if (options->NodeFamilies) {
3354    options->NodeFamilySets = smartlist_new();
3355    for (cl = options->NodeFamilies; cl; cl = cl->next) {
3356      routerset_t *rs = routerset_new();
3357      if (routerset_parse(rs, cl->value, cl->key) == 0) {
3358        smartlist_add(options->NodeFamilySets, rs);
3359      } else {
3360        routerset_free(rs);
3361      }
3362    }
3363  }
3364
3365  if (options->ExcludeNodes && options->StrictNodes) {
3366    COMPLAIN("You have asked to exclude certain relays from all positions "
3367             "in your circuits. Expect hidden services and other Tor "
3368             "features to be broken in unpredictable ways.");
3369  }
3370
3371  for (cl = options->RecommendedPackages; cl; cl = cl->next) {
3372    if (! validate_recommended_package_line(cl->value)) {
3373      log_warn(LD_CONFIG, "Invalid RecommendedPackage line %s will be ignored",
3374               escaped(cl->value));
3375    }
3376  }
3377
3378  if (options->AuthoritativeDir) {
3379    if (!options->ContactInfo && !options->TestingTorNetwork)
3380      REJECT("Authoritative directory servers must set ContactInfo");
3381    if (!options->RecommendedClientVersions)
3382      options->RecommendedClientVersions =
3383        config_lines_dup(options->RecommendedVersions);
3384    if (!options->RecommendedServerVersions)
3385      options->RecommendedServerVersions =
3386        config_lines_dup(options->RecommendedVersions);
3387    if (options->VersioningAuthoritativeDir &&
3388        (!options->RecommendedClientVersions ||
3389         !options->RecommendedServerVersions))
3390      REJECT("Versioning authoritative dir servers must set "
3391             "Recommended*Versions.");
3392    if (options->UseEntryGuards) {
3393      log_info(LD_CONFIG, "Authoritative directory servers can't set "
3394               "UseEntryGuards. Disabling.");
3395      options->UseEntryGuards = 0;
3396    }
3397    if (!options->DownloadExtraInfo && authdir_mode_v3(options)) {
3398      log_info(LD_CONFIG, "Authoritative directories always try to download "
3399               "extra-info documents. Setting DownloadExtraInfo.");
3400      options->DownloadExtraInfo = 1;
3401    }
3402    if (!(options->BridgeAuthoritativeDir ||
3403          options->V3AuthoritativeDir))
3404      REJECT("AuthoritativeDir is set, but none of "
3405             "(Bridge/V3)AuthoritativeDir is set.");
3406    /* If we have a v3bandwidthsfile and it's broken, complain on startup */
3407    if (options->V3BandwidthsFile && !old_options) {
3408      dirserv_read_measured_bandwidths(options->V3BandwidthsFile, NULL);
3409    }
3410    /* same for guardfraction file */
3411    if (options->GuardfractionFile && !old_options) {
3412      dirserv_read_guardfraction_file(options->GuardfractionFile, NULL);
3413    }
3414  }
3415
3416  if (options->AuthoritativeDir && !options->DirPort_set)
3417    REJECT("Running as authoritative directory, but no DirPort set.");
3418
3419  if (options->AuthoritativeDir && !options->ORPort_set)
3420    REJECT("Running as authoritative directory, but no ORPort set.");
3421
3422  if (options->AuthoritativeDir && options->ClientOnly)
3423    REJECT("Running as authoritative directory, but ClientOnly also set.");
3424
3425  if (options->FetchDirInfoExtraEarly && !options->FetchDirInfoEarly)
3426    REJECT("FetchDirInfoExtraEarly requires that you also set "
3427           "FetchDirInfoEarly");
3428
3429  if (options->ConnLimit <= 0) {
3430    tor_asprintf(msg,
3431        "ConnLimit must be greater than 0, but was set to %d",
3432        options->ConnLimit);
3433    return -1;
3434  }
3435
3436  if (options->PathsNeededToBuildCircuits >= 0.0) {
3437    if (options->PathsNeededToBuildCircuits < 0.25) {
3438      log_warn(LD_CONFIG, "PathsNeededToBuildCircuits is too low. Increasing "
3439               "to 0.25");
3440      options->PathsNeededToBuildCircuits = 0.25;
3441    } else if (options->PathsNeededToBuildCircuits > 0.95) {
3442      log_warn(LD_CONFIG, "PathsNeededToBuildCircuits is too high. Decreasing "
3443               "to 0.95");
3444      options->PathsNeededToBuildCircuits = 0.95;
3445    }
3446  }
3447
3448  if (options->MaxClientCircuitsPending <= 0 ||
3449      options->MaxClientCircuitsPending > MAX_MAX_CLIENT_CIRCUITS_PENDING) {
3450    tor_asprintf(msg,
3451                 "MaxClientCircuitsPending must be between 1 and %d, but "
3452                 "was set to %d", MAX_MAX_CLIENT_CIRCUITS_PENDING,
3453                 options->MaxClientCircuitsPending);
3454    return -1;
3455  }
3456
3457  if (validate_ports_csv(options->FirewallPorts, "FirewallPorts", msg) < 0)
3458    return -1;
3459
3460  if (validate_ports_csv(options->LongLivedPorts, "LongLivedPorts", msg) < 0)
3461    return -1;
3462
3463  if (validate_ports_csv(options->RejectPlaintextPorts,
3464                         "RejectPlaintextPorts", msg) < 0)
3465    return -1;
3466
3467  if (validate_ports_csv(options->WarnPlaintextPorts,
3468                         "WarnPlaintextPorts", msg) < 0)
3469    return -1;
3470
3471  if (options->FascistFirewall && !options->ReachableAddresses) {
3472    if (options->FirewallPorts && smartlist_len(options->FirewallPorts)) {
3473      /* We already have firewall ports set, so migrate them to
3474       * ReachableAddresses, which will set ReachableORAddresses and
3475       * ReachableDirAddresses if they aren't set explicitly. */
3476      smartlist_t *instead = smartlist_new();
3477      config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3478      new_line->key = tor_strdup("ReachableAddresses");
3479      /* If we're configured with the old format, we need to prepend some
3480       * open ports. */
3481      SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
3482      {
3483        int p = atoi(portno);
3484        if (p<0) continue;
3485        smartlist_add_asprintf(instead, "*:%d", p);
3486      });
3487      new_line->value = smartlist_join_strings(instead,",",0,NULL);
3488      /* These have been deprecated since 0.1.1.5-alpha-cvs */
3489      log_notice(LD_CONFIG,
3490          "Converting FascistFirewall and FirewallPorts "
3491          "config options to new format: \"ReachableAddresses %s\"",
3492          new_line->value);
3493      options->ReachableAddresses = new_line;
3494      SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
3495      smartlist_free(instead);
3496    } else {
3497      /* We do not have FirewallPorts set, so add 80 to
3498       * ReachableDirAddresses, and 443 to ReachableORAddresses. */
3499      if (!options->ReachableDirAddresses) {
3500        config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3501        new_line->key = tor_strdup("ReachableDirAddresses");
3502        new_line->value = tor_strdup("*:80");
3503        options->ReachableDirAddresses = new_line;
3504        log_notice(LD_CONFIG, "Converting FascistFirewall config option "
3505            "to new format: \"ReachableDirAddresses *:80\"");
3506      }
3507      if (!options->ReachableORAddresses) {
3508        config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3509        new_line->key = tor_strdup("ReachableORAddresses");
3510        new_line->value = tor_strdup("*:443");
3511        options->ReachableORAddresses = new_line;
3512        log_notice(LD_CONFIG, "Converting FascistFirewall config option "
3513            "to new format: \"ReachableORAddresses *:443\"");
3514      }
3515    }
3516  }
3517
3518  /* Terminate Reachable*Addresses with reject *
3519   */
3520  for (i=0; i<3; i++) {
3521    config_line_t **linep =
3522      (i==0) ? &options->ReachableAddresses :
3523        (i==1) ? &options->ReachableORAddresses :
3524                 &options->ReachableDirAddresses;
3525    if (!*linep)
3526      continue;
3527    /* We need to end with a reject *:*, not an implicit accept *:* */
3528    for (;;) {
3529      linep = &((*linep)->next);
3530      if (!*linep) {
3531        *linep = tor_malloc_zero(sizeof(config_line_t));
3532        (*linep)->key = tor_strdup(
3533          (i==0) ?  "ReachableAddresses" :
3534            (i==1) ? "ReachableORAddresses" :
3535                     "ReachableDirAddresses");
3536        (*linep)->value = tor_strdup("reject *:*");
3537        break;
3538      }
3539    }
3540  }
3541
3542  if ((options->ReachableAddresses ||
3543       options->ReachableORAddresses ||
3544       options->ReachableDirAddresses ||
3545       options->ClientUseIPv4 == 0) &&
3546      server_mode(options))
3547    REJECT("Servers must be able to freely connect to the rest "
3548           "of the Internet, so they must not set Reachable*Addresses "
3549           "or FascistFirewall or FirewallPorts or ClientUseIPv4 0.");
3550
3551  if (options->UseBridges &&
3552      server_mode(options))
3553    REJECT("Servers must be able to freely connect to the rest "
3554           "of the Internet, so they must not set UseBridges.");
3555
3556  /* If both of these are set, we'll end up with funny behavior where we
3557   * demand enough entrynodes be up and running else we won't build
3558   * circuits, yet we never actually use them. */
3559  if (options->UseBridges && options->EntryNodes)
3560    REJECT("You cannot set both UseBridges and EntryNodes.");
3561
3562  /* If we have UseBridges as 1 and UseEntryGuards as 0, we end up bypassing
3563   * the use of bridges */
3564  if (options->UseBridges && !options->UseEntryGuards)
3565    REJECT("Setting UseBridges requires also setting UseEntryGuards.");
3566
3567  options->MaxMemInQueues =
3568    compute_real_max_mem_in_queues(options->MaxMemInQueues_raw,
3569                                   server_mode(options));
3570  options->MaxMemInQueues_low_threshold = (options->MaxMemInQueues / 4) * 3;
3571
3572  if (!options->SafeLogging ||
3573      !strcasecmp(options->SafeLogging, "0")) {
3574    options->SafeLogging_ = SAFELOG_SCRUB_NONE;
3575  } else if (!strcasecmp(options->SafeLogging, "relay")) {
3576    options->SafeLogging_ = SAFELOG_SCRUB_RELAY;
3577  } else if (!strcasecmp(options->SafeLogging, "1")) {
3578    options->SafeLogging_ = SAFELOG_SCRUB_ALL;
3579  } else {
3580    tor_asprintf(msg,
3581                     "Unrecognized value '%s' in SafeLogging",
3582                     escaped(options->SafeLogging));
3583    return -1;
3584  }
3585
3586  if (compute_publishserverdescriptor(options) < 0) {
3587    tor_asprintf(msg, "Unrecognized value in PublishServerDescriptor");
3588    return -1;
3589  }
3590
3591  if ((options->BridgeRelay
3592        || options->PublishServerDescriptor_ & BRIDGE_DIRINFO)
3593      && (options->PublishServerDescriptor_ & V3_DIRINFO)) {
3594    REJECT("Bridges are not supposed to publish router descriptors to the "
3595           "directory authorities. Please correct your "
3596           "PublishServerDescriptor line.");
3597  }
3598
3599  if (options->BridgeRelay && options->DirPort_set) {
3600    log_warn(LD_CONFIG, "Can't set a DirPort on a bridge relay; disabling "
3601             "DirPort");
3602    config_free_lines(options->DirPort_lines);
3603    options->DirPort_lines = NULL;
3604    options->DirPort_set = 0;
3605  }
3606
3607  if (server_mode(options) && options->ConnectionPadding != -1) {
3608    REJECT("Relays must use 'auto' for the ConnectionPadding setting.");
3609  }
3610
3611  if (server_mode(options) && options->ReducedConnectionPadding != 0) {
3612    REJECT("Relays cannot set ReducedConnectionPadding. ");
3613  }
3614
3615  if (options->BridgeDistribution) {
3616    if (!options->BridgeRelay) {
3617      REJECT("You set BridgeDistribution, but you didn't set BridgeRelay!");
3618    }
3619    if (check_bridge_distribution_setting(options->BridgeDistribution) < 0) {
3620      REJECT("Invalid BridgeDistribution value.");
3621    }
3622  }
3623
3624  if (options->MinUptimeHidServDirectoryV2 < 0) {
3625    log_warn(LD_CONFIG, "MinUptimeHidServDirectoryV2 option must be at "
3626                        "least 0 seconds. Changing to 0.");
3627    options->MinUptimeHidServDirectoryV2 = 0;
3628  }
3629
3630  const int min_rendpostperiod =
3631    options->TestingTorNetwork ?
3632    MIN_REND_POST_PERIOD_TESTING : MIN_REND_POST_PERIOD;
3633  if (options->RendPostPeriod < min_rendpostperiod) {
3634    log_warn(LD_CONFIG, "RendPostPeriod option is too short; "
3635             "raising to %d seconds.", min_rendpostperiod);
3636    options->RendPostPeriod = min_rendpostperiod;
3637  }
3638
3639  if (options->RendPostPeriod > MAX_DIR_PERIOD) {
3640    log_warn(LD_CONFIG, "RendPostPeriod is too large; clipping to %ds.",
3641             MAX_DIR_PERIOD);
3642    options->RendPostPeriod = MAX_DIR_PERIOD;
3643  }
3644
3645  /* Check the Single Onion Service options */
3646  if (options_validate_single_onion(options, msg) < 0)
3647    return -1;
3648
3649  if (options->CircuitsAvailableTimeout > MAX_CIRCS_AVAILABLE_TIME) {
3650    // options_t is immutable for new code (the above code is older),
3651    // so just make the user fix the value themselves rather than
3652    // silently keep a shadow value lower than what they asked for.
3653    REJECT("CircuitsAvailableTimeout is too large. Max is 24 hours.");
3654  }
3655
3656#ifdef ENABLE_TOR2WEB_MODE
3657  if (options->Tor2webMode && options->UseEntryGuards) {
3658    /* tor2web mode clients do not (and should not) use entry guards
3659     * in any meaningful way.  Further, tor2web mode causes the hidden
3660     * service client code to do things which break the path bias
3661     * detector, and it's far easier to turn off entry guards (and
3662     * thus the path bias detector with it) than to figure out how to
3663     * make a piece of code which cannot possibly help tor2web mode
3664     * users compatible with tor2web mode.
3665     */
3666    log_notice(LD_CONFIG,
3667               "Tor2WebMode is enabled; disabling UseEntryGuards.");
3668    options->UseEntryGuards = 0;
3669  }
3670#endif /* defined(ENABLE_TOR2WEB_MODE) */
3671
3672  if (options->Tor2webRendezvousPoints && !options->Tor2webMode) {
3673    REJECT("Tor2webRendezvousPoints cannot be set without Tor2webMode.");
3674  }
3675
3676  if (options->EntryNodes && !options->UseEntryGuards) {
3677    REJECT("If EntryNodes is set, UseEntryGuards must be enabled.");
3678  }
3679
3680  if (!(options->UseEntryGuards) &&
3681      (options->RendConfigLines != NULL) &&
3682      !rend_service_allow_non_anonymous_connection(options)) {
3683    log_warn(LD_CONFIG,
3684             "UseEntryGuards is disabled, but you have configured one or more "
3685             "hidden services on this Tor instance.  Your hidden services "
3686             "will be very easy to locate using a well-known attack -- see "
3687             "http://freehaven.net/anonbib/#hs-attack06 for details.");
3688  }
3689
3690  if (options->EntryNodes &&
3691      routerset_is_list(options->EntryNodes) &&
3692      (routerset_len(options->EntryNodes) == 1) &&
3693      (options->RendConfigLines != NULL)) {
3694    tor_asprintf(msg,
3695             "You have one single EntryNodes and at least one hidden service "
3696             "configured. This is bad because it's very easy to locate your "
3697             "entry guard which can then lead to the deanonymization of your "
3698             "hidden service -- for more details, see "
3699             "https://trac.torproject.org/projects/tor/ticket/14917. "
3700             "For this reason, the use of one EntryNodes with an hidden "
3701             "service is prohibited until a better solution is found.");
3702    return -1;
3703  }
3704
3705  /* Inform the hidden service operator that pinning EntryNodes can possibly
3706   * be harmful for the service anonymity. */
3707  if (options->EntryNodes &&
3708      routerset_is_list(options->EntryNodes) &&
3709      (options->RendConfigLines != NULL)) {
3710    log_warn(LD_CONFIG,
3711             "EntryNodes is set with multiple entries and at least one "
3712             "hidden service is configured. Pinning entry nodes can possibly "
3713             "be harmful to the service anonymity. Because of this, we "
3714             "recommend you either don't do that or make sure you know what "
3715             "you are doing. For more details, please look at "
3716             "https://trac.torproject.org/projects/tor/ticket/21155.");
3717  }
3718
3719  /* Single Onion Services: non-anonymous hidden services */
3720  if (rend_service_non_anonymous_mode_enabled(options)) {
3721    log_warn(LD_CONFIG,
3722             "HiddenServiceNonAnonymousMode is set. Every hidden service on "
3723             "this tor instance is NON-ANONYMOUS. If "
3724             "the HiddenServiceNonAnonymousMode option is changed, Tor will "
3725             "refuse to launch hidden services from the same directories, to "
3726             "protect your anonymity against config errors. This setting is "
3727             "for experimental use only.");
3728  }
3729
3730  if (!options->LearnCircuitBuildTimeout && options->CircuitBuildTimeout &&
3731      options->CircuitBuildTimeout < RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT) {
3732    log_warn(LD_CONFIG,
3733        "CircuitBuildTimeout is shorter (%d seconds) than the recommended "
3734        "minimum (%d seconds), and LearnCircuitBuildTimeout is disabled.  "
3735        "If tor isn't working, raise this value or enable "
3736        "LearnCircuitBuildTimeout.",
3737        options->CircuitBuildTimeout,
3738        RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT );
3739  } else if (!options->LearnCircuitBuildTimeout &&
3740             !options->CircuitBuildTimeout) {
3741    int severity = LOG_NOTICE;
3742    /* Be a little quieter if we've deliberately disabled
3743     * LearnCircuitBuildTimeout. */
3744    if (circuit_build_times_disabled_(options, 1)) {
3745      severity = LOG_INFO;
3746    }
3747    log_fn(severity, LD_CONFIG, "You disabled LearnCircuitBuildTimeout, but "
3748           "didn't specify a CircuitBuildTimeout. I'll pick a plausible "
3749           "default.");
3750  }
3751
3752  if (options->PathBiasNoticeRate > 1.0) {
3753    tor_asprintf(msg,
3754              "PathBiasNoticeRate is too high. "
3755              "It must be between 0 and 1.0");
3756    return -1;
3757  }
3758  if (options->PathBiasWarnRate > 1.0) {
3759    tor_asprintf(msg,
3760              "PathBiasWarnRate is too high. "
3761              "It must be between 0 and 1.0");
3762    return -1;
3763  }
3764  if (options->PathBiasExtremeRate > 1.0) {
3765    tor_asprintf(msg,
3766              "PathBiasExtremeRate is too high. "
3767              "It must be between 0 and 1.0");
3768    return -1;
3769  }
3770  if (options->PathBiasNoticeUseRate > 1.0) {
3771    tor_asprintf(msg,
3772              "PathBiasNoticeUseRate is too high. "
3773              "It must be between 0 and 1.0");
3774    return -1;
3775  }
3776  if (options->PathBiasExtremeUseRate > 1.0) {
3777    tor_asprintf(msg,
3778              "PathBiasExtremeUseRate is too high. "
3779              "It must be between 0 and 1.0");
3780    return -1;
3781  }
3782
3783  if (options->MaxCircuitDirtiness < MIN_MAX_CIRCUIT_DIRTINESS) {
3784    log_warn(LD_CONFIG, "MaxCircuitDirtiness option is too short; "
3785             "raising to %d seconds.", MIN_MAX_CIRCUIT_DIRTINESS);
3786    options->MaxCircuitDirtiness = MIN_MAX_CIRCUIT_DIRTINESS;
3787  }
3788
3789  if (options->MaxCircuitDirtiness > MAX_MAX_CIRCUIT_DIRTINESS) {
3790    log_warn(LD_CONFIG, "MaxCircuitDirtiness option is too high; "
3791             "setting to %d days.", MAX_MAX_CIRCUIT_DIRTINESS/86400);
3792    options->MaxCircuitDirtiness = MAX_MAX_CIRCUIT_DIRTINESS;
3793  }
3794
3795  if (options->CircuitStreamTimeout &&
3796      options->CircuitStreamTimeout < MIN_CIRCUIT_STREAM_TIMEOUT) {
3797    log_warn(LD_CONFIG, "CircuitStreamTimeout option is too short; "
3798             "raising to %d seconds.", MIN_CIRCUIT_STREAM_TIMEOUT);
3799    options->CircuitStreamTimeout = MIN_CIRCUIT_STREAM_TIMEOUT;
3800  }
3801
3802  if (options->HeartbeatPeriod &&
3803      options->HeartbeatPeriod < MIN_HEARTBEAT_PERIOD) {
3804    log_warn(LD_CONFIG, "HeartbeatPeriod option is too short; "
3805             "raising to %d seconds.", MIN_HEARTBEAT_PERIOD);
3806    options->HeartbeatPeriod = MIN_HEARTBEAT_PERIOD;
3807  }
3808
3809  if (options->KeepalivePeriod < 1)
3810    REJECT("KeepalivePeriod option must be positive.");
3811
3812  if (options->PortForwarding && options->Sandbox) {
3813    REJECT("PortForwarding is not compatible with Sandbox; at most one can "
3814           "be set");
3815  }
3816  if (options->PortForwarding && options->NoExec) {
3817    COMPLAIN("Both PortForwarding and NoExec are set; PortForwarding will "
3818             "be ignored.");
3819  }
3820
3821  if (ensure_bandwidth_cap(&options->BandwidthRate,
3822                           "BandwidthRate", msg) < 0)
3823    return -1;
3824  if (ensure_bandwidth_cap(&options->BandwidthBurst,
3825                           "BandwidthBurst", msg) < 0)
3826    return -1;
3827  if (ensure_bandwidth_cap(&options->MaxAdvertisedBandwidth,
3828                           "MaxAdvertisedBandwidth", msg) < 0)
3829    return -1;
3830  if (ensure_bandwidth_cap(&options->RelayBandwidthRate,
3831                           "RelayBandwidthRate", msg) < 0)
3832    return -1;
3833  if (ensure_bandwidth_cap(&options->RelayBandwidthBurst,
3834                           "RelayBandwidthBurst", msg) < 0)
3835    return -1;
3836  if (ensure_bandwidth_cap(&options->PerConnBWRate,
3837                           "PerConnBWRate", msg) < 0)
3838    return -1;
3839  if (ensure_bandwidth_cap(&options->PerConnBWBurst,
3840                           "PerConnBWBurst", msg) < 0)
3841    return -1;
3842  if (ensure_bandwidth_cap(&options->AuthDirFastGuarantee,
3843                           "AuthDirFastGuarantee", msg) < 0)
3844    return -1;
3845  if (ensure_bandwidth_cap(&options->AuthDirGuardBWGuarantee,
3846                           "AuthDirGuardBWGuarantee", msg) < 0)
3847    return -1;
3848
3849  if (options->RelayBandwidthRate && !options->RelayBandwidthBurst)
3850    options->RelayBandwidthBurst = options->RelayBandwidthRate;
3851  if (options->RelayBandwidthBurst && !options->RelayBandwidthRate)
3852    options->RelayBandwidthRate = options->RelayBandwidthBurst;
3853
3854  if (server_mode(options)) {
3855    const unsigned required_min_bw =
3856      public_server_mode(options) ?
3857       RELAY_REQUIRED_MIN_BANDWIDTH : BRIDGE_REQUIRED_MIN_BANDWIDTH;
3858    const char * const optbridge =
3859      public_server_mode(options) ? "" : "bridge ";
3860    if (options->BandwidthRate < required_min_bw) {
3861      tor_asprintf(msg,
3862                       "BandwidthRate is set to %d bytes/second. "
3863                       "For %sservers, it must be at least %u.",
3864                       (int)options->BandwidthRate, optbridge,
3865                       required_min_bw);
3866      return -1;
3867    } else if (options->MaxAdvertisedBandwidth <
3868               required_min_bw/2) {
3869      tor_asprintf(msg,
3870                       "MaxAdvertisedBandwidth is set to %d bytes/second. "
3871                       "For %sservers, it must be at least %u.",
3872                       (int)options->MaxAdvertisedBandwidth, optbridge,
3873                       required_min_bw/2);
3874      return -1;
3875    }
3876    if (options->RelayBandwidthRate &&
3877      options->RelayBandwidthRate < required_min_bw) {
3878      tor_asprintf(msg,
3879                       "RelayBandwidthRate is set to %d bytes/second. "
3880                       "For %sservers, it must be at least %u.",
3881                       (int)options->RelayBandwidthRate, optbridge,
3882                       required_min_bw);
3883      return -1;
3884    }
3885  }
3886
3887  if (options->RelayBandwidthRate > options->RelayBandwidthBurst)
3888    REJECT("RelayBandwidthBurst must be at least equal "
3889           "to RelayBandwidthRate.");
3890
3891  if (options->BandwidthRate > options->BandwidthBurst)
3892    REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
3893
3894  /* if they set relaybandwidth* really high but left bandwidth*
3895   * at the default, raise the defaults. */
3896  if (options->RelayBandwidthRate > options->BandwidthRate)
3897    options->BandwidthRate = options->RelayBandwidthRate;
3898  if (options->RelayBandwidthBurst > options->BandwidthBurst)
3899    options->BandwidthBurst = options->RelayBandwidthBurst;
3900
3901  if (accounting_parse_options(options, 1)<0)
3902    REJECT("Failed to parse accounting options. See logs for details.");
3903
3904  if (options->AccountingMax) {
3905    if (options->RendConfigLines && server_mode(options)) {
3906      log_warn(LD_CONFIG, "Using accounting with a hidden service and an "
3907               "ORPort is risky: your hidden service(s) and your public "
3908               "address will all turn off at the same time, which may alert "
3909               "observers that they are being run by the same party.");
3910    } else if (config_count_key(options->RendConfigLines,
3911                                "HiddenServiceDir") > 1) {
3912      log_warn(LD_CONFIG, "Using accounting with multiple hidden services is "
3913               "risky: they will all turn off at the same time, which may "
3914               "alert observers that they are being run by the same party.");
3915    }
3916  }
3917
3918  options->AccountingRule = ACCT_MAX;
3919  if (options->AccountingRule_option) {
3920    if (!strcmp(options->AccountingRule_option, "sum"))
3921      options->AccountingRule = ACCT_SUM;
3922    else if (!strcmp(options->AccountingRule_option, "max"))
3923      options->AccountingRule = ACCT_MAX;
3924    else if (!strcmp(options->AccountingRule_option, "in"))
3925      options->AccountingRule = ACCT_IN;
3926    else if (!strcmp(options->AccountingRule_option, "out"))
3927      options->AccountingRule = ACCT_OUT;
3928    else
3929      REJECT("AccountingRule must be 'sum', 'max', 'in', or 'out'");
3930  }
3931
3932  if (options->DirPort_set && !options->DirCache) {
3933    REJECT("DirPort configured but DirCache disabled. DirPort requires "
3934           "DirCache.");
3935  }
3936
3937  if (options->BridgeRelay && !options->DirCache) {
3938    REJECT("We're a bridge but DirCache is disabled. BridgeRelay requires "
3939           "DirCache.");
3940  }
3941
3942  if (server_mode(options)) {
3943    char *dircache_msg = NULL;
3944    if (have_enough_mem_for_dircache(options, 0, &dircache_msg)) {
3945      log_warn(LD_CONFIG, "%s", dircache_msg);
3946      tor_free(dircache_msg);
3947    }
3948  }
3949
3950  if (options->HTTPProxy) { /* parse it now */
3951    if (tor_addr_port_lookup(options->HTTPProxy,
3952                        &options->HTTPProxyAddr, &options->HTTPProxyPort) < 0)
3953      REJECT("HTTPProxy failed to parse or resolve. Please fix.");
3954    if (options->HTTPProxyPort == 0) { /* give it a default */
3955      options->HTTPProxyPort = 80;
3956    }
3957  }
3958
3959  if (options->HTTPProxyAuthenticator) {
3960    if (strlen(options->HTTPProxyAuthenticator) >= 512)
3961      REJECT("HTTPProxyAuthenticator is too long (>= 512 chars).");
3962  }
3963
3964  if (options->HTTPSProxy) { /* parse it now */
3965    if (tor_addr_port_lookup(options->HTTPSProxy,
3966                        &options->HTTPSProxyAddr, &options->HTTPSProxyPort) <0)
3967      REJECT("HTTPSProxy failed to parse or resolve. Please fix.");
3968    if (options->HTTPSProxyPort == 0) { /* give it a default */
3969      options->HTTPSProxyPort = 443;
3970    }
3971  }
3972
3973  if (options->HTTPSProxyAuthenticator) {
3974    if (strlen(options->HTTPSProxyAuthenticator) >= 512)
3975      REJECT("HTTPSProxyAuthenticator is too long (>= 512 chars).");
3976  }
3977
3978  if (options->Socks4Proxy) { /* parse it now */
3979    if (tor_addr_port_lookup(options->Socks4Proxy,
3980                        &options->Socks4ProxyAddr,
3981                        &options->Socks4ProxyPort) <0)
3982      REJECT("Socks4Proxy failed to parse or resolve. Please fix.");
3983    if (options->Socks4ProxyPort == 0) { /* give it a default */
3984      options->Socks4ProxyPort = 1080;
3985    }
3986  }
3987
3988  if (options->Socks5Proxy) { /* parse it now */
3989    if (tor_addr_port_lookup(options->Socks5Proxy,
3990                            &options->Socks5ProxyAddr,
3991                            &options->Socks5ProxyPort) <0)
3992      REJECT("Socks5Proxy failed to parse or resolve. Please fix.");
3993    if (options->Socks5ProxyPort == 0) { /* give it a default */
3994      options->Socks5ProxyPort = 1080;
3995    }
3996  }
3997
3998  /* Check if more than one exclusive proxy type has been enabled. */
3999  if (!!options->Socks4Proxy + !!options->Socks5Proxy +
4000      !!options->HTTPSProxy > 1)
4001    REJECT("You have configured more than one proxy type. "
4002           "(Socks4Proxy|Socks5Proxy|HTTPSProxy)");
4003
4004  /* Check if the proxies will give surprising behavior. */
4005  if (options->HTTPProxy && !(options->Socks4Proxy ||
4006                              options->Socks5Proxy ||
4007                              options->HTTPSProxy)) {
4008    log_warn(LD_CONFIG, "HTTPProxy configured, but no SOCKS proxy or "
4009             "HTTPS proxy configured. Watch out: this configuration will "
4010             "proxy unencrypted directory connections only.");
4011  }
4012
4013  if (options->Socks5ProxyUsername) {
4014    size_t len;
4015
4016    len = strlen(options->Socks5ProxyUsername);
4017    if (len < 1 || len > MAX_SOCKS5_AUTH_FIELD_SIZE)
4018      REJECT("Socks5ProxyUsername must be between 1 and 255 characters.");
4019
4020    if (!options->Socks5ProxyPassword)
4021      REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
4022
4023    len = strlen(options->Socks5ProxyPassword);
4024    if (len < 1 || len > MAX_SOCKS5_AUTH_FIELD_SIZE)
4025      REJECT("Socks5ProxyPassword must be between 1 and 255 characters.");
4026  } else if (options->Socks5ProxyPassword)
4027    REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
4028
4029  if (options->HashedControlPassword) {
4030    smartlist_t *sl = decode_hashed_passwords(options->HashedControlPassword);
4031    if (!sl) {
4032      REJECT("Bad HashedControlPassword: wrong length or bad encoding");
4033    } else {
4034      SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
4035      smartlist_free(sl);
4036    }
4037  }
4038
4039  if (options->HashedControlSessionPassword) {
4040    smartlist_t *sl = decode_hashed_passwords(
4041                                  options->HashedControlSessionPassword);
4042    if (!sl) {
4043      REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
4044    } else {
4045      SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
4046      smartlist_free(sl);
4047    }
4048  }
4049
4050  if (options->OwningControllerProcess) {
4051    const char *validate_pspec_msg = NULL;
4052    if (tor_validate_process_specifier(options->OwningControllerProcess,
4053                                       &validate_pspec_msg)) {
4054      tor_asprintf(msg, "Bad OwningControllerProcess: %s",
4055                   validate_pspec_msg);
4056      return -1;
4057    }
4058  }
4059
4060  if ((options->ControlPort_set || world_writable_control_socket) &&
4061      !options->HashedControlPassword &&
4062      !options->HashedControlSessionPassword &&
4063      !options->CookieAuthentication) {
4064    log_warn(LD_CONFIG, "Control%s is %s, but no authentication method "
4065             "has been configured.  This means that any program on your "
4066             "computer can reconfigure your Tor.  That's bad!  You should "
4067             "upgrade your Tor controller as soon as possible.",
4068             options->ControlPort_set ? "Port" : "Socket",
4069             options->ControlPort_set ? "open" : "world writable");
4070  }
4071
4072  if (options->CookieAuthFileGroupReadable && !options->CookieAuthFile) {
4073    log_warn(LD_CONFIG, "CookieAuthFileGroupReadable is set, but will have "
4074             "no effect: you must specify an explicit CookieAuthFile to "
4075             "have it group-readable.");
4076  }
4077
4078  if (options->MyFamily_lines && options->BridgeRelay) {
4079    log_warn(LD_CONFIG, "Listing a family for a bridge relay is not "
4080             "supported: it can reveal bridge fingerprints to censors. "
4081             "You should also make sure you aren't listing this bridge's "
4082             "fingerprint in any other MyFamily.");
4083  }
4084  if (normalize_nickname_list(&options->MyFamily,
4085                              options->MyFamily_lines, "MyFamily", msg))
4086    return -1;
4087  for (cl = options->NodeFamilies; cl; cl = cl->next) {
4088    routerset_t *rs = routerset_new();
4089    if (routerset_parse(rs, cl->value, cl->key)) {
4090      routerset_free(rs);
4091      return -1;
4092    }
4093    routerset_free(rs);
4094  }
4095
4096  if (validate_addr_policies(options, msg) < 0)
4097    return -1;
4098
4099  /* If FallbackDir is set, we don't UseDefaultFallbackDirs */
4100  if (options->UseDefaultFallbackDirs && options->FallbackDir) {
4101    log_info(LD_CONFIG, "You have set UseDefaultFallbackDirs 1 and "
4102             "FallbackDir(s). Ignoring UseDefaultFallbackDirs, and "
4103             "using the FallbackDir(s) you have set.");
4104  }
4105
4106  if (validate_dir_servers(options, old_options) < 0)
4107    REJECT("Directory authority/fallback line did not parse. See logs "
4108           "for details.");
4109
4110  if (options->UseBridges && !options->Bridges)
4111    REJECT("If you set UseBridges, you must specify at least one bridge.");
4112
4113  for (cl = options->Bridges; cl; cl = cl->next) {
4114      bridge_line_t *bridge_line = parse_bridge_line(cl->value);
4115      if (!bridge_line)
4116        REJECT("Bridge line did not parse. See logs for details.");
4117      bridge_line_free(bridge_line);
4118  }
4119
4120  for (cl = options->ClientTransportPlugin; cl; cl = cl->next) {
4121    if (parse_transport_line(options, cl->value, 1, 0) < 0)
4122      REJECT("Invalid client transport line. See logs for details.");
4123  }
4124
4125  for (cl = options->ServerTransportPlugin; cl; cl = cl->next) {
4126    if (parse_transport_line(options, cl->value, 1, 1) < 0)
4127      REJECT("Invalid server transport line. See logs for details.");
4128  }
4129
4130  if (options->ServerTransportPlugin && !server_mode(options)) {
4131    log_notice(LD_GENERAL, "Tor is not configured as a relay but you specified"
4132               " a ServerTransportPlugin line (%s). The ServerTransportPlugin "
4133               "line will be ignored.",
4134               escaped(options->ServerTransportPlugin->value));
4135  }
4136
4137  for (cl = options->ServerTransportListenAddr; cl; cl = cl->next) {
4138    /** If get_bindaddr_from_transport_listen_line() fails with
4139        'transport' being NULL, it means that something went wrong
4140        while parsing the ServerTransportListenAddr line. */
4141    char *bindaddr = get_bindaddr_from_transport_listen_line(cl->value, NULL);
4142    if (!bindaddr)
4143      REJECT("ServerTransportListenAddr did not parse. See logs for details.");
4144    tor_free(bindaddr);
4145  }
4146
4147  if (options->ServerTransportListenAddr && !options->ServerTransportPlugin) {
4148    log_notice(LD_GENERAL, "You need at least a single managed-proxy to "
4149               "specify a transport listen address. The "
4150               "ServerTransportListenAddr line will be ignored.");
4151  }
4152
4153  for (cl = options->ServerTransportOptions; cl; cl = cl->next) {
4154    /** If get_options_from_transport_options_line() fails with
4155        'transport' being NULL, it means that something went wrong
4156        while parsing the ServerTransportOptions line. */
4157    smartlist_t *options_sl =
4158      get_options_from_transport_options_line(cl->value, NULL);
4159    if (!options_sl)
4160      REJECT("ServerTransportOptions did not parse. See logs for details.");
4161
4162    SMARTLIST_FOREACH(options_sl, char *, cp, tor_free(cp));
4163    smartlist_free(options_sl);
4164  }
4165
4166  if (options->ConstrainedSockets) {
4167    /* If the user wants to constrain socket buffer use, make sure the desired
4168     * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
4169    if (options->ConstrainedSockSize < MIN_CONSTRAINED_TCP_BUFFER ||
4170        options->ConstrainedSockSize > MAX_CONSTRAINED_TCP_BUFFER ||
4171        options->ConstrainedSockSize % 1024) {
4172      tor_asprintf(msg,
4173          "ConstrainedSockSize is invalid.  Must be a value between %d and %d "
4174          "in 1024 byte increments.",
4175          MIN_CONSTRAINED_TCP_BUFFER, MAX_CONSTRAINED_TCP_BUFFER);
4176      return -1;
4177    }
4178    if (options->DirPort_set) {
4179      /* Providing cached directory entries while system TCP buffers are scarce
4180       * will exacerbate the socket errors.  Suggest that this be disabled. */
4181      COMPLAIN("You have requested constrained socket buffers while also "
4182               "serving directory entries via DirPort.  It is strongly "
4183               "suggested that you disable serving directory requests when "
4184               "system TCP buffer resources are scarce.");
4185    }
4186  }
4187
4188  if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
4189      options->V3AuthVotingInterval/2) {
4190    /*
4191    This doesn't work, but it seems like it should:
4192     what code is preventing the interval being less than twice the lead-up?
4193    if (options->TestingTorNetwork) {
4194      if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
4195          options->V3AuthVotingInterval) {
4196        REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than "
4197               "V3AuthVotingInterval");
4198      } else {
4199        COMPLAIN("V3AuthVoteDelay plus V3AuthDistDelay is more than half "
4200                 "V3AuthVotingInterval. This may lead to "
4201                 "consensus instability, particularly if clocks drift.");
4202      }
4203    } else {
4204     */
4205      REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
4206             "V3AuthVotingInterval");
4207    /*
4208    }
4209     */
4210  }
4211
4212  if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS) {
4213    if (options->TestingTorNetwork) {
4214      if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS_TESTING) {
4215        REJECT("V3AuthVoteDelay is way too low.");
4216      } else {
4217        COMPLAIN("V3AuthVoteDelay is very low. "
4218                 "This may lead to failure to vote for a consensus.");
4219      }
4220    } else {
4221      REJECT("V3AuthVoteDelay is way too low.");
4222    }
4223  }
4224
4225  if (options->V3AuthDistDelay < MIN_DIST_SECONDS) {
4226    if (options->TestingTorNetwork) {
4227      if (options->V3AuthDistDelay < MIN_DIST_SECONDS_TESTING) {
4228        REJECT("V3AuthDistDelay is way too low.");
4229      } else {
4230        COMPLAIN("V3AuthDistDelay is very low. "
4231                 "This may lead to missing votes in a consensus.");
4232      }
4233    } else {
4234      REJECT("V3AuthDistDelay is way too low.");
4235    }
4236  }
4237
4238  if (options->V3AuthNIntervalsValid < 2)
4239    REJECT("V3AuthNIntervalsValid must be at least 2.");
4240
4241  if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL) {
4242    if (options->TestingTorNetwork) {
4243      if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL_TESTING) {
4244        REJECT("V3AuthVotingInterval is insanely low.");
4245      } else {
4246        COMPLAIN("V3AuthVotingInterval is very low. "
4247                 "This may lead to failure to synchronise for a consensus.");
4248      }
4249    } else {
4250      REJECT("V3AuthVotingInterval is insanely low.");
4251    }
4252  } else if (options->V3AuthVotingInterval > 24*60*60) {
4253    REJECT("V3AuthVotingInterval is insanely high.");
4254  } else if (((24*60*60) % options->V3AuthVotingInterval) != 0) {
4255    COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
4256  }
4257
4258  if (hs_config_service_all(options, 1) < 0)
4259    REJECT("Failed to configure rendezvous options. See logs for details.");
4260
4261  /* Parse client-side authorization for hidden services. */
4262  if (rend_parse_service_authorization(options, 1) < 0)
4263    REJECT("Failed to configure client authorization for hidden services. "
4264           "See logs for details.");
4265
4266  if (parse_virtual_addr_network(options->VirtualAddrNetworkIPv4,
4267                                 AF_INET, 1, msg)<0)
4268    return -1;
4269  if (parse_virtual_addr_network(options->VirtualAddrNetworkIPv6,
4270                                 AF_INET6, 1, msg)<0)
4271    return -1;
4272
4273  if (options->TestingTorNetwork &&
4274      !(options->DirAuthorities ||
4275        (options->AlternateDirAuthority &&
4276         options->AlternateBridgeAuthority))) {
4277    REJECT("TestingTorNetwork may only be configured in combination with "
4278           "a non-default set of DirAuthority or both of "
4279           "AlternateDirAuthority and AlternateBridgeAuthority configured.");
4280  }
4281
4282#define CHECK_DEFAULT(arg)                                              \
4283  STMT_BEGIN                                                            \
4284    if (!options->TestingTorNetwork &&                                  \
4285        !options->UsingTestNetworkDefaults_ &&                          \
4286        !config_is_same(&options_format,options,                        \
4287                        default_options,#arg)) {                        \
4288      REJECT(#arg " may only be changed in testing Tor "                \
4289             "networks!");                                              \
4290    } STMT_END
4291  CHECK_DEFAULT(TestingV3AuthInitialVotingInterval);
4292  CHECK_DEFAULT(TestingV3AuthInitialVoteDelay);
4293  CHECK_DEFAULT(TestingV3AuthInitialDistDelay);
4294  CHECK_DEFAULT(TestingV3AuthVotingStartOffset);
4295  CHECK_DEFAULT(TestingAuthDirTimeToLearnReachability);
4296  CHECK_DEFAULT(TestingEstimatedDescriptorPropagationTime);
4297  CHECK_DEFAULT(TestingServerDownloadSchedule);
4298  CHECK_DEFAULT(TestingClientDownloadSchedule);
4299  CHECK_DEFAULT(TestingServerConsensusDownloadSchedule);
4300  CHECK_DEFAULT(TestingClientConsensusDownloadSchedule);
4301  CHECK_DEFAULT(TestingBridgeDownloadSchedule);
4302  CHECK_DEFAULT(TestingBridgeBootstrapDownloadSchedule);
4303  CHECK_DEFAULT(TestingClientMaxIntervalWithoutRequest);
4304  CHECK_DEFAULT(TestingDirConnectionMaxStall);
4305  CHECK_DEFAULT(TestingConsensusMaxDownloadTries);
4306  CHECK_DEFAULT(TestingDescriptorMaxDownloadTries);
4307  CHECK_DEFAULT(TestingMicrodescMaxDownloadTries);
4308  CHECK_DEFAULT(TestingCertMaxDownloadTries);
4309  CHECK_DEFAULT(TestingAuthKeyLifetime);
4310  CHECK_DEFAULT(TestingLinkCertLifetime);
4311  CHECK_DEFAULT(TestingSigningKeySlop);
4312  CHECK_DEFAULT(TestingAuthKeySlop);
4313  CHECK_DEFAULT(TestingLinkKeySlop);
4314#undef CHECK_DEFAULT
4315
4316  if (!options->ClientDNSRejectInternalAddresses &&
4317      !(options->DirAuthorities ||
4318        (options->AlternateDirAuthority && options->AlternateBridgeAuthority)))
4319    REJECT("ClientDNSRejectInternalAddresses used for default network.");
4320  if (options->SigningKeyLifetime < options->TestingSigningKeySlop*2)
4321    REJECT("SigningKeyLifetime is too short.");
4322  if (options->TestingLinkCertLifetime < options->TestingAuthKeySlop*2)
4323    REJECT("LinkCertLifetime is too short.");
4324  if (options->TestingAuthKeyLifetime < options->TestingLinkKeySlop*2)
4325    REJECT("TestingAuthKeyLifetime is too short.");
4326
4327  if (options->TestingV3AuthInitialVotingInterval
4328      < MIN_VOTE_INTERVAL_TESTING_INITIAL) {
4329    REJECT("TestingV3AuthInitialVotingInterval is insanely low.");
4330  } else if (((30*60) % options->TestingV3AuthInitialVotingInterval) != 0) {
4331    REJECT("TestingV3AuthInitialVotingInterval does not divide evenly into "
4332           "30 minutes.");
4333  }
4334
4335  if (options->TestingV3AuthInitialVoteDelay < MIN_VOTE_SECONDS_TESTING) {
4336    REJECT("TestingV3AuthInitialVoteDelay is way too low.");
4337  }
4338
4339  if (options->TestingV3AuthInitialDistDelay < MIN_DIST_SECONDS_TESTING) {
4340    REJECT("TestingV3AuthInitialDistDelay is way too low.");
4341  }
4342
4343  if (options->TestingV3AuthInitialVoteDelay +
4344      options->TestingV3AuthInitialDistDelay >=
4345      options->TestingV3AuthInitialVotingInterval) {
4346    REJECT("TestingV3AuthInitialVoteDelay plus TestingV3AuthInitialDistDelay "
4347           "must be less than TestingV3AuthInitialVotingInterval");
4348  }
4349
4350  if (options->TestingV3AuthVotingStartOffset >
4351      MIN(options->TestingV3AuthInitialVotingInterval,
4352          options->V3AuthVotingInterval)) {
4353    REJECT("TestingV3AuthVotingStartOffset is higher than the voting "
4354           "interval.");
4355  } else if (options->TestingV3AuthVotingStartOffset < 0) {
4356    REJECT("TestingV3AuthVotingStartOffset must be non-negative.");
4357  }
4358
4359  if (options->TestingAuthDirTimeToLearnReachability < 0) {
4360    REJECT("TestingAuthDirTimeToLearnReachability must be non-negative.");
4361  } else if (options->TestingAuthDirTimeToLearnReachability > 2*60*60) {
4362    COMPLAIN("TestingAuthDirTimeToLearnReachability is insanely high.");
4363  }
4364
4365  if (options->TestingEstimatedDescriptorPropagationTime < 0) {
4366    REJECT("TestingEstimatedDescriptorPropagationTime must be non-negative.");
4367  } else if (options->TestingEstimatedDescriptorPropagationTime > 60*60) {
4368    COMPLAIN("TestingEstimatedDescriptorPropagationTime is insanely high.");
4369  }
4370
4371  if (options->TestingClientMaxIntervalWithoutRequest < 1) {
4372    REJECT("TestingClientMaxIntervalWithoutRequest is way too low.");
4373  } else if (options->TestingClientMaxIntervalWithoutRequest > 3600) {
4374    COMPLAIN("TestingClientMaxIntervalWithoutRequest is insanely high.");
4375  }
4376
4377  if (options->TestingDirConnectionMaxStall < 5) {
4378    REJECT("TestingDirConnectionMaxStall is way too low.");
4379  } else if (options->TestingDirConnectionMaxStall > 3600) {
4380    COMPLAIN("TestingDirConnectionMaxStall is insanely high.");
4381  }
4382
4383  if (options->TestingConsensusMaxDownloadTries < 2) {
4384    REJECT("TestingConsensusMaxDownloadTries must be greater than 2.");
4385  } else if (options->TestingConsensusMaxDownloadTries > 800) {
4386    COMPLAIN("TestingConsensusMaxDownloadTries is insanely high.");
4387  }
4388
4389  if (options->ClientBootstrapConsensusMaxDownloadTries < 2) {
4390    REJECT("ClientBootstrapConsensusMaxDownloadTries must be greater "
4391           "than 2."
4392           );
4393  } else if (options->ClientBootstrapConsensusMaxDownloadTries > 800) {
4394    COMPLAIN("ClientBootstrapConsensusMaxDownloadTries is insanely "
4395             "high.");
4396  }
4397
4398  if (options->ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries
4399      < 2) {
4400    REJECT("ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries must "
4401           "be greater than 2."
4402           );
4403  } else if (
4404        options->ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries
4405        > 800) {
4406    COMPLAIN("ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries is "
4407             "insanely high.");
4408  }
4409
4410  if (options->ClientBootstrapConsensusMaxInProgressTries < 1) {
4411    REJECT("ClientBootstrapConsensusMaxInProgressTries must be greater "
4412           "than 0.");
4413  } else if (options->ClientBootstrapConsensusMaxInProgressTries
4414             > 100) {
4415    COMPLAIN("ClientBootstrapConsensusMaxInProgressTries is insanely "
4416             "high.");
4417  }
4418
4419  if (options->TestingDescriptorMaxDownloadTries < 2) {
4420    REJECT("TestingDescriptorMaxDownloadTries must be greater than 1.");
4421  } else if (options->TestingDescriptorMaxDownloadTries > 800) {
4422    COMPLAIN("TestingDescriptorMaxDownloadTries is insanely high.");
4423  }
4424
4425  if (options->TestingMicrodescMaxDownloadTries < 2) {
4426    REJECT("TestingMicrodescMaxDownloadTries must be greater than 1.");
4427  } else if (options->TestingMicrodescMaxDownloadTries > 800) {
4428    COMPLAIN("TestingMicrodescMaxDownloadTries is insanely high.");
4429  }
4430
4431  if (options->TestingCertMaxDownloadTries < 2) {
4432    REJECT("TestingCertMaxDownloadTries must be greater than 1.");
4433  } else if (options->TestingCertMaxDownloadTries > 800) {
4434    COMPLAIN("TestingCertMaxDownloadTries is insanely high.");
4435  }
4436
4437  if (options->TestingEnableConnBwEvent &&
4438      !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
4439    REJECT("TestingEnableConnBwEvent may only be changed in testing "
4440           "Tor networks!");
4441  }
4442
4443  if (options->TestingEnableCellStatsEvent &&
4444      !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
4445    REJECT("TestingEnableCellStatsEvent may only be changed in testing "
4446           "Tor networks!");
4447  }
4448
4449  if (options->TestingEnableTbEmptyEvent &&
4450      !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
4451    REJECT("TestingEnableTbEmptyEvent may only be changed in testing "
4452           "Tor networks!");
4453  }
4454
4455  if (options->TestingTorNetwork) {
4456    log_warn(LD_CONFIG, "TestingTorNetwork is set. This will make your node "
4457                        "almost unusable in the public Tor network, and is "
4458                        "therefore only advised if you are building a "
4459                        "testing Tor network!");
4460  }
4461
4462  if (options->AccelName && !options->HardwareAccel)
4463    options->HardwareAccel = 1;
4464  if (options->AccelDir && !options->AccelName)
4465    REJECT("Can't use hardware crypto accelerator dir without engine name.");
4466
4467  if (options->PublishServerDescriptor)
4468    SMARTLIST_FOREACH(options->PublishServerDescriptor, const char *, pubdes, {
4469      if (!strcmp(pubdes, "1") || !strcmp(pubdes, "0"))
4470        if (smartlist_len(options->PublishServerDescriptor) > 1) {
4471          COMPLAIN("You have passed a list of multiple arguments to the "
4472                   "PublishServerDescriptor option that includes 0 or 1. "
4473                   "0 or 1 should only be used as the sole argument. "
4474                   "This configuration will be rejected in a future release.");
4475          break;
4476        }
4477    });
4478
4479  if (options->BridgeRelay == 1 && ! options->ORPort_set)
4480      REJECT("BridgeRelay is 1, ORPort is not set. This is an invalid "
4481             "combination.");
4482
4483  if (options_validate_scheduler(options, msg) < 0) {
4484    return -1;
4485  }
4486
4487  return 0;
4488}
4489
4490#undef REJECT
4491#undef COMPLAIN
4492
4493/* Given the value that the user has set for MaxMemInQueues, compute the
4494 * actual maximum value.  We clip this value if it's too low, and autodetect
4495 * it if it's set to 0. */
4496static uint64_t
4497compute_real_max_mem_in_queues(const uint64_t val, int log_guess)
4498{
4499  uint64_t result;
4500
4501  if (val == 0) {
4502#define ONE_GIGABYTE (U64_LITERAL(1) << 30)
4503#define ONE_MEGABYTE (U64_LITERAL(1) << 20)
4504#if SIZEOF_VOID_P >= 8
4505#define MAX_DEFAULT_MAXMEM (8*ONE_GIGABYTE)
4506#else
4507#define MAX_DEFAULT_MAXMEM (2*ONE_GIGABYTE)
4508#endif
4509    /* The user didn't pick a memory limit.  Choose a very large one
4510     * that is still smaller than the system memory */
4511    static int notice_sent = 0;
4512    size_t ram = 0;
4513    if (get_total_system_memory(&ram) < 0) {
4514      /* We couldn't determine our total system memory!  */
4515#if SIZEOF_VOID_P >= 8
4516      /* 64-bit system.  Let's hope for 8 GB. */
4517      result = 8 * ONE_GIGABYTE;
4518#else
4519      /* (presumably) 32-bit system. Let's hope for 1 GB. */
4520      result = ONE_GIGABYTE;
4521#endif /* SIZEOF_VOID_P >= 8 */
4522    } else {
4523      /* We detected it, so let's pick 3/4 of the total RAM as our limit. */
4524      const uint64_t avail = (ram / 4) * 3;
4525
4526      /* Make sure it's in range from 0.25 GB to 8 GB. */
4527      if (avail > MAX_DEFAULT_MAXMEM) {
4528        /* If you want to use more than this much RAM, you need to configure
4529           it yourself */
4530        result = MAX_DEFAULT_MAXMEM;
4531      } else if (avail < ONE_GIGABYTE / 4) {
4532        result = ONE_GIGABYTE / 4;
4533      } else {
4534        result = avail;
4535      }
4536    }
4537    if (log_guess && ! notice_sent) {
4538      log_notice(LD_CONFIG, "%sMaxMemInQueues is set to "U64_FORMAT" MB. "
4539                 "You can override this by setting MaxMemInQueues by hand.",
4540                 ram ? "Based on detected system memory, " : "",
4541                 U64_PRINTF_ARG(result / ONE_MEGABYTE));
4542      notice_sent = 1;
4543    }
4544    return result;
4545  } else if (val < ONE_GIGABYTE / 4) {
4546    log_warn(LD_CONFIG, "MaxMemInQueues must be at least 256 MB for now. "
4547             "Ideally, have it as large as you can afford.");
4548    return ONE_GIGABYTE / 4;
4549  } else {
4550    /* The value was fine all along */
4551    return val;
4552  }
4553}
4554
4555/* If we have less than 300 MB suggest disabling dircache */
4556#define DIRCACHE_MIN_MEM_MB 300
4557#define DIRCACHE_MIN_MEM_BYTES (DIRCACHE_MIN_MEM_MB*ONE_MEGABYTE)
4558#define STRINGIFY(val) #val
4559
4560/** Create a warning message for emitting if we are a dircache but may not have
4561 * enough system memory, or if we are not a dircache but probably should be.
4562 * Return -1 when a message is returned in *msg*, else return 0. */
4563STATIC int
4564have_enough_mem_for_dircache(const or_options_t *options, size_t total_mem,
4565                             char **msg)
4566{
4567  *msg = NULL;
4568  /* XXX We should possibly be looking at MaxMemInQueues here
4569   * unconditionally.  Or we should believe total_mem unconditionally. */
4570  if (total_mem == 0) {
4571    if (get_total_system_memory(&total_mem) < 0) {
4572      total_mem = options->MaxMemInQueues >= SIZE_MAX ?
4573        SIZE_MAX : (size_t)options->MaxMemInQueues;
4574    }
4575  }
4576  if (options->DirCache) {
4577    if (total_mem < DIRCACHE_MIN_MEM_BYTES) {
4578      if (options->BridgeRelay) {
4579        *msg = tor_strdup("Running a Bridge with less than "
4580                      STRINGIFY(DIRCACHE_MIN_MEM_MB) " MB of memory is not "
4581                      "recommended.");
4582      } else {
4583        *msg = tor_strdup("Being a directory cache (default) with less than "
4584                      STRINGIFY(DIRCACHE_MIN_MEM_MB) " MB of memory is not "
4585                      "recommended and may consume most of the available "
4586                      "resources, consider disabling this functionality by "
4587                      "setting the DirCache option to 0.");
4588      }
4589    }
4590  } else {
4591    if (total_mem >= DIRCACHE_MIN_MEM_BYTES) {
4592      *msg = tor_strdup("DirCache is disabled and we are configured as a "
4593               "relay. This may disqualify us from becoming a guard in the "
4594               "future.");
4595    }
4596  }
4597  return *msg == NULL ? 0 : -1;
4598}
4599#undef STRINGIFY
4600
4601/** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
4602 * equal strings. */
4603static int
4604opt_streq(const char *s1, const char *s2)
4605{
4606  return 0 == strcmp_opt(s1, s2);
4607}
4608
4609/** Check if any of the previous options have changed but aren't allowed to. */
4610static int
4611options_transition_allowed(const or_options_t *old,
4612                           const or_options_t *new_val,
4613                           char **msg)
4614{
4615  if (!old)
4616    return 0;
4617
4618  if (!opt_streq(old->PidFile, new_val->PidFile)) {
4619    *msg = tor_strdup("PidFile is not allowed to change.");
4620    return -1;
4621  }
4622
4623  if (old->RunAsDaemon != new_val->RunAsDaemon) {
4624    *msg = tor_strdup("While Tor is running, changing RunAsDaemon "
4625                      "is not allowed.");
4626    return -1;
4627  }
4628
4629  if (old->Sandbox != new_val->Sandbox) {
4630    *msg = tor_strdup("While Tor is running, changing Sandbox "
4631                      "is not allowed.");
4632    return -1;
4633  }
4634
4635  if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
4636    tor_asprintf(msg,
4637               "While Tor is running, changing DataDirectory "
4638               "(\"%s\"->\"%s\") is not allowed.",
4639               old->DataDirectory, new_val->DataDirectory);
4640    return -1;
4641  }
4642
4643  if (!opt_streq(old->KeyDirectory, new_val->KeyDirectory)) {
4644    tor_asprintf(msg,
4645               "While Tor is running, changing KeyDirectory "
4646               "(\"%s\"->\"%s\") is not allowed.",
4647               old->KeyDirectory, new_val->KeyDirectory);
4648    return -1;
4649  }
4650
4651  if (!opt_streq(old->CacheDirectory, new_val->CacheDirectory)) {
4652    tor_asprintf(msg,
4653               "While Tor is running, changing CacheDirectory "
4654               "(\"%s\"->\"%s\") is not allowed.",
4655               old->CacheDirectory, new_val->CacheDirectory);
4656    return -1;
4657  }
4658
4659  if (!opt_streq(old->User, new_val->User)) {
4660    *msg = tor_strdup("While Tor is running, changing User is not allowed.");
4661    return -1;
4662  }
4663
4664  if (old->KeepBindCapabilities != new_val->KeepBindCapabilities) {
4665    *msg = tor_strdup("While Tor is running, changing KeepBindCapabilities is "
4666                      "not allowed.");
4667    return -1;
4668  }
4669
4670  if (!opt_streq(old->SyslogIdentityTag, new_val->SyslogIdentityTag)) {
4671    *msg = tor_strdup("While Tor is running, changing "
4672                      "SyslogIdentityTag is not allowed.");
4673    return -1;
4674  }
4675
4676  if (!opt_streq(old->AndroidIdentityTag, new_val->AndroidIdentityTag)) {
4677    *msg = tor_strdup("While Tor is running, changing "
4678                      "AndroidIdentityTag is not allowed.");
4679    return -1;
4680  }
4681
4682  if ((old->HardwareAccel != new_val->HardwareAccel)
4683      || !opt_streq(old->AccelName, new_val->AccelName)
4684      || !opt_streq(old->AccelDir, new_val->AccelDir)) {
4685    *msg = tor_strdup("While Tor is running, changing OpenSSL hardware "
4686                      "acceleration engine is not allowed.");
4687    return -1;
4688  }
4689
4690  if (old->TestingTorNetwork != new_val->TestingTorNetwork) {
4691    *msg = tor_strdup("While Tor is running, changing TestingTorNetwork "
4692                      "is not allowed.");
4693    return -1;
4694  }
4695
4696  if (old->DisableAllSwap != new_val->DisableAllSwap) {
4697    *msg = tor_strdup("While Tor is running, changing DisableAllSwap "
4698                      "is not allowed.");
4699    return -1;
4700  }
4701
4702  if (old->TokenBucketRefillInterval != new_val->TokenBucketRefillInterval) {
4703    *msg = tor_strdup("While Tor is running, changing TokenBucketRefill"
4704                      "Interval is not allowed");
4705    return -1;
4706  }
4707
4708  if (old->HiddenServiceSingleHopMode != new_val->HiddenServiceSingleHopMode) {
4709    *msg = tor_strdup("While Tor is running, changing "
4710                      "HiddenServiceSingleHopMode is not allowed.");
4711    return -1;
4712  }
4713
4714  if (old->HiddenServiceNonAnonymousMode !=
4715      new_val->HiddenServiceNonAnonymousMode) {
4716    *msg = tor_strdup("While Tor is running, changing "
4717                      "HiddenServiceNonAnonymousMode is not allowed.");
4718    return -1;
4719  }
4720
4721  if (old->DisableDebuggerAttachment &&
4722      !new_val->DisableDebuggerAttachment) {
4723    *msg = tor_strdup("While Tor is running, disabling "
4724                      "DisableDebuggerAttachment is not allowed.");
4725    return -1;
4726  }
4727
4728  if (old->NoExec && !new_val->NoExec) {
4729    *msg = tor_strdup("While Tor is running, disabling "
4730                      "NoExec is not allowed.");
4731    return -1;
4732  }
4733
4734  if (old->OwningControllerFD != new_val->OwningControllerFD) {
4735    *msg = tor_strdup("While Tor is running, changing OwningControllerFD "
4736                      "is not allowed.");
4737    return -1;
4738  }
4739
4740  if (sandbox_is_active()) {
4741#define SB_NOCHANGE_STR(opt)                                            \
4742    do {                                                                \
4743      if (! opt_streq(old->opt, new_val->opt)) {                        \
4744        *msg = tor_strdup("Can't change " #opt " while Sandbox is active"); \
4745        return -1;                                                      \
4746      }                                                                 \
4747    } while (0)
4748
4749    SB_NOCHANGE_STR(Address);
4750    SB_NOCHANGE_STR(ServerDNSResolvConfFile);
4751    SB_NOCHANGE_STR(DirPortFrontPage);
4752    SB_NOCHANGE_STR(CookieAuthFile);
4753    SB_NOCHANGE_STR(ExtORPortCookieAuthFile);
4754
4755#undef SB_NOCHANGE_STR
4756
4757    if (! config_lines_eq(old->Logs, new_val->Logs)) {
4758      *msg = tor_strdup("Can't change Logs while Sandbox is active");
4759      return -1;
4760    }
4761    if (old->ConnLimit != new_val->ConnLimit) {
4762      *msg = tor_strdup("Can't change ConnLimit while Sandbox is active");
4763      return -1;
4764    }
4765    if (server_mode(old) != server_mode(new_val)) {
4766      *msg = tor_strdup("Can't start/stop being a server while "
4767                        "Sandbox is active");
4768      return -1;
4769    }
4770  }
4771
4772  return 0;
4773}
4774
4775/** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
4776 * will require us to rotate the CPU and DNS workers; else return 0. */
4777static int
4778options_transition_affects_workers(const or_options_t *old_options,
4779                                   const or_options_t *new_options)
4780{
4781  if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
4782      old_options->NumCPUs != new_options->NumCPUs ||
4783      !config_lines_eq(old_options->ORPort_lines, new_options->ORPort_lines) ||
4784      old_options->ServerDNSSearchDomains !=
4785                                       new_options->ServerDNSSearchDomains ||
4786      old_options->SafeLogging_ != new_options->SafeLogging_ ||
4787      old_options->ClientOnly != new_options->ClientOnly ||
4788      server_mode(old_options) != server_mode(new_options) ||
4789      public_server_mode(old_options) != public_server_mode(new_options) ||
4790      !config_lines_eq(old_options->Logs, new_options->Logs) ||
4791      old_options->LogMessageDomains != new_options->LogMessageDomains)
4792    return 1;
4793
4794  /* Check whether log options match. */
4795
4796  /* Nothing that changed matters. */
4797  return 0;
4798}
4799
4800/** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
4801 * will require us to generate a new descriptor; else return 0. */
4802static int
4803options_transition_affects_descriptor(const or_options_t *old_options,
4804                                      const or_options_t *new_options)
4805{
4806  /* XXX We can be smarter here. If your DirPort isn't being
4807   * published and you just turned it off, no need to republish. Etc. */
4808  if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
4809      !opt_streq(old_options->Nickname,new_options->Nickname) ||
4810      !opt_streq(old_options->Address,new_options->Address) ||
4811      !config_lines_eq(old_options->ExitPolicy,new_options->ExitPolicy) ||
4812      old_options->ExitRelay != new_options->ExitRelay ||
4813      old_options->ExitPolicyRejectPrivate !=
4814        new_options->ExitPolicyRejectPrivate ||
4815      old_options->ExitPolicyRejectLocalInterfaces !=
4816        new_options->ExitPolicyRejectLocalInterfaces ||
4817      old_options->IPv6Exit != new_options->IPv6Exit ||
4818      !config_lines_eq(old_options->ORPort_lines,
4819                       new_options->ORPort_lines) ||
4820      !config_lines_eq(old_options->DirPort_lines,
4821                       new_options->DirPort_lines) ||
4822      old_options->ClientOnly != new_options->ClientOnly ||
4823      old_options->DisableNetwork != new_options->DisableNetwork ||
4824      old_options->PublishServerDescriptor_ !=
4825        new_options->PublishServerDescriptor_ ||
4826      get_effective_bwrate(old_options) != get_effective_bwrate(new_options) ||
4827      get_effective_bwburst(old_options) !=
4828        get_effective_bwburst(new_options) ||
4829      !opt_streq(old_options->ContactInfo, new_options->ContactInfo) ||
4830      !opt_streq(old_options->BridgeDistribution,
4831                 new_options->BridgeDistribution) ||
4832      !config_lines_eq(old_options->MyFamily, new_options->MyFamily) ||
4833      !opt_streq(old_options->AccountingStart, new_options->AccountingStart) ||
4834      old_options->AccountingMax != new_options->AccountingMax ||
4835      old_options->AccountingRule != new_options->AccountingRule ||
4836      public_server_mode(old_options) != public_server_mode(new_options) ||
4837      old_options->DirCache != new_options->DirCache ||
4838      old_options->AssumeReachable != new_options->AssumeReachable)
4839    return 1;
4840
4841  return 0;
4842}
4843
4844#ifdef _WIN32
4845/** Return the directory on windows where we expect to find our application
4846 * data. */
4847static char *
4848get_windows_conf_root(void)
4849{
4850  static int is_set = 0;
4851  static char path[MAX_PATH*2+1];
4852  TCHAR tpath[MAX_PATH] = {0};
4853
4854  LPITEMIDLIST idl;
4855  IMalloc *m;
4856  HRESULT result;
4857
4858  if (is_set)
4859    return path;
4860
4861  /* Find X:\documents and settings\username\application data\ .
4862   * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
4863   */
4864#ifdef ENABLE_LOCAL_APPDATA
4865#define APPDATA_PATH CSIDL_LOCAL_APPDATA
4866#else
4867#define APPDATA_PATH CSIDL_APPDATA
4868#endif
4869  if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, APPDATA_PATH, &idl))) {
4870    getcwd(path,MAX_PATH);
4871    is_set = 1;
4872    log_warn(LD_CONFIG,
4873             "I couldn't find your application data folder: are you "
4874             "running an ancient version of Windows 95? Defaulting to \"%s\"",
4875             path);
4876    return path;
4877  }
4878  /* Convert the path from an "ID List" (whatever that is!) to a path. */
4879  result = SHGetPathFromIDList(idl, tpath);
4880#ifdef UNICODE
4881  wcstombs(path,tpath,sizeof(path));
4882  path[sizeof(path)-1] = '\0';
4883#else
4884  strlcpy(path,tpath,sizeof(path));
4885#endif /* defined(UNICODE) */
4886
4887  /* Now we need to free the memory that the path-idl was stored in.  In
4888   * typical Windows fashion, we can't just call 'free()' on it. */
4889  SHGetMalloc(&m);
4890  if (m) {
4891    m->lpVtbl->Free(m, idl);
4892    m->lpVtbl->Release(m);
4893  }
4894  if (!SUCCEEDED(result)) {
4895    return NULL;
4896  }
4897  strlcat(path,"\\tor",MAX_PATH);
4898  is_set = 1;
4899  return path;
4900}
4901#endif /* defined(_WIN32) */
4902
4903/** Return the default location for our torrc file (if <b>defaults_file</b> is
4904 * false), or for the torrc-defaults file (if <b>defaults_file</b> is true). */
4905static const char *
4906get_default_conf_file(int defaults_file)
4907{
4908#ifdef DISABLE_SYSTEM_TORRC
4909  (void) defaults_file;
4910  return NULL;
4911#elif defined(_WIN32)
4912  if (defaults_file) {
4913    static char defaults_path[MAX_PATH+1];
4914    tor_snprintf(defaults_path, MAX_PATH, "%s\\torrc-defaults",
4915                 get_windows_conf_root());
4916    return defaults_path;
4917  } else {
4918    static char path[MAX_PATH+1];
4919    tor_snprintf(path, MAX_PATH, "%s\\torrc",
4920                 get_windows_conf_root());
4921    return path;
4922  }
4923#else
4924  return defaults_file ? CONFDIR "/torrc-defaults" : CONFDIR "/torrc";
4925#endif /* defined(DISABLE_SYSTEM_TORRC) || ... */
4926}
4927
4928/** Verify whether lst is a list of strings containing valid-looking
4929 * comma-separated nicknames, or NULL. Will normalise <b>lst</b> to prefix '$'
4930 * to any nickname or fingerprint that needs it. Also splits comma-separated
4931 * list elements into multiple elements. Return 0 on success.
4932 * Warn and return -1 on failure.
4933 */
4934static int
4935normalize_nickname_list(config_line_t **normalized_out,
4936                        const config_line_t *lst, const char *name,
4937                        char **msg)
4938{
4939  if (!lst)
4940    return 0;
4941
4942  config_line_t *new_nicknames = NULL;
4943  config_line_t **new_nicknames_next = &new_nicknames;
4944
4945  const config_line_t *cl;
4946  for (cl = lst; cl; cl = cl->next) {
4947    const char *line = cl->value;
4948    if (!line)
4949      continue;
4950
4951    int valid_line = 1;
4952    smartlist_t *sl = smartlist_new();
4953    smartlist_split_string(sl, line, ",",
4954      SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK|SPLIT_STRIP_SPACE, 0);
4955    SMARTLIST_FOREACH_BEGIN(sl, char *, s)
4956    {
4957      char *normalized = NULL;
4958      if (!is_legal_nickname_or_hexdigest(s)) {
4959        // check if first char is dollar
4960        if (s[0] != '$') {
4961          // Try again but with a dollar symbol prepended
4962          char *prepended;
4963          tor_asprintf(&prepended, "$%s", s);
4964
4965          if (is_legal_nickname_or_hexdigest(prepended)) {
4966            // The nickname is valid when it's prepended, set it as the
4967            // normalized version
4968            normalized = prepended;
4969          } else {
4970            // Still not valid, free and fallback to error message
4971            tor_free(prepended);
4972          }
4973        }
4974
4975        if (!normalized) {
4976          tor_asprintf(msg, "Invalid nickname '%s' in %s line", s, name);
4977          valid_line = 0;
4978          break;
4979        }
4980      } else {
4981        normalized = tor_strdup(s);
4982      }
4983
4984      config_line_t *next = tor_malloc_zero(sizeof(*next));
4985      next->key = tor_strdup(cl->key);
4986      next->value = normalized;
4987      next->next = NULL;
4988
4989      *new_nicknames_next = next;
4990      new_nicknames_next = &next->next;
4991    } SMARTLIST_FOREACH_END(s);
4992
4993    SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
4994    smartlist_free(sl);
4995
4996    if (!valid_line) {
4997      config_free_lines(new_nicknames);
4998      return -1;
4999    }
5000  }
5001
5002  *normalized_out = new_nicknames;
5003
5004  return 0;
5005}
5006
5007/** Learn config file name from command line arguments, or use the default.
5008 *
5009 * If <b>defaults_file</b> is true, we're looking for torrc-defaults;
5010 * otherwise, we're looking for the regular torrc_file.
5011 *
5012 * Set *<b>using_default_fname</b> to true if we're using the default
5013 * configuration file name; or false if we've set it from the command line.
5014 *
5015 * Set *<b>ignore_missing_torrc</b> to true if we should ignore the resulting
5016 * filename if it doesn't exist.
5017 */
5018static char *
5019find_torrc_filename(config_line_t *cmd_arg,
5020                    int defaults_file,
5021                    int *using_default_fname, int *ignore_missing_torrc)
5022{
5023  char *fname=NULL;
5024  config_line_t *p_index;
5025  const char *fname_opt = defaults_file ? "--defaults-torrc" : "-f";
5026  const char *ignore_opt = defaults_file ? NULL : "--ignore-missing-torrc";
5027
5028  if (defaults_file)
5029    *ignore_missing_torrc = 1;
5030
5031  for (p_index = cmd_arg; p_index; p_index = p_index->next) {
5032    if (!strcmp(p_index->key, fname_opt)) {
5033      if (fname) {
5034        log_warn(LD_CONFIG, "Duplicate %s options on command line.",
5035            fname_opt);
5036        tor_free(fname);
5037      }
5038      fname = expand_filename(p_index->value);
5039
5040      {
5041        char *absfname;
5042        absfname = make_path_absolute(fname);
5043        tor_free(fname);
5044        fname = absfname;
5045      }
5046
5047      *using_default_fname = 0;
5048    } else if (ignore_opt && !strcmp(p_index->key,ignore_opt)) {
5049      *ignore_missing_torrc = 1;
5050    }
5051  }
5052
5053  if (*using_default_fname) {
5054    /* didn't find one, try CONFDIR */
5055    const char *dflt = get_default_conf_file(defaults_file);
5056    file_status_t st = file_status(dflt);
5057    if (dflt && (st == FN_FILE || st == FN_EMPTY)) {
5058      fname = tor_strdup(dflt);
5059    } else {
5060#ifndef _WIN32
5061      char *fn = NULL;
5062      if (!defaults_file) {
5063        fn = expand_filename("~/.torrc");
5064      }
5065      if (fn) {
5066        file_status_t hmst = file_status(fn);
5067        if (hmst == FN_FILE || hmst == FN_EMPTY || dflt == NULL) {
5068          fname = fn;
5069        } else {
5070          tor_free(fn);
5071          fname = tor_strdup(dflt);
5072        }
5073      } else {
5074        fname = dflt ? tor_strdup(dflt) : NULL;
5075      }
5076#else /* !(!defined(_WIN32)) */
5077      fname = dflt ? tor_strdup(dflt) : NULL;
5078#endif /* !defined(_WIN32) */
5079    }
5080  }
5081  return fname;
5082}
5083
5084/** Read the torrc from standard input and return it as a string.
5085 * Upon failure, return NULL.
5086 */
5087static char *
5088load_torrc_from_stdin(void)
5089{
5090   size_t sz_out;
5091
5092   return read_file_to_str_until_eof(STDIN_FILENO,SIZE_MAX,&sz_out);
5093}
5094
5095/** Load a configuration file from disk, setting torrc_fname or
5096 * torrc_defaults_fname if successful.
5097 *
5098 * If <b>defaults_file</b> is true, load torrc-defaults; otherwise load torrc.
5099 *
5100 * Return the contents of the file on success, and NULL on failure.
5101 */
5102static char *
5103load_torrc_from_disk(config_line_t *cmd_arg, int defaults_file)
5104{
5105  char *fname=NULL;
5106  char *cf = NULL;
5107  int using_default_torrc = 1;
5108  int ignore_missing_torrc = 0;
5109  char **fname_var = defaults_file ? &torrc_defaults_fname : &torrc_fname;
5110
5111  if (*fname_var == NULL) {
5112    fname = find_torrc_filename(cmd_arg, defaults_file,
5113                                &using_default_torrc, &ignore_missing_torrc);
5114    tor_free(*fname_var);
5115    *fname_var = fname;
5116  } else {
5117    fname = *fname_var;
5118  }
5119  log_debug(LD_CONFIG, "Opening config file \"%s\"", fname?fname:"<NULL>");
5120
5121  /* Open config file */
5122  file_status_t st = fname ? file_status(fname) : FN_EMPTY;
5123  if (fname == NULL ||
5124      !(st == FN_FILE || st == FN_EMPTY) ||
5125      !(cf = read_file_to_str(fname,0,NULL))) {
5126    if (using_default_torrc == 1 || ignore_missing_torrc) {
5127      if (!defaults_file)
5128        log_notice(LD_CONFIG, "Configuration file \"%s\" not present, "
5129            "using reasonable defaults.", fname);
5130      tor_free(fname); /* sets fname to NULL */
5131      *fname_var = NULL;
5132      cf = tor_strdup("");
5133    } else {
5134      log_warn(LD_CONFIG,
5135          "Unable to open configuration file \"%s\".", fname);
5136      goto err;
5137    }
5138  } else {
5139    log_notice(LD_CONFIG, "Read configuration file \"%s\".", fname);
5140  }
5141
5142  return cf;
5143 err:
5144  tor_free(fname);
5145  *fname_var = NULL;
5146  return NULL;
5147}
5148
5149/** Read a configuration file into <b>options</b>, finding the configuration
5150 * file location based on the command line.  After loading the file
5151 * call options_init_from_string() to load the config.
5152 * Return 0 if success, -1 if failure, and 1 if we succeeded but should exit
5153 * anyway. */
5154int
5155options_init_from_torrc(int argc, char **argv)
5156{
5157  char *cf=NULL, *cf_defaults=NULL;
5158  int command;
5159  int retval = -1;
5160  char *command_arg = NULL;
5161  char *errmsg=NULL;
5162  config_line_t *p_index = NULL;
5163  config_line_t *cmdline_only_options = NULL;
5164
5165  /* Go through command-line variables */
5166  if (! have_parsed_cmdline) {
5167    /* Or we could redo the list every time we pass this place.
5168     * It does not really matter */
5169    if (config_parse_commandline(argc, argv, 0, &global_cmdline_options,
5170                                 &global_cmdline_only_options) < 0) {
5171      goto err;
5172    }
5173    have_parsed_cmdline = 1;
5174  }
5175  cmdline_only_options = global_cmdline_only_options;
5176
5177  if (config_line_find(cmdline_only_options, "-h") ||
5178      config_line_find(cmdline_only_options, "--help")) {
5179    print_usage();
5180    return 1;
5181  }
5182  if (config_line_find(cmdline_only_options, "--list-torrc-options")) {
5183    /* For validating whether we've documented everything. */
5184    list_torrc_options();
5185    return 1;
5186  }
5187  if (config_line_find(cmdline_only_options, "--list-deprecated-options")) {
5188    /* For validating whether what we have deprecated really exists. */
5189    list_deprecated_options();
5190    return 1;
5191  }
5192
5193  if (config_line_find(cmdline_only_options, "--version")) {
5194    printf("Tor version %s.\n",get_version());
5195    return 1;
5196  }
5197
5198  if (config_line_find(cmdline_only_options, "--library-versions")) {
5199    printf("Tor version %s. \n", get_version());
5200    printf("Library versions\tCompiled\t\tRuntime\n");
5201    printf("Libevent\t\t%-15s\t\t%s\n",
5202                      tor_libevent_get_header_version_str(),
5203                      tor_libevent_get_version_str());
5204    printf("OpenSSL \t\t%-15s\t\t%s\n",
5205                      crypto_openssl_get_header_version_str(),
5206                      crypto_openssl_get_version_str());
5207    if (tor_compress_supports_method(ZLIB_METHOD)) {
5208      printf("Zlib    \t\t%-15s\t\t%s\n",
5209                        tor_compress_version_str(ZLIB_METHOD),
5210                        tor_compress_header_version_str(ZLIB_METHOD));
5211    }
5212    if (tor_compress_supports_method(LZMA_METHOD)) {
5213      printf("Liblzma \t\t%-15s\t\t%s\n",
5214                        tor_compress_version_str(LZMA_METHOD),
5215                        tor_compress_header_version_str(LZMA_METHOD));
5216    }
5217    if (tor_compress_supports_method(ZSTD_METHOD)) {
5218      printf("Libzstd \t\t%-15s\t\t%s\n",
5219                        tor_compress_version_str(ZSTD_METHOD),
5220                        tor_compress_header_version_str(ZSTD_METHOD));
5221    }
5222    //TODO: Hex versions?
5223    return 1;
5224  }
5225
5226  command = CMD_RUN_TOR;
5227  for (p_index = cmdline_only_options; p_index; p_index = p_index->next) {
5228    if (!strcmp(p_index->key,"--keygen")) {
5229      command = CMD_KEYGEN;
5230    } else if (!strcmp(p_index->key, "--key-expiration")) {
5231      command = CMD_KEY_EXPIRATION;
5232      command_arg = p_index->value;
5233    } else if (!strcmp(p_index->key,"--list-fingerprint")) {
5234      command = CMD_LIST_FINGERPRINT;
5235    } else if (!strcmp(p_index->key, "--hash-password")) {
5236      command = CMD_HASH_PASSWORD;
5237      command_arg = p_index->value;
5238    } else if (!strcmp(p_index->key, "--dump-config")) {
5239      command = CMD_DUMP_CONFIG;
5240      command_arg = p_index->value;
5241    } else if (!strcmp(p_index->key, "--verify-config")) {
5242      command = CMD_VERIFY_CONFIG;
5243    }
5244  }
5245
5246  if (command == CMD_HASH_PASSWORD) {
5247    cf_defaults = tor_strdup("");
5248    cf = tor_strdup("");
5249  } else {
5250    cf_defaults = load_torrc_from_disk(cmdline_only_options, 1);
5251
5252    const config_line_t *f_line = config_line_find(cmdline_only_options,
5253                                                   "-f");
5254
5255    const int read_torrc_from_stdin =
5256    (f_line != NULL && strcmp(f_line->value, "-") == 0);
5257
5258    if (read_torrc_from_stdin) {
5259      cf = load_torrc_from_stdin();
5260    } else {
5261      cf = load_torrc_from_disk(cmdline_only_options, 0);
5262    }
5263
5264    if (!cf) {
5265      if (config_line_find(cmdline_only_options, "--allow-missing-torrc")) {
5266        cf = tor_strdup("");
5267      } else {
5268        goto err;
5269      }
5270    }
5271  }
5272
5273  retval = options_init_from_string(cf_defaults, cf, command, command_arg,
5274                                    &errmsg);
5275
5276  if (retval < 0)
5277    goto err;
5278
5279  if (config_line_find(cmdline_only_options, "--no-passphrase")) {
5280    if (command == CMD_KEYGEN) {
5281      get_options_mutable()->keygen_force_passphrase = FORCE_PASSPHRASE_OFF;
5282    } else {
5283      log_err(LD_CONFIG, "--no-passphrase specified without --keygen!");
5284      retval = -1;
5285      goto err;
5286    }
5287  }
5288
5289  if (config_line_find(cmdline_only_options, "--newpass")) {
5290    if (command == CMD_KEYGEN) {
5291      get_options_mutable()->change_key_passphrase = 1;
5292    } else {
5293      log_err(LD_CONFIG, "--newpass specified without --keygen!");
5294      retval = -1;
5295      goto err;
5296    }
5297  }
5298
5299  {
5300    const config_line_t *fd_line = config_line_find(cmdline_only_options,
5301                                                    "--passphrase-fd");
5302    if (fd_line) {
5303      if (get_options()->keygen_force_passphrase == FORCE_PASSPHRASE_OFF) {
5304        log_err(LD_CONFIG, "--no-passphrase specified with --passphrase-fd!");
5305        retval = -1;
5306        goto err;
5307      } else if (command != CMD_KEYGEN) {
5308        log_err(LD_CONFIG, "--passphrase-fd specified without --keygen!");
5309        retval = -1;
5310        goto err;
5311      } else {
5312        const char *v = fd_line->value;
5313        int ok = 1;
5314        long fd = tor_parse_long(v, 10, 0, INT_MAX, &ok, NULL);
5315        if (fd < 0 || ok == 0) {
5316          log_err(LD_CONFIG, "Invalid --passphrase-fd value %s", escaped(v));
5317          retval = -1;
5318          goto err;
5319        }
5320        get_options_mutable()->keygen_passphrase_fd = (int)fd;
5321        get_options_mutable()->use_keygen_passphrase_fd = 1;
5322        get_options_mutable()->keygen_force_passphrase = FORCE_PASSPHRASE_ON;
5323      }
5324    }
5325  }
5326
5327  {
5328    const config_line_t *key_line = config_line_find(cmdline_only_options,
5329                                                     "--master-key");
5330    if (key_line) {
5331      if (command != CMD_KEYGEN) {
5332        log_err(LD_CONFIG, "--master-key without --keygen!");
5333        retval = -1;
5334        goto err;
5335      } else {
5336        get_options_mutable()->master_key_fname = tor_strdup(key_line->value);
5337      }
5338    }
5339  }
5340
5341 err:
5342
5343  tor_free(cf);
5344  tor_free(cf_defaults);
5345  if (errmsg) {
5346    log_warn(LD_CONFIG,"%s", errmsg);
5347    tor_free(errmsg);
5348  }
5349  return retval < 0 ? -1 : 0;
5350}
5351
5352/** Load the options from the configuration in <b>cf</b>, validate
5353 * them for consistency and take actions based on them.
5354 *
5355 * Return 0 if success, negative on error:
5356 *  * -1 for general errors.
5357 *  * -2 for failure to parse/validate,
5358 *  * -3 for transition not allowed
5359 *  * -4 for error while setting the new options
5360 */
5361setopt_err_t
5362options_init_from_string(const char *cf_defaults, const char *cf,
5363                         int command, const char *command_arg,
5364                         char **msg)
5365{
5366  or_options_t *oldoptions, *newoptions, *newdefaultoptions=NULL;
5367  config_line_t *cl;
5368  int retval;
5369  setopt_err_t err = SETOPT_ERR_MISC;
5370  int cf_has_include = 0;
5371  tor_assert(msg);
5372
5373  oldoptions = global_options; /* get_options unfortunately asserts if
5374                                  this is the first time we run*/
5375
5376  newoptions = tor_malloc_zero(sizeof(or_options_t));
5377  newoptions->magic_ = OR_OPTIONS_MAGIC;
5378  options_init(newoptions);
5379  newoptions->command = command;
5380  newoptions->command_arg = command_arg ? tor_strdup(command_arg) : NULL;
5381
5382  smartlist_t *opened_files = smartlist_new();
5383  for (int i = 0; i < 2; ++i) {
5384    const char *body = i==0 ? cf_defaults : cf;
5385    if (!body)
5386      continue;
5387
5388    /* get config lines, assign them */
5389    retval = config_get_lines_include(body, &cl, 1,
5390                                      body == cf ? &cf_has_include : NULL,
5391                                      opened_files);
5392    if (retval < 0) {
5393      err = SETOPT_ERR_PARSE;
5394      goto err;
5395    }
5396    retval = config_assign(&options_format, newoptions, cl,
5397                           CAL_WARN_DEPRECATIONS, msg);
5398    config_free_lines(cl);
5399    if (retval < 0) {
5400      err = SETOPT_ERR_PARSE;
5401      goto err;
5402    }
5403    if (i==0)
5404      newdefaultoptions = config_dup(&options_format, newoptions);
5405  }
5406
5407  if (newdefaultoptions == NULL) {
5408    newdefaultoptions = config_dup(&options_format, global_default_options);
5409  }
5410
5411  /* Go through command-line variables too */
5412  retval = config_assign(&options_format, newoptions,
5413                         global_cmdline_options, CAL_WARN_DEPRECATIONS, msg);
5414  if (retval < 0) {
5415    err = SETOPT_ERR_PARSE;
5416    goto err;
5417  }
5418
5419  newoptions->IncludeUsed = cf_has_include;
5420  newoptions->FilesOpenedByIncludes = opened_files;
5421
5422  /* If this is a testing network configuration, change defaults
5423   * for a list of dependent config options, re-initialize newoptions
5424   * with the new defaults, and assign all options to it second time. */
5425  if (newoptions->TestingTorNetwork) {
5426    /* XXXX this is a bit of a kludge.  perhaps there's a better way to do
5427     * this?  We could, for example, make the parsing algorithm do two passes
5428     * over the configuration.  If it finds any "suite" options like
5429     * TestingTorNetwork, it could change the defaults before its second pass.
5430     * Not urgent so long as this seems to work, but at any sign of trouble,
5431     * let's clean it up.  -NM */
5432
5433    /* Change defaults. */
5434    for (int i = 0; testing_tor_network_defaults[i].name; ++i) {
5435      const config_var_t *new_var = &testing_tor_network_defaults[i];
5436      config_var_t *old_var =
5437          config_find_option_mutable(&options_format, new_var->name);
5438      tor_assert(new_var);
5439      tor_assert(old_var);
5440      old_var->initvalue = new_var->initvalue;
5441
5442      if ((config_find_deprecation(&options_format, new_var->name))) {
5443        log_warn(LD_GENERAL, "Testing options override the deprecated "
5444                 "option %s. Is that intentional?",
5445                 new_var->name);
5446      }
5447    }
5448
5449    /* Clear newoptions and re-initialize them with new defaults. */
5450    or_options_free(newoptions);
5451    or_options_free(newdefaultoptions);
5452    newdefaultoptions = NULL;
5453    newoptions = tor_malloc_zero(sizeof(or_options_t));
5454    newoptions->magic_ = OR_OPTIONS_MAGIC;
5455    options_init(newoptions);
5456    newoptions->command = command;
5457    newoptions->command_arg = command_arg ? tor_strdup(command_arg) : NULL;
5458
5459    /* Assign all options a second time. */
5460    opened_files = smartlist_new();
5461    for (int i = 0; i < 2; ++i) {
5462      const char *body = i==0 ? cf_defaults : cf;
5463      if (!body)
5464        continue;
5465
5466      /* get config lines, assign them */
5467      retval = config_get_lines_include(body, &cl, 1,
5468                                        body == cf ? &cf_has_include : NULL,
5469                                        opened_files);
5470      if (retval < 0) {
5471        err = SETOPT_ERR_PARSE;
5472        goto err;
5473      }
5474      retval = config_assign(&options_format, newoptions, cl, 0, msg);
5475      config_free_lines(cl);
5476      if (retval < 0) {
5477        err = SETOPT_ERR_PARSE;
5478        goto err;
5479      }
5480      if (i==0)
5481        newdefaultoptions = config_dup(&options_format, newoptions);
5482    }
5483    /* Assign command-line variables a second time too */
5484    retval = config_assign(&options_format, newoptions,
5485                           global_cmdline_options, 0, msg);
5486    if (retval < 0) {
5487      err = SETOPT_ERR_PARSE;
5488      goto err;
5489    }
5490  }
5491
5492  newoptions->IncludeUsed = cf_has_include;
5493  in_option_validation = 1;
5494  newoptions->FilesOpenedByIncludes = opened_files;
5495
5496  /* Validate newoptions */
5497  if (options_validate(oldoptions, newoptions, newdefaultoptions,
5498                       0, msg) < 0) {
5499    err = SETOPT_ERR_PARSE; /*XXX make this a separate return value.*/
5500    goto err;
5501  }
5502
5503  if (options_transition_allowed(oldoptions, newoptions, msg) < 0) {
5504    err = SETOPT_ERR_TRANSITION;
5505    goto err;
5506  }
5507  in_option_validation = 0;
5508
5509  if (set_options(newoptions, msg)) {
5510    err = SETOPT_ERR_SETTING;
5511    goto err; /* frees and replaces old options */
5512  }
5513
5514  or_options_free(global_default_options);
5515  global_default_options = newdefaultoptions;
5516
5517  return SETOPT_OK;
5518
5519 err:
5520  in_option_validation = 0;
5521  if (opened_files) {
5522    SMARTLIST_FOREACH(opened_files, char *, f, tor_free(f));
5523    smartlist_free(opened_files);
5524  }
5525  // may have been set to opened_files, avoid double free
5526  newoptions->FilesOpenedByIncludes = NULL;
5527  or_options_free(newoptions);
5528  or_options_free(newdefaultoptions);
5529  if (*msg) {
5530    char *old_msg = *msg;
5531    tor_asprintf(msg, "Failed to parse/validate config: %s", old_msg);
5532    tor_free(old_msg);
5533  }
5534  return err;
5535}
5536
5537/** Return the location for our configuration file.  May return NULL.
5538 */
5539const char *
5540get_torrc_fname(int defaults_fname)
5541{
5542  const char *fname = defaults_fname ? torrc_defaults_fname : torrc_fname;
5543
5544  if (fname)
5545    return fname;
5546  else
5547    return get_default_conf_file(defaults_fname);
5548}
5549
5550/** Adjust the address map based on the MapAddress elements in the
5551 * configuration <b>options</b>
5552 */
5553void
5554config_register_addressmaps(const or_options_t *options)
5555{
5556  smartlist_t *elts;
5557  config_line_t *opt;
5558  const char *from, *to, *msg;
5559
5560  addressmap_clear_configured();
5561  elts = smartlist_new();
5562  for (opt = options->AddressMap; opt; opt = opt->next) {
5563    smartlist_split_string(elts, opt->value, NULL,
5564                           SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
5565    if (smartlist_len(elts) < 2) {
5566      log_warn(LD_CONFIG,"MapAddress '%s' has too few arguments. Ignoring.",
5567               opt->value);
5568      goto cleanup;
5569    }
5570
5571    from = smartlist_get(elts,0);
5572    to = smartlist_get(elts,1);
5573
5574    if (to[0] == '.' || from[0] == '.') {
5575      log_warn(LD_CONFIG,"MapAddress '%s' is ambiguous - address starts with a"
5576              "'.'. Ignoring.",opt->value);
5577      goto cleanup;
5578    }
5579
5580    if (addressmap_register_auto(from, to, 0, ADDRMAPSRC_TORRC, &msg) < 0) {
5581      log_warn(LD_CONFIG,"MapAddress '%s' failed: %s. Ignoring.", opt->value,
5582               msg);
5583      goto cleanup;
5584    }
5585
5586    if (smartlist_len(elts) > 2)
5587      log_warn(LD_CONFIG,"Ignoring extra arguments to MapAddress.");
5588
5589  cleanup:
5590    SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
5591    smartlist_clear(elts);
5592  }
5593  smartlist_free(elts);
5594}
5595
5596/** As addressmap_register(), but detect the wildcarded status of "from" and
5597 * "to", and do not steal a reference to <b>to</b>. */
5598/* XXXX move to connection_edge.c */
5599int
5600addressmap_register_auto(const char *from, const char *to,
5601                         time_t expires,
5602                         addressmap_entry_source_t addrmap_source,
5603                         const char **msg)
5604{
5605  int from_wildcard = 0, to_wildcard = 0;
5606
5607  *msg = "whoops, forgot the error message";
5608
5609  if (!strcmp(to, "*") || !strcmp(from, "*")) {
5610    *msg = "can't remap from or to *";
5611    return -1;
5612  }
5613  /* Detect asterisks in expressions of type: '*.example.com' */
5614  if (!strncmp(from,"*.",2)) {
5615    from += 2;
5616    from_wildcard = 1;
5617  }
5618  if (!strncmp(to,"*.",2)) {
5619    to += 2;
5620    to_wildcard = 1;
5621  }
5622
5623  if (to_wildcard && !from_wildcard) {
5624    *msg =  "can only use wildcard (i.e. '*.') if 'from' address "
5625      "uses wildcard also";
5626    return -1;
5627  }
5628
5629  if (address_is_invalid_destination(to, 1)) {
5630    *msg = "destination is invalid";
5631    return -1;
5632  }
5633
5634  addressmap_register(from, tor_strdup(to), expires, addrmap_source,
5635                      from_wildcard, to_wildcard);
5636
5637  return 0;
5638}
5639
5640/**
5641 * Initialize the logs based on the configuration file.
5642 */
5643static int
5644options_init_logs(const or_options_t *old_options, or_options_t *options,
5645                  int validate_only)
5646{
5647  config_line_t *opt;
5648  int ok;
5649  smartlist_t *elts;
5650  int run_as_daemon =
5651#ifdef _WIN32
5652               0;
5653#else
5654               options->RunAsDaemon;
5655#endif
5656
5657  if (options->LogTimeGranularity <= 0) {
5658    log_warn(LD_CONFIG, "Log time granularity '%d' has to be positive.",
5659             options->LogTimeGranularity);
5660    return -1;
5661  } else if (1000 % options->LogTimeGranularity != 0 &&
5662             options->LogTimeGranularity % 1000 != 0) {
5663    int granularity = options->LogTimeGranularity;
5664    if (granularity < 40) {
5665      do granularity++;
5666      while (1000 % granularity != 0);
5667    } else if (granularity < 1000) {
5668      granularity = 1000 / granularity;
5669      while (1000 % granularity != 0)
5670        granularity--;
5671      granularity = 1000 / granularity;
5672    } else {
5673      granularity = 1000 * ((granularity / 1000) + 1);
5674    }
5675    log_warn(LD_CONFIG, "Log time granularity '%d' has to be either a "
5676                        "divisor or a multiple of 1 second. Changing to "
5677                        "'%d'.",
5678             options->LogTimeGranularity, granularity);
5679    if (!validate_only)
5680      set_log_time_granularity(granularity);
5681  } else {
5682    if (!validate_only)
5683      set_log_time_granularity(options->LogTimeGranularity);
5684  }
5685
5686  ok = 1;
5687  elts = smartlist_new();
5688
5689  for (opt = options->Logs; opt; opt = opt->next) {
5690    log_severity_list_t *severity;
5691    const char *cfg = opt->value;
5692    severity = tor_malloc_zero(sizeof(log_severity_list_t));
5693    if (parse_log_severity_config(&cfg, severity) < 0) {
5694      log_warn(LD_CONFIG, "Couldn't parse log levels in Log option 'Log %s'",
5695               opt->value);
5696      ok = 0; goto cleanup;
5697    }
5698
5699    smartlist_split_string(elts, cfg, NULL,
5700                           SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
5701
5702    if (smartlist_len(elts) == 0)
5703      smartlist_add_strdup(elts, "stdout");
5704
5705    if (smartlist_len(elts) == 1 &&
5706        (!strcasecmp(smartlist_get(elts,0), "stdout") ||
5707         !strcasecmp(smartlist_get(elts,0), "stderr"))) {
5708      int err = smartlist_len(elts) &&
5709        !strcasecmp(smartlist_get(elts,0), "stderr");
5710      if (!validate_only) {
5711        if (run_as_daemon) {
5712          log_warn(LD_CONFIG,
5713                   "Can't log to %s with RunAsDaemon set; skipping stdout",
5714                   err?"stderr":"stdout");
5715        } else {
5716          add_stream_log(severity, err?"<stderr>":"<stdout>",
5717                         fileno(err?stderr:stdout));
5718        }
5719      }
5720      goto cleanup;
5721    }
5722    if (smartlist_len(elts) == 1) {
5723      if (!strcasecmp(smartlist_get(elts,0), "syslog")) {
5724#ifdef HAVE_SYSLOG_H
5725        if (!validate_only) {
5726          add_syslog_log(severity, options->SyslogIdentityTag);
5727        }
5728#else
5729        log_warn(LD_CONFIG, "Syslog is not supported on this system. Sorry.");
5730#endif /* defined(HAVE_SYSLOG_H) */
5731        goto cleanup;
5732      }
5733
5734      if (!strcasecmp(smartlist_get(elts, 0), "android")) {
5735#ifdef HAVE_ANDROID_LOG_H
5736        if (!validate_only) {
5737          add_android_log(severity, options->AndroidIdentityTag);
5738        }
5739#else
5740        log_warn(LD_CONFIG, "Android logging is not supported"
5741                            " on this system. Sorry.");
5742#endif // HAVE_ANDROID_LOG_H.
5743        goto cleanup;
5744      }
5745    }
5746
5747    if (smartlist_len(elts) == 2 &&
5748        !strcasecmp(smartlist_get(elts,0), "file")) {
5749      if (!validate_only) {
5750        char *fname = expand_filename(smartlist_get(elts, 1));
5751        /* Truncate if TruncateLogFile is set and we haven't seen this option
5752           line before. */
5753        int truncate_log = 0;
5754        if (options->TruncateLogFile) {
5755          truncate_log = 1;
5756          if (old_options) {
5757            config_line_t *opt2;
5758            for (opt2 = old_options->Logs; opt2; opt2 = opt2->next)
5759              if (!strcmp(opt->value, opt2->value)) {
5760                truncate_log = 0;
5761                break;
5762              }
5763          }
5764        }
5765        if (add_file_log(severity, fname, truncate_log) < 0) {
5766          log_warn(LD_CONFIG, "Couldn't open file for 'Log %s': %s",
5767                   opt->value, strerror(errno));
5768          ok = 0;
5769        }
5770        tor_free(fname);
5771      }
5772      goto cleanup;
5773    }
5774
5775    log_warn(LD_CONFIG, "Bad syntax on file Log option 'Log %s'",
5776             opt->value);
5777    ok = 0; goto cleanup;
5778
5779  cleanup:
5780    SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
5781    smartlist_clear(elts);
5782    tor_free(severity);
5783  }
5784  smartlist_free(elts);
5785
5786  if (ok && !validate_only)
5787    logs_set_domain_logging(options->LogMessageDomains);
5788
5789  return ok?0:-1;
5790}
5791
5792/** Given a smartlist of SOCKS arguments to be passed to a transport
5793 *  proxy in <b>args</b>, validate them and return -1 if they are
5794 *  corrupted. Return 0 if they seem OK. */
5795static int
5796validate_transport_socks_arguments(const smartlist_t *args)
5797{
5798  char *socks_string = NULL;
5799  size_t socks_string_len;
5800
5801  tor_assert(args);
5802  tor_assert(smartlist_len(args) > 0);
5803
5804  SMARTLIST_FOREACH_BEGIN(args, const char *, s) {
5805    if (!string_is_key_value(LOG_WARN, s)) { /* items should be k=v items */
5806      log_warn(LD_CONFIG, "'%s' is not a k=v item.", s);
5807      return -1;
5808    }
5809  } SMARTLIST_FOREACH_END(s);
5810
5811  socks_string = pt_stringify_socks_args(args);
5812  if (!socks_string)
5813    return -1;
5814
5815  socks_string_len = strlen(socks_string);
5816  tor_free(socks_string);
5817
5818  if (socks_string_len > MAX_SOCKS5_AUTH_SIZE_TOTAL) {
5819    log_warn(LD_CONFIG, "SOCKS arguments can't be more than %u bytes (%lu).",
5820             MAX_SOCKS5_AUTH_SIZE_TOTAL,
5821             (unsigned long) socks_string_len);
5822    return -1;
5823  }
5824
5825  return 0;
5826}
5827
5828/** Deallocate a bridge_line_t structure. */
5829/* private */ void
5830bridge_line_free_(bridge_line_t *bridge_line)
5831{
5832  if (!bridge_line)
5833    return;
5834
5835  if (bridge_line->socks_args) {
5836    SMARTLIST_FOREACH(bridge_line->socks_args, char*, s, tor_free(s));
5837    smartlist_free(bridge_line->socks_args);
5838  }
5839  tor_free(bridge_line->transport_name);
5840  tor_free(bridge_line);
5841}
5842
5843/** Parse the contents of a string, <b>line</b>, containing a Bridge line,
5844 * into a bridge_line_t.
5845 *
5846 * Validates that the IP:PORT, fingerprint, and SOCKS arguments (given to the
5847 * Pluggable Transport, if a one was specified) are well-formed.
5848 *
5849 * Returns NULL If the Bridge line could not be validated, and returns a
5850 * bridge_line_t containing the parsed information otherwise.
5851 *
5852 * Bridge line format:
5853 * Bridge [transport] IP:PORT [id-fingerprint] [k=v] [k=v] ...
5854 */
5855/* private */ bridge_line_t *
5856parse_bridge_line(const char *line)
5857{
5858  smartlist_t *items = NULL;
5859  char *addrport=NULL, *fingerprint=NULL;
5860  char *field=NULL;
5861  bridge_line_t *bridge_line = tor_malloc_zero(sizeof(bridge_line_t));
5862
5863  items = smartlist_new();
5864  smartlist_split_string(items, line, NULL,
5865                         SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5866  if (smartlist_len(items) < 1) {
5867    log_warn(LD_CONFIG, "Too few arguments to Bridge line.");
5868    goto err;
5869  }
5870
5871  /* first field is either a transport name or addrport */
5872  field = smartlist_get(items, 0);
5873  smartlist_del_keeporder(items, 0);
5874
5875  if (string_is_C_identifier(field)) {
5876    /* It's a transport name. */
5877    bridge_line->transport_name = field;
5878    if (smartlist_len(items) < 1) {
5879      log_warn(LD_CONFIG, "Too few items to Bridge line.");
5880      goto err;
5881    }
5882    addrport = smartlist_get(items, 0); /* Next field is addrport then. */
5883    smartlist_del_keeporder(items, 0);
5884  } else {
5885    addrport = field;
5886  }
5887
5888  if (tor_addr_port_parse(LOG_INFO, addrport,
5889                          &bridge_line->addr, &bridge_line->port, 443)<0) {
5890    log_warn(LD_CONFIG, "Error parsing Bridge address '%s'", addrport);
5891    goto err;
5892  }
5893
5894  /* If transports are enabled, next field could be a fingerprint or a
5895     socks argument. If transports are disabled, next field must be
5896     a fingerprint. */
5897  if (smartlist_len(items)) {
5898    if (bridge_line->transport_name) { /* transports enabled: */
5899      field = smartlist_get(items, 0);
5900      smartlist_del_keeporder(items, 0);
5901
5902      /* If it's a key=value pair, then it's a SOCKS argument for the
5903         transport proxy... */
5904      if (string_is_key_value(LOG_DEBUG, field)) {
5905        bridge_line->socks_args = smartlist_new();
5906        smartlist_add(bridge_line->socks_args, field);
5907      } else { /* ...otherwise, it's the bridge fingerprint. */
5908        fingerprint = field;
5909      }
5910
5911    } else { /* transports disabled: */
5912      fingerprint = smartlist_join_strings(items, "", 0, NULL);
5913    }
5914  }
5915
5916  /* Handle fingerprint, if it was provided. */
5917  if (fingerprint) {
5918    if (strlen(fingerprint) != HEX_DIGEST_LEN) {
5919      log_warn(LD_CONFIG, "Key digest for Bridge is wrong length.");
5920      goto err;
5921    }
5922    if (base16_decode(bridge_line->digest, DIGEST_LEN,
5923                      fingerprint, HEX_DIGEST_LEN) != DIGEST_LEN) {
5924      log_warn(LD_CONFIG, "Unable to decode Bridge key digest.");
5925      goto err;
5926    }
5927  }
5928
5929  /* If we are using transports, any remaining items in the smartlist
5930     should be k=v values. */
5931  if (bridge_line->transport_name && smartlist_len(items)) {
5932    if (!bridge_line->socks_args)
5933      bridge_line->socks_args = smartlist_new();
5934
5935    /* append remaining items of 'items' to 'socks_args' */
5936    smartlist_add_all(bridge_line->socks_args, items);
5937    smartlist_clear(items);
5938
5939    tor_assert(smartlist_len(bridge_line->socks_args) > 0);
5940  }
5941
5942  if (bridge_line->socks_args) {
5943    if (validate_transport_socks_arguments(bridge_line->socks_args) < 0)
5944      goto err;
5945  }
5946
5947  goto done;
5948
5949 err:
5950  bridge_line_free(bridge_line);
5951  bridge_line = NULL;
5952
5953 done:
5954  SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5955  smartlist_free(items);
5956  tor_free(addrport);
5957  tor_free(fingerprint);
5958
5959  return bridge_line;
5960}
5961
5962/** Read the contents of a ClientTransportPlugin or ServerTransportPlugin
5963 * line from <b>line</b>, depending on the value of <b>server</b>. Return 0
5964 * if the line is well-formed, and -1 if it isn't.
5965 *
5966 * If <b>validate_only</b> is 0, the line is well-formed, and the transport is
5967 * needed by some bridge:
5968 * - If it's an external proxy line, add the transport described in the line to
5969 * our internal transport list.
5970 * - If it's a managed proxy line, launch the managed proxy.
5971 */
5972
5973STATIC int
5974parse_transport_line(const or_options_t *options,
5975                     const char *line, int validate_only,
5976                     int server)
5977{
5978
5979  smartlist_t *items = NULL;
5980  int r;
5981  const char *transports = NULL;
5982  smartlist_t *transport_list = NULL;
5983  char *type = NULL;
5984  char *addrport = NULL;
5985  tor_addr_t addr;
5986  uint16_t port = 0;
5987  int socks_ver = PROXY_NONE;
5988
5989  /* managed proxy options */
5990  int is_managed = 0;
5991  char **proxy_argv = NULL;
5992  char **tmp = NULL;
5993  int proxy_argc, i;
5994  int is_useless_proxy = 1;
5995
5996  int line_length;
5997
5998  /* Split the line into space-separated tokens */
5999  items = smartlist_new();
6000  smartlist_split_string(items, line, NULL,
6001                         SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
6002  line_length = smartlist_len(items);
6003
6004  if (line_length < 3) {
6005    log_warn(LD_CONFIG,
6006             "Too few arguments on %sTransportPlugin line.",
6007             server ? "Server" : "Client");
6008    goto err;
6009  }
6010
6011  /* Get the first line element, split it to commas into
6012     transport_list (in case it's multiple transports) and validate
6013     the transport names. */
6014  transports = smartlist_get(items, 0);
6015  transport_list = smartlist_new();
6016  smartlist_split_string(transport_list, transports, ",",
6017                         SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
6018  SMARTLIST_FOREACH_BEGIN(transport_list, const char *, transport_name) {
6019    /* validate transport names */
6020    if (!string_is_C_identifier(transport_name)) {
6021      log_warn(LD_CONFIG, "Transport name is not a C identifier (%s).",
6022               transport_name);
6023      goto err;
6024    }
6025
6026    /* see if we actually need the transports provided by this proxy */
6027    if (!validate_only && transport_is_needed(transport_name))
6028      is_useless_proxy = 0;
6029  } SMARTLIST_FOREACH_END(transport_name);
6030
6031  type = smartlist_get(items, 1);
6032  if (!strcmp(type, "exec")) {
6033    is_managed = 1;
6034  } else if (server && !strcmp(type, "proxy")) {
6035    /* 'proxy' syntax only with ServerTransportPlugin */
6036    is_managed = 0;
6037  } else if (!server && !strcmp(type, "socks4")) {
6038    /* 'socks4' syntax only with ClientTransportPlugin */
6039    is_managed = 0;
6040    socks_ver = PROXY_SOCKS4;
6041  } else if (!server && !strcmp(type, "socks5")) {
6042    /* 'socks5' syntax only with ClientTransportPlugin */
6043    is_managed = 0;
6044    socks_ver = PROXY_SOCKS5;
6045  } else {
6046    log_warn(LD_CONFIG,
6047             "Strange %sTransportPlugin type '%s'",
6048             server ? "Server" : "Client", type);
6049    goto err;
6050  }
6051
6052  if (is_managed && options->Sandbox) {
6053    log_warn(LD_CONFIG,
6054             "Managed proxies are not compatible with Sandbox mode."
6055             "(%sTransportPlugin line was %s)",
6056             server ? "Server" : "Client", escaped(line));
6057    goto err;
6058  }
6059
6060  if (is_managed && options->NoExec) {
6061    log_warn(LD_CONFIG,
6062             "Managed proxies are not compatible with NoExec mode; ignoring."
6063             "(%sTransportPlugin line was %s)",
6064             server ? "Server" : "Client", escaped(line));
6065    r = 0;
6066    goto done;
6067  }
6068
6069  if (is_managed) {
6070    /* managed */
6071
6072    if (!server && !validate_only && is_useless_proxy) {
6073      log_info(LD_GENERAL,
6074               "Pluggable transport proxy (%s) does not provide "
6075               "any needed transports and will not be launched.",
6076               line);
6077    }
6078
6079