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