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