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