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