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