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