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