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