Rename dirclient_modes.h identifiers to start with dirclient_
[tor.git] / src / app / config / config.c
blob9a5bb5265f2a357eb1d33fcc266f774ff994fbe1
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 */
7 /**
8 * \file config.c
9 * \brief Code to interpret the user's configuration of Tor.
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.
17 * The module additionally has some tools for manipulating and
18 * inspecting values that are calculated as a result of the
19 * configured options.
21 * <h3>How to add new options</h3>
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>
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>
53 * <h3>Changing the value of an option</h3>
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 **/
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"
71 #include "core/mainloop/connection.h"
72 #include "core/mainloop/mainloop.h"
73 #include "core/mainloop/netstatus.h"
74 #include "core/or/channel.h"
75 #include "core/or/circuitlist.h"
76 #include "core/or/circuitmux.h"
77 #include "core/or/circuitmux_ewma.h"
78 #include "core/or/circuitstats.h"
79 #include "core/or/connection_edge.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"
84 #include "feature/client/addressmap.h"
85 #include "feature/client/bridges.h"
86 #include "feature/client/entrynodes.h"
87 #include "feature/client/transports.h"
88 #include "feature/control/control.h"
89 #include "feature/control/control_auth.h"
90 #include "feature/control/control_events.h"
91 #include "feature/dirclient/dirclient_modes.h"
92 #include "feature/hibernate/hibernate.h"
93 #include "feature/hs/hs_config.h"
94 #include "feature/nodelist/dirlist.h"
95 #include "feature/nodelist/networkstatus.h"
96 #include "feature/nodelist/nickname.h"
97 #include "feature/nodelist/nodelist.h"
98 #include "feature/nodelist/routerlist.h"
99 #include "feature/nodelist/routerset.h"
100 #include "feature/relay/dns.h"
101 #include "feature/relay/ext_orport.h"
102 #include "feature/relay/routermode.h"
103 #include "feature/relay/relay_config.h"
104 #include "feature/relay/transport_config.h"
105 #include "feature/rend/rendclient.h"
106 #include "feature/rend/rendservice.h"
107 #include "lib/geoip/geoip.h"
108 #include "feature/stats/geoip_stats.h"
109 #include "lib/compress/compress.h"
110 #include "lib/confmgt/structvar.h"
111 #include "lib/crypt_ops/crypto_init.h"
112 #include "lib/crypt_ops/crypto_rand.h"
113 #include "lib/crypt_ops/crypto_util.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"
119 #ifdef ENABLE_NSS
120 #include "lib/crypt_ops/crypto_nss_mgt.h"
121 #else
122 #include "lib/crypt_ops/crypto_openssl_mgt.h"
123 #endif
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
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"
151 #include "lib/encoding/keyval.h"
152 #include "lib/fs/conffile.h"
153 #include "lib/evloop/procmon.h"
155 #include "feature/dirauth/authmode.h"
156 #include "feature/dirauth/dirauth_config.h"
158 #include "core/or/connection_st.h"
159 #include "core/or/port_cfg_st.h"
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.
166 # define __INCLUDE_LEVEL__ 2
167 #endif /* defined(__COVERITY__) && !defined(__INCLUDE_LEVEL__) */
168 #include <systemd/sd-daemon.h>
169 #endif /* defined(HAVE_SYSTEMD) */
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:\"";
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 */
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) */
190 /** A list of abbreviations and aliases to map command-line options, obsolete
191 * option names, or alternative option names, to their current values. */
192 static const config_abbrev_t option_abbrevs_[] = {
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 },
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),
248 { NULL, NULL, 0, 0},
251 /** dummy instance of or_options_t, used for type-checking its
252 * members with CONF_CHECK_VAR_TYPE. */
253 DUMMY_TYPECHECK_INSTANCE(or_options_t);
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>"
259 #define VAR(varname,conftype,member,initvalue) \
260 CONFIG_VAR_ETYPE(or_options_t, varname, conftype, member, 0, initvalue)
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)
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)
276 #define V(member,conftype,initvalue) \
277 VAR(#member, conftype, member, initvalue)
279 #define VAR_IMMUTABLE(varname, conftype, member, initvalue) \
280 CONFIG_VAR_ETYPE(or_options_t, varname, conftype, member, \
281 CFLG_IMMUTABLE, initvalue)
283 #define V_IMMUTABLE(member,conftype,initvalue) \
284 VAR_IMMUTABLE(#member, conftype, member, initvalue)
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)
290 /** An entry for config_vars: "The option <b>varname</b> is obsolete." */
291 #define OBSOLETE(varname) CONFIG_VAR_OBSOLETE(varname)
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.
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)
305 /** UINT64_MAX as a decimal string */
306 #define UINT64_MAX_STRING "18446744073709551615"
308 /** Array of configuration options. Until we disallow nonstandard
309 * abbreviations, order is significant, since the first matching option will
310 * be chosen first.
312 static const config_var_t option_vars_[] = {
313 V(AccountingMax, MEMUNIT, "0 bytes"),
314 VAR("AccountingRule", STRING, AccountingRule_option, "max"),
315 V(AccountingStart, STRING, NULL),
316 V(Address, STRING, NULL),
317 OBSOLETE("AllowDotExit"),
318 OBSOLETE("AllowInvalidNodes"),
319 V(AllowNonRFC953Hostnames, BOOL, "0"),
320 OBSOLETE("AllowSingleHopCircuits"),
321 OBSOLETE("AllowSingleHopExits"),
322 V(AlternateBridgeAuthority, LINELIST, NULL),
323 V(AlternateDirAuthority, LINELIST, NULL),
324 OBSOLETE("AlternateHSAuthority"),
325 V(AssumeReachable, BOOL, "0"),
326 OBSOLETE("AuthDirBadDir"),
327 OBSOLETE("AuthDirBadDirCCs"),
328 V(AuthDirBadExit, LINELIST, NULL),
329 V(AuthDirBadExitCCs, CSV, ""),
330 V(AuthDirInvalid, LINELIST, NULL),
331 V(AuthDirInvalidCCs, CSV, ""),
332 V(AuthDirFastGuarantee, MEMUNIT, "100 KB"),
333 V(AuthDirGuardBWGuarantee, MEMUNIT, "2 MB"),
334 V(AuthDirPinKeys, BOOL, "1"),
335 V(AuthDirReject, LINELIST, NULL),
336 V(AuthDirRejectCCs, CSV, ""),
337 OBSOLETE("AuthDirRejectUnlisted"),
338 OBSOLETE("AuthDirListBadDirs"),
339 V(AuthDirListBadExits, BOOL, "0"),
340 OBSOLETE("AuthDirMaxServersPerAuthAddr"),
341 V(AuthDirHasIPv6Connectivity, BOOL, "0"),
342 VAR("AuthoritativeDirectory", BOOL, AuthoritativeDir, "0"),
343 V(AutomapHostsOnResolve, BOOL, "0"),
344 V(AutomapHostsSuffixes, CSV, ".onion,.exit"),
345 V(AvoidDiskWrites, BOOL, "0"),
346 V(BandwidthBurst, MEMUNIT, "1 GB"),
347 V(BandwidthRate, MEMUNIT, "1 GB"),
348 V(BridgeAuthoritativeDir, BOOL, "0"),
349 VAR("Bridge", LINELIST, Bridges, NULL),
350 V(BridgePassword, STRING, NULL),
351 V(BridgeRecordUsageByCountry, BOOL, "1"),
352 V(BridgeRelay, BOOL, "0"),
353 V(BridgeDistribution, STRING, NULL),
354 VAR_IMMUTABLE("CacheDirectory",FILENAME, CacheDirectory_option, NULL),
355 V(CacheDirectoryGroupReadable, AUTOBOOL, "auto"),
356 V(CellStatistics, BOOL, "0"),
357 V(PaddingStatistics, BOOL, "1"),
358 V(LearnCircuitBuildTimeout, BOOL, "1"),
359 V(CircuitBuildTimeout, INTERVAL, "0"),
360 OBSOLETE("CircuitIdleTimeout"),
361 V(CircuitsAvailableTimeout, INTERVAL, "0"),
362 V(CircuitStreamTimeout, INTERVAL, "0"),
363 V(CircuitPriorityHalflife, DOUBLE, "-1.0"), /*negative:'Use default'*/
364 V(ClientDNSRejectInternalAddresses, BOOL,"1"),
365 #if defined(HAVE_MODULE_RELAY) || defined(TOR_UNIT_TESTS)
366 /* The unit tests expect the ClientOnly default to be 0. */
367 V(ClientOnly, BOOL, "0"),
368 #else
369 /* We must be a Client if the relay module is disabled. */
370 V(ClientOnly, BOOL, "1"),
371 #endif /* defined(HAVE_MODULE_RELAY) || defined(TOR_UNIT_TESTS) */
372 V(ClientPreferIPv6ORPort, AUTOBOOL, "auto"),
373 V(ClientPreferIPv6DirPort, AUTOBOOL, "auto"),
374 V(ClientAutoIPv6ORPort, BOOL, "0"),
375 V(ClientRejectInternalAddresses, BOOL, "1"),
376 V(ClientTransportPlugin, LINELIST, NULL),
377 V(ClientUseIPv6, BOOL, "0"),
378 V(ClientUseIPv4, BOOL, "1"),
379 V(ConsensusParams, STRING, NULL),
380 V(ConnLimit, POSINT, "1000"),
381 V(ConnDirectionStatistics, BOOL, "0"),
382 V(ConstrainedSockets, BOOL, "0"),
383 V(ConstrainedSockSize, MEMUNIT, "8192"),
384 V(ContactInfo, STRING, NULL),
385 OBSOLETE("ControlListenAddress"),
386 VPORT(ControlPort),
387 V(ControlPortFileGroupReadable,BOOL, "0"),
388 V(ControlPortWriteToFile, FILENAME, NULL),
389 V(ControlSocket, LINELIST, NULL),
390 V(ControlSocketsGroupWritable, BOOL, "0"),
391 V(UnixSocksGroupWritable, BOOL, "0"),
392 V(CookieAuthentication, BOOL, "0"),
393 V(CookieAuthFileGroupReadable, BOOL, "0"),
394 V(CookieAuthFile, FILENAME, NULL),
395 V(CountPrivateBandwidth, BOOL, "0"),
396 VAR_IMMUTABLE("DataDirectory", FILENAME, DataDirectory_option, NULL),
397 V(DataDirectoryGroupReadable, BOOL, "0"),
398 V(DisableOOSCheck, BOOL, "1"),
399 V(DisableNetwork, BOOL, "0"),
400 V(DirAllowPrivateAddresses, BOOL, "0"),
401 V(TestingAuthDirTimeToLearnReachability, INTERVAL, "30 minutes"),
402 OBSOLETE("DirListenAddress"),
403 V(DirPolicy, LINELIST, NULL),
404 VPORT(DirPort),
405 V(DirPortFrontPage, FILENAME, NULL),
406 VAR("DirReqStatistics", BOOL, DirReqStatistics_option, "1"),
407 VAR("DirAuthority", LINELIST, DirAuthorities, NULL),
408 #if defined(HAVE_MODULE_RELAY) || defined(TOR_UNIT_TESTS)
409 /* The unit tests expect the DirCache default to be 1. */
410 V(DirCache, BOOL, "1"),
411 #else
412 /* We can't be a DirCache if the relay module is disabled. */
413 V(DirCache, BOOL, "0"),
414 #endif /* defined(HAVE_MODULE_RELAY) || defined(TOR_UNIT_TESTS) */
415 /* A DirAuthorityFallbackRate of 0.1 means that 0.5% of clients try an
416 * authority when all fallbacks are up, and 2% try an authority when 25% of
417 * fallbacks are down. (We rebuild the list when 25% of fallbacks are down).
419 * We want to reduce load on authorities, but keep these two figures within
420 * an order of magnitude, so there isn't too much load shifting to
421 * authorities when fallbacks go down. */
422 V(DirAuthorityFallbackRate, DOUBLE, "0.1"),
423 V_IMMUTABLE(DisableAllSwap, BOOL, "0"),
424 V_IMMUTABLE(DisableDebuggerAttachment, BOOL, "1"),
425 OBSOLETE("DisableIOCP"),
426 OBSOLETE("DisableV2DirectoryInfo_"),
427 OBSOLETE("DynamicDHGroups"),
428 VPORT(DNSPort),
429 OBSOLETE("DNSListenAddress"),
430 V(DormantClientTimeout, INTERVAL, "24 hours"),
431 V(DormantTimeoutDisabledByIdleStreams, BOOL, "1"),
432 V(DormantOnFirstStartup, BOOL, "0"),
433 V(DormantCanceledByStartup, BOOL, "0"),
434 /* DoS circuit creation options. */
435 V(DoSCircuitCreationEnabled, AUTOBOOL, "auto"),
436 V(DoSCircuitCreationMinConnections, POSINT, "0"),
437 V(DoSCircuitCreationRate, POSINT, "0"),
438 V(DoSCircuitCreationBurst, POSINT, "0"),
439 V(DoSCircuitCreationDefenseType, INT, "0"),
440 V(DoSCircuitCreationDefenseTimePeriod, INTERVAL, "0"),
441 /* DoS connection options. */
442 V(DoSConnectionEnabled, AUTOBOOL, "auto"),
443 V(DoSConnectionMaxConcurrentCount, POSINT, "0"),
444 V(DoSConnectionDefenseType, INT, "0"),
445 /* DoS single hop client options. */
446 V(DoSRefuseSingleHopClientRendezvous, AUTOBOOL, "auto"),
447 V(DownloadExtraInfo, BOOL, "0"),
448 V(TestingEnableConnBwEvent, BOOL, "0"),
449 V(TestingEnableCellStatsEvent, BOOL, "0"),
450 OBSOLETE("TestingEnableTbEmptyEvent"),
451 V(EnforceDistinctSubnets, BOOL, "1"),
452 V_D(EntryNodes, ROUTERSET, NULL),
453 V(EntryStatistics, BOOL, "0"),
454 OBSOLETE("TestingEstimatedDescriptorPropagationTime"),
455 V_D(ExcludeNodes, ROUTERSET, NULL),
456 V_D(ExcludeExitNodes, ROUTERSET, NULL),
457 OBSOLETE("ExcludeSingleHopRelays"),
458 V_D(ExitNodes, ROUTERSET, NULL),
459 /* Researchers need a way to tell their clients to use specific
460 * middles that they also control, to allow safe live-network
461 * experimentation with new padding machines. */
462 V_D(MiddleNodes, ROUTERSET, NULL),
463 V(ExitPolicy, LINELIST, NULL),
464 V(ExitPolicyRejectPrivate, BOOL, "1"),
465 V(ExitPolicyRejectLocalInterfaces, BOOL, "0"),
466 V(ExitPortStatistics, BOOL, "0"),
467 V(ExtendAllowPrivateAddresses, BOOL, "0"),
468 V(ExitRelay, AUTOBOOL, "auto"),
469 VPORT(ExtORPort),
470 V(ExtORPortCookieAuthFile, FILENAME, NULL),
471 V(ExtORPortCookieAuthFileGroupReadable, BOOL, "0"),
472 V(ExtraInfoStatistics, BOOL, "1"),
473 V(ExtendByEd25519ID, AUTOBOOL, "auto"),
474 V(FallbackDir, LINELIST, NULL),
476 V(UseDefaultFallbackDirs, BOOL, "1"),
478 OBSOLETE("FallbackNetworkstatusFile"),
479 V(FascistFirewall, BOOL, "0"),
480 V(FirewallPorts, CSV, ""),
481 OBSOLETE("FastFirstHopPK"),
482 V(FetchDirInfoEarly, BOOL, "0"),
483 V(FetchDirInfoExtraEarly, BOOL, "0"),
484 V(FetchServerDescriptors, BOOL, "1"),
485 V(FetchHidServDescriptors, BOOL, "1"),
486 V(FetchUselessDescriptors, BOOL, "0"),
487 OBSOLETE("FetchV2Networkstatus"),
488 V(GeoIPExcludeUnknown, AUTOBOOL, "auto"),
489 #ifdef _WIN32
490 V(GeoIPFile, FILENAME, "<default>"),
491 V(GeoIPv6File, FILENAME, "<default>"),
492 #else
493 V(GeoIPFile, FILENAME,
494 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip"),
495 V(GeoIPv6File, FILENAME,
496 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip6"),
497 #endif /* defined(_WIN32) */
498 OBSOLETE("Group"),
499 V(GuardLifetime, INTERVAL, "0 minutes"),
500 V(HeartbeatPeriod, INTERVAL, "6 hours"),
501 V(MainloopStats, BOOL, "0"),
502 V(HashedControlPassword, LINELIST, NULL),
503 OBSOLETE("HidServDirectoryV2"),
504 VAR("HiddenServiceDir", LINELIST_S, RendConfigLines, NULL),
505 VAR("HiddenServiceDirGroupReadable", LINELIST_S, RendConfigLines, NULL),
506 VAR("HiddenServiceOptions",LINELIST_V, RendConfigLines, NULL),
507 VAR("HiddenServicePort", LINELIST_S, RendConfigLines, NULL),
508 VAR("HiddenServiceVersion",LINELIST_S, RendConfigLines, NULL),
509 VAR("HiddenServiceAuthorizeClient",LINELIST_S,RendConfigLines, NULL),
510 VAR("HiddenServiceAllowUnknownPorts",LINELIST_S, RendConfigLines, NULL),
511 VAR("HiddenServiceMaxStreams",LINELIST_S, RendConfigLines, NULL),
512 VAR("HiddenServiceMaxStreamsCloseCircuit",LINELIST_S, RendConfigLines, NULL),
513 VAR("HiddenServiceNumIntroductionPoints", LINELIST_S, RendConfigLines, NULL),
514 VAR("HiddenServiceExportCircuitID", LINELIST_S, RendConfigLines, NULL),
515 VAR("HiddenServiceEnableIntroDoSDefense", LINELIST_S, RendConfigLines, NULL),
516 VAR("HiddenServiceEnableIntroDoSRatePerSec",
517 LINELIST_S, RendConfigLines, NULL),
518 VAR("HiddenServiceEnableIntroDoSBurstPerSec",
519 LINELIST_S, RendConfigLines, NULL),
520 VAR("HiddenServiceStatistics", BOOL, HiddenServiceStatistics_option, "1"),
521 V(HidServAuth, LINELIST, NULL),
522 V(ClientOnionAuthDir, FILENAME, NULL),
523 OBSOLETE("CloseHSClientCircuitsImmediatelyOnTimeout"),
524 OBSOLETE("CloseHSServiceRendCircuitsImmediatelyOnTimeout"),
525 V_IMMUTABLE(HiddenServiceSingleHopMode, BOOL, "0"),
526 V_IMMUTABLE(HiddenServiceNonAnonymousMode,BOOL, "0"),
527 V(HTTPProxy, STRING, NULL),
528 V(HTTPProxyAuthenticator, STRING, NULL),
529 V(HTTPSProxy, STRING, NULL),
530 V(HTTPSProxyAuthenticator, STRING, NULL),
531 VPORT(HTTPTunnelPort),
532 V(IPv6Exit, BOOL, "0"),
533 VAR("ServerTransportPlugin", LINELIST, ServerTransportPlugin, NULL),
534 V(ServerTransportListenAddr, LINELIST, NULL),
535 V(ServerTransportOptions, LINELIST, NULL),
536 V(SigningKeyLifetime, INTERVAL, "30 days"),
537 V(Socks4Proxy, STRING, NULL),
538 V(Socks5Proxy, STRING, NULL),
539 V(Socks5ProxyUsername, STRING, NULL),
540 V(Socks5ProxyPassword, STRING, NULL),
541 V(TCPProxy, STRING, NULL),
542 VAR_IMMUTABLE("KeyDirectory", FILENAME, KeyDirectory_option, NULL),
543 V(KeyDirectoryGroupReadable, AUTOBOOL, "auto"),
544 VAR_D("HSLayer2Nodes", ROUTERSET, HSLayer2Nodes, NULL),
545 VAR_D("HSLayer3Nodes", ROUTERSET, HSLayer3Nodes, NULL),
546 V(KeepalivePeriod, INTERVAL, "5 minutes"),
547 V_IMMUTABLE(KeepBindCapabilities, AUTOBOOL, "auto"),
548 VAR("Log", LINELIST, Logs, NULL),
549 V(LogMessageDomains, BOOL, "0"),
550 V(LogTimeGranularity, MSEC_INTERVAL, "1 second"),
551 V(TruncateLogFile, BOOL, "0"),
552 V_IMMUTABLE(SyslogIdentityTag, STRING, NULL),
553 V_IMMUTABLE(AndroidIdentityTag,STRING, NULL),
554 V(LongLivedPorts, CSV,
555 "21,22,706,1863,5050,5190,5222,5223,6523,6667,6697,8300"),
556 VAR("MapAddress", LINELIST, AddressMap, NULL),
557 V(MaxAdvertisedBandwidth, MEMUNIT, "1 GB"),
558 V(MaxCircuitDirtiness, INTERVAL, "10 minutes"),
559 V(MaxClientCircuitsPending, POSINT, "32"),
560 V(MaxConsensusAgeForDiffs, INTERVAL, "0 seconds"),
561 VAR("MaxMemInQueues", MEMUNIT, MaxMemInQueues_raw, "0"),
562 OBSOLETE("MaxOnionsPending"),
563 V(MaxOnionQueueDelay, MSEC_INTERVAL, "1750 msec"),
564 V(MaxUnparseableDescSizeToLog, MEMUNIT, "10 MB"),
565 V(MinMeasuredBWsForAuthToIgnoreAdvertised, INT, "500"),
566 VAR("MyFamily", LINELIST, MyFamily_lines, NULL),
567 V(NewCircuitPeriod, INTERVAL, "30 seconds"),
568 OBSOLETE("NamingAuthoritativeDirectory"),
569 OBSOLETE("NATDListenAddress"),
570 VPORT(NATDPort),
571 V(Nickname, STRING, NULL),
572 OBSOLETE("PredictedPortsRelevanceTime"),
573 OBSOLETE("WarnUnsafeSocks"),
574 VAR("NodeFamily", LINELIST, NodeFamilies, NULL),
575 V_IMMUTABLE(NoExec, BOOL, "0"),
576 V(NumCPUs, POSINT, "0"),
577 V(NumDirectoryGuards, POSINT, "0"),
578 V(NumEntryGuards, POSINT, "0"),
579 V(NumPrimaryGuards, POSINT, "0"),
580 V(OfflineMasterKey, BOOL, "0"),
581 OBSOLETE("ORListenAddress"),
582 VPORT(ORPort),
583 V(OutboundBindAddress, LINELIST, NULL),
584 V(OutboundBindAddressOR, LINELIST, NULL),
585 V(OutboundBindAddressExit, LINELIST, NULL),
587 OBSOLETE("PathBiasDisableRate"),
588 V(PathBiasCircThreshold, INT, "-1"),
589 V(PathBiasNoticeRate, DOUBLE, "-1"),
590 V(PathBiasWarnRate, DOUBLE, "-1"),
591 V(PathBiasExtremeRate, DOUBLE, "-1"),
592 V(PathBiasScaleThreshold, INT, "-1"),
593 OBSOLETE("PathBiasScaleFactor"),
594 OBSOLETE("PathBiasMultFactor"),
595 V(PathBiasDropGuards, AUTOBOOL, "0"),
596 OBSOLETE("PathBiasUseCloseCounts"),
598 V(PathBiasUseThreshold, INT, "-1"),
599 V(PathBiasNoticeUseRate, DOUBLE, "-1"),
600 V(PathBiasExtremeUseRate, DOUBLE, "-1"),
601 V(PathBiasScaleUseThreshold, INT, "-1"),
603 V(PathsNeededToBuildCircuits, DOUBLE, "-1"),
604 V(PerConnBWBurst, MEMUNIT, "0"),
605 V(PerConnBWRate, MEMUNIT, "0"),
606 V_IMMUTABLE(PidFile, FILENAME, NULL),
607 V_IMMUTABLE(TestingTorNetwork, BOOL, "0"),
608 V(TestingMinExitFlagThreshold, MEMUNIT, "0"),
609 V(TestingMinFastFlagThreshold, MEMUNIT, "0"),
611 V(TestingLinkCertLifetime, INTERVAL, "2 days"),
612 V(TestingAuthKeyLifetime, INTERVAL, "2 days"),
613 V(TestingLinkKeySlop, INTERVAL, "3 hours"),
614 V(TestingAuthKeySlop, INTERVAL, "3 hours"),
615 V(TestingSigningKeySlop, INTERVAL, "1 day"),
617 V(OptimisticData, AUTOBOOL, "auto"),
618 OBSOLETE("PortForwarding"),
619 OBSOLETE("PortForwardingHelper"),
620 OBSOLETE("PreferTunneledDirConns"),
621 V(ProtocolWarnings, BOOL, "0"),
622 V(PublishServerDescriptor, CSV, "1"),
623 V(PublishHidServDescriptors, BOOL, "1"),
624 V(ReachableAddresses, LINELIST, NULL),
625 V(ReachableDirAddresses, LINELIST, NULL),
626 V(ReachableORAddresses, LINELIST, NULL),
627 V(RecommendedVersions, LINELIST, NULL),
628 V(RecommendedClientVersions, LINELIST, NULL),
629 V(RecommendedServerVersions, LINELIST, NULL),
630 OBSOLETE("RecommendedPackages"),
631 V(ReducedConnectionPadding, BOOL, "0"),
632 V(ConnectionPadding, AUTOBOOL, "auto"),
633 V(RefuseUnknownExits, AUTOBOOL, "auto"),
634 V(CircuitPadding, BOOL, "1"),
635 V(ReducedCircuitPadding, BOOL, "0"),
636 V(RejectPlaintextPorts, CSV, ""),
637 V(RelayBandwidthBurst, MEMUNIT, "0"),
638 V(RelayBandwidthRate, MEMUNIT, "0"),
639 V(RendPostPeriod, INTERVAL, "1 hour"),
640 V(RephistTrackTime, INTERVAL, "24 hours"),
641 V_IMMUTABLE(RunAsDaemon, BOOL, "0"),
642 V(ReducedExitPolicy, BOOL, "0"),
643 OBSOLETE("RunTesting"), // currently unused
644 V_IMMUTABLE(Sandbox, BOOL, "0"),
645 V(SafeLogging, STRING, "1"),
646 V(SafeSocks, BOOL, "0"),
647 V(ServerDNSAllowBrokenConfig, BOOL, "1"),
648 V(ServerDNSAllowNonRFC953Hostnames, BOOL,"0"),
649 V(ServerDNSDetectHijacking, BOOL, "1"),
650 V(ServerDNSRandomizeCase, BOOL, "1"),
651 V(ServerDNSResolvConfFile, FILENAME, NULL),
652 V(ServerDNSSearchDomains, BOOL, "0"),
653 V(ServerDNSTestAddresses, CSV,
654 "www.google.com,www.mit.edu,www.yahoo.com,www.slashdot.org"),
655 OBSOLETE("SchedulerLowWaterMark__"),
656 OBSOLETE("SchedulerHighWaterMark__"),
657 OBSOLETE("SchedulerMaxFlushCells__"),
658 V(KISTSchedRunInterval, MSEC_INTERVAL, "0 msec"),
659 V(KISTSockBufSizeFactor, DOUBLE, "1.0"),
660 V(Schedulers, CSV, "KIST,KISTLite,Vanilla"),
661 V(ShutdownWaitLength, INTERVAL, "30 seconds"),
662 OBSOLETE("SocksListenAddress"),
663 V(SocksPolicy, LINELIST, NULL),
664 VPORT(SocksPort),
665 V(SocksTimeout, INTERVAL, "2 minutes"),
666 V(SSLKeyLifetime, INTERVAL, "0"),
667 OBSOLETE("StrictEntryNodes"),
668 OBSOLETE("StrictExitNodes"),
669 V(StrictNodes, BOOL, "0"),
670 OBSOLETE("Support022HiddenServices"),
671 V(TestSocks, BOOL, "0"),
672 V_IMMUTABLE(TokenBucketRefillInterval, MSEC_INTERVAL, "100 msec"),
673 OBSOLETE("Tor2webMode"),
674 OBSOLETE("Tor2webRendezvousPoints"),
675 OBSOLETE("TLSECGroup"),
676 V(TrackHostExits, CSV, NULL),
677 V(TrackHostExitsExpire, INTERVAL, "30 minutes"),
678 OBSOLETE("TransListenAddress"),
679 VPORT(TransPort),
680 V(TransProxyType, STRING, "default"),
681 OBSOLETE("TunnelDirConns"),
682 V(UpdateBridgesFromAuthority, BOOL, "0"),
683 V(UseBridges, BOOL, "0"),
684 VAR("UseEntryGuards", BOOL, UseEntryGuards_option, "1"),
685 OBSOLETE("UseEntryGuardsAsDirGuards"),
686 V(UseGuardFraction, AUTOBOOL, "auto"),
687 V(UseMicrodescriptors, AUTOBOOL, "auto"),
688 OBSOLETE("UseNTorHandshake"),
689 V_IMMUTABLE(User, STRING, NULL),
690 OBSOLETE("UserspaceIOCPBuffers"),
691 V(AuthDirSharedRandomness, BOOL, "1"),
692 V(AuthDirTestEd25519LinkKeys, BOOL, "1"),
693 OBSOLETE("V1AuthoritativeDirectory"),
694 OBSOLETE("V2AuthoritativeDirectory"),
695 VAR("V3AuthoritativeDirectory",BOOL, V3AuthoritativeDir, "0"),
696 V(TestingV3AuthInitialVotingInterval, INTERVAL, "30 minutes"),
697 V(TestingV3AuthInitialVoteDelay, INTERVAL, "5 minutes"),
698 V(TestingV3AuthInitialDistDelay, INTERVAL, "5 minutes"),
699 V(TestingV3AuthVotingStartOffset, INTERVAL, "0"),
700 V(V3AuthVotingInterval, INTERVAL, "1 hour"),
701 V(V3AuthVoteDelay, INTERVAL, "5 minutes"),
702 V(V3AuthDistDelay, INTERVAL, "5 minutes"),
703 V(V3AuthNIntervalsValid, POSINT, "3"),
704 V(V3AuthUseLegacyKey, BOOL, "0"),
705 V(V3BandwidthsFile, FILENAME, NULL),
706 V(GuardfractionFile, FILENAME, NULL),
707 VAR("VersioningAuthoritativeDirectory",BOOL,VersioningAuthoritativeDir, "0"),
708 OBSOLETE("VoteOnHidServDirectoriesV2"),
709 V(VirtualAddrNetworkIPv4, STRING, "127.192.0.0/10"),
710 V(VirtualAddrNetworkIPv6, STRING, "[FE80::]/10"),
711 V(WarnPlaintextPorts, CSV, "23,109,110,143"),
712 OBSOLETE("UseFilteringSSLBufferevents"),
713 OBSOLETE("__UseFilteringSSLBufferevents"),
714 VAR_NODUMP("__ReloadTorrcOnSIGHUP", BOOL, ReloadTorrcOnSIGHUP, "1"),
715 VAR_NODUMP("__AllDirActionsPrivate", BOOL, AllDirActionsPrivate, "0"),
716 VAR_NODUMP("__DisablePredictedCircuits",BOOL,DisablePredictedCircuits, "0"),
717 VAR_NODUMP_IMMUTABLE("__DisableSignalHandlers", BOOL,
718 DisableSignalHandlers, "0"),
719 VAR_NODUMP("__LeaveStreamsUnattached",BOOL, LeaveStreamsUnattached, "0"),
720 VAR_NODUMP("__HashedControlSessionPassword", LINELIST,
721 HashedControlSessionPassword,
722 NULL),
723 VAR_NODUMP("__OwningControllerProcess",STRING,
724 OwningControllerProcess, NULL),
725 VAR_NODUMP_IMMUTABLE("__OwningControllerFD", UINT64, OwningControllerFD,
726 UINT64_MAX_STRING),
727 V(MinUptimeHidServDirectoryV2, INTERVAL, "96 hours"),
728 V(TestingServerDownloadInitialDelay, CSV_INTERVAL, "0"),
729 V(TestingClientDownloadInitialDelay, CSV_INTERVAL, "0"),
730 V(TestingServerConsensusDownloadInitialDelay, CSV_INTERVAL, "0"),
731 V(TestingClientConsensusDownloadInitialDelay, CSV_INTERVAL, "0"),
732 /* With the ClientBootstrapConsensus*Download* below:
733 * Clients with only authorities will try:
734 * - at least 3 authorities over 10 seconds, then exponentially backoff,
735 * with the next attempt 3-21 seconds later,
736 * Clients with authorities and fallbacks will try:
737 * - at least 2 authorities and 4 fallbacks over 21 seconds, then
738 * exponentially backoff, with the next attempts 4-33 seconds later,
739 * Clients will also retry when an application request arrives.
740 * After a number of failed requests, clients retry every 3 days + 1 hour.
742 * Clients used to try 2 authorities over 10 seconds, then wait for
743 * 60 minutes or an application request.
745 * When clients have authorities and fallbacks available, they use these
746 * schedules: (we stagger the times to avoid thundering herds) */
747 V(ClientBootstrapConsensusAuthorityDownloadInitialDelay, CSV_INTERVAL, "6"),
748 V(ClientBootstrapConsensusFallbackDownloadInitialDelay, CSV_INTERVAL, "0"),
749 /* When clients only have authorities available, they use this schedule: */
750 V(ClientBootstrapConsensusAuthorityOnlyDownloadInitialDelay, CSV_INTERVAL,
751 "0"),
752 /* We don't want to overwhelm slow networks (or mirrors whose replies are
753 * blocked), but we also don't want to fail if only some mirrors are
754 * blackholed. Clients will try 3 directories simultaneously.
755 * (Relays never use simultaneous connections.) */
756 V(ClientBootstrapConsensusMaxInProgressTries, POSINT, "3"),
757 /* When a client has any running bridges, check each bridge occasionally,
758 * whether or not that bridge is actually up. */
759 V(TestingBridgeDownloadInitialDelay, CSV_INTERVAL,"10800"),
760 /* When a client is just starting, or has no running bridges, check each
761 * bridge a few times quickly, and then try again later. These schedules
762 * are much longer than the other schedules, because we try each and every
763 * configured bridge with this schedule. */
764 V(TestingBridgeBootstrapDownloadInitialDelay, CSV_INTERVAL, "0"),
765 V(TestingClientMaxIntervalWithoutRequest, INTERVAL, "10 minutes"),
766 V(TestingDirConnectionMaxStall, INTERVAL, "5 minutes"),
767 OBSOLETE("TestingConsensusMaxDownloadTries"),
768 OBSOLETE("ClientBootstrapConsensusMaxDownloadTries"),
769 OBSOLETE("ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries"),
770 OBSOLETE("TestingDescriptorMaxDownloadTries"),
771 OBSOLETE("TestingMicrodescMaxDownloadTries"),
772 OBSOLETE("TestingCertMaxDownloadTries"),
773 V_D(TestingDirAuthVoteExit, ROUTERSET, NULL),
774 V(TestingDirAuthVoteExitIsStrict, BOOL, "0"),
775 V_D(TestingDirAuthVoteGuard, ROUTERSET, NULL),
776 V(TestingDirAuthVoteGuardIsStrict, BOOL, "0"),
777 V_D(TestingDirAuthVoteHSDir, ROUTERSET, NULL),
778 V(TestingDirAuthVoteHSDirIsStrict, BOOL, "0"),
779 VAR_INVIS("___UsingTestNetworkDefaults", BOOL, UsingTestNetworkDefaults_,
780 "0"),
782 END_OF_CONFIG_VARS
785 /** List of default directory authorities */
786 static const char *default_authorities[] = {
787 #ifndef COCCI
788 #include "auth_dirs.inc"
789 #endif
790 NULL
793 /** List of fallback directory authorities. The list is generated by opt-in of
794 * relays that meet certain stability criteria.
796 static const char *default_fallbacks[] = {
797 #ifndef COCCI
798 #include "fallback_dirs.inc"
799 #endif
800 NULL
803 /** Override default values with these if the user sets the TestingTorNetwork
804 * option. */
805 static const struct {
806 const char *k;
807 const char *v;
808 } testing_tor_network_defaults[] = {
809 #ifndef COCCI
810 #include "testnet.inc"
811 #endif
812 { NULL, NULL }
815 #undef VAR
816 #undef V
817 #undef OBSOLETE
819 static const config_deprecation_t option_deprecation_notes_[] = {
820 /* Deprecated since 0.3.2.0-alpha. */
821 { "HTTPProxy", "It only applies to direct unencrypted HTTP connections "
822 "to your directory server, which your Tor probably wasn't using." },
823 { "HTTPProxyAuthenticator", "HTTPProxy is deprecated in favor of HTTPSProxy "
824 "which should be used with HTTPSProxyAuthenticator." },
825 /* End of options deprecated since 0.3.2.1-alpha */
827 /* Options deprecated since 0.3.2.2-alpha */
828 { "ReachableDirAddresses", "It has no effect on relays, and has had no "
829 "effect on clients since 0.2.8." },
830 { "ClientPreferIPv6DirPort", "It has no effect on relays, and has had no "
831 "effect on clients since 0.2.8." },
832 /* End of options deprecated since 0.3.2.2-alpha. */
834 { NULL, NULL }
837 #ifdef _WIN32
838 static char *get_windows_conf_root(void);
839 #endif
841 static int options_check_transition_cb(const void *old,
842 const void *new,
843 char **msg);
844 static int parse_ports(or_options_t *options, int validate_only,
845 char **msg_out, int *n_ports_out,
846 int *world_writable_control_socket);
847 static int validate_data_directories(or_options_t *options);
848 static int write_configuration_file(const char *fname,
849 const or_options_t *options);
851 static void init_libevent(const or_options_t *options);
852 static int opt_streq(const char *s1, const char *s2);
853 static int parse_outbound_addresses(or_options_t *options, int validate_only,
854 char **msg);
855 static void config_maybe_load_geoip_files_(const or_options_t *options,
856 const or_options_t *old_options);
857 static int options_validate_cb(const void *old_options, void *options,
858 char **msg);
859 static void cleanup_protocol_warning_severity_level(void);
860 static void set_protocol_warning_severity_level(int warning_severity);
861 static void options_clear_cb(const config_mgr_t *mgr, void *opts);
862 static setopt_err_t options_validate_and_set(const or_options_t *old_options,
863 or_options_t *new_options,
864 char **msg_out);
865 struct listener_transaction_t;
866 static void options_rollback_listener_transaction(
867 struct listener_transaction_t *xn);
869 /** Magic value for or_options_t. */
870 #define OR_OPTIONS_MAGIC 9090909
872 /** Configuration format for or_options_t. */
873 static const config_format_t options_format = {
874 .size = sizeof(or_options_t),
875 .magic = {
876 "or_options_t",
877 OR_OPTIONS_MAGIC,
878 offsetof(or_options_t, magic_),
880 .abbrevs = option_abbrevs_,
881 .deprecations = option_deprecation_notes_,
882 .vars = option_vars_,
883 .legacy_validate_fn = options_validate_cb,
884 .check_transition_fn = options_check_transition_cb,
885 .clear_fn = options_clear_cb,
886 .has_config_suite = true,
887 .config_suite_offset = offsetof(or_options_t, subconfigs_),
891 * Functions to read and write the global options pointer.
894 /** Command-line and config-file options. */
895 static or_options_t *global_options = NULL;
896 /** The fallback options_t object; this is where we look for options not
897 * in torrc before we fall back to Tor's defaults. */
898 static or_options_t *global_default_options = NULL;
899 /** Name of most recently read torrc file. */
900 static char *torrc_fname = NULL;
901 /** Name of the most recently read torrc-defaults file.*/
902 static char *torrc_defaults_fname = NULL;
903 /** Result of parsing the command line. */
904 static parsed_cmdline_t *global_cmdline = NULL;
905 /** List of port_cfg_t for all configured ports. */
906 static smartlist_t *configured_ports = NULL;
907 /** True iff we're currently validating options, and any calls to
908 * get_options() are likely to be bugs. */
909 static int in_option_validation = 0;
910 /** True iff we have run options_act_once_on_startup() */
911 static bool have_set_startup_options = false;
913 /* A global configuration manager to handle all configuration objects. */
914 static config_mgr_t *options_mgr = NULL;
916 /** Return the global configuration manager object for torrc options. */
917 STATIC const config_mgr_t *
918 get_options_mgr(void)
920 if (PREDICT_UNLIKELY(options_mgr == NULL)) {
921 options_mgr = config_mgr_new(&options_format);
922 int rv = subsystems_register_options_formats(options_mgr);
923 tor_assert(rv == 0);
924 config_mgr_freeze(options_mgr);
926 return options_mgr;
929 #define CHECK_OPTIONS_MAGIC(opt) STMT_BEGIN \
930 config_check_toplevel_magic(get_options_mgr(), (opt)); \
931 STMT_END
933 /** Returns the currently configured options. */
934 MOCK_IMPL(or_options_t *,
935 get_options_mutable, (void))
937 tor_assert(global_options);
938 tor_assert_nonfatal(! in_option_validation);
939 return global_options;
942 /** Returns the currently configured options */
943 MOCK_IMPL(const or_options_t *,
944 get_options,(void))
946 return get_options_mutable();
950 * True iff we have noticed that this is a testing tor network, and we
951 * should use the corresponding defaults.
953 static bool testing_network_configured = false;
955 /** Return a set of lines for any default options that we want to override
956 * from those set in our config_var_t values. */
957 static config_line_t *
958 get_options_defaults(void)
960 int i;
961 config_line_t *result = NULL, **next = &result;
963 if (testing_network_configured) {
964 for (i = 0; testing_tor_network_defaults[i].k; ++i) {
965 config_line_append(next,
966 testing_tor_network_defaults[i].k,
967 testing_tor_network_defaults[i].v);
968 next = &(*next)->next;
972 return result;
975 /** Change the current global options to contain <b>new_val</b> instead of
976 * their current value; take action based on the new value; free the old value
977 * as necessary. Returns 0 on success, -1 on failure.
980 set_options(or_options_t *new_val, char **msg)
982 or_options_t *old_options = global_options;
983 global_options = new_val;
984 /* Note that we pass the *old* options below, for comparison. It
985 * pulls the new options directly out of global_options. */
986 if (options_act_reversible(old_options, msg)<0) {
987 tor_assert(*msg);
988 global_options = old_options;
989 return -1;
991 if (subsystems_set_options(get_options_mgr(), new_val) < 0 ||
992 options_act(old_options) < 0) { /* acting on the options failed. die. */
993 if (! tor_event_loop_shutdown_is_pending()) {
994 log_err(LD_BUG,
995 "Acting on config options left us in a broken state. Dying.");
996 tor_shutdown_event_loop_and_exit(1);
998 global_options = old_options;
999 return -1;
1001 /* Issues a CONF_CHANGED event to notify controller of the change. If Tor is
1002 * just starting up then the old_options will be undefined. */
1003 if (old_options && old_options != global_options) {
1004 config_line_t *changes =
1005 config_get_changes(get_options_mgr(), old_options, new_val);
1006 control_event_conf_changed(changes);
1007 config_free_lines(changes);
1010 if (old_options != global_options) {
1011 or_options_free(old_options);
1012 /* If we are here it means we've successfully applied the new options and
1013 * that the global options have been changed to the new values. We'll
1014 * check if we need to remove or add periodic events. */
1015 periodic_events_on_new_options(global_options);
1018 return 0;
1021 /** Release additional memory allocated in options
1023 static void
1024 options_clear_cb(const config_mgr_t *mgr, void *opts)
1026 (void)mgr;
1027 CHECK_OPTIONS_MAGIC(opts);
1028 or_options_t *options = opts;
1030 routerset_free(options->ExcludeExitNodesUnion_);
1031 if (options->NodeFamilySets) {
1032 SMARTLIST_FOREACH(options->NodeFamilySets, routerset_t *,
1033 rs, routerset_free(rs));
1034 smartlist_free(options->NodeFamilySets);
1036 if (options->SchedulerTypes_) {
1037 SMARTLIST_FOREACH(options->SchedulerTypes_, int *, i, tor_free(i));
1038 smartlist_free(options->SchedulerTypes_);
1040 if (options->FilesOpenedByIncludes) {
1041 SMARTLIST_FOREACH(options->FilesOpenedByIncludes, char *, f, tor_free(f));
1042 smartlist_free(options->FilesOpenedByIncludes);
1044 tor_free(options->DataDirectory);
1045 tor_free(options->CacheDirectory);
1046 tor_free(options->KeyDirectory);
1047 tor_free(options->BridgePassword_AuthDigest_);
1048 tor_free(options->command_arg);
1049 tor_free(options->master_key_fname);
1050 config_free_lines(options->MyFamily);
1053 /** Release all memory allocated in options
1055 STATIC void
1056 or_options_free_(or_options_t *options)
1058 config_free(get_options_mgr(), options);
1061 /** Release all memory and resources held by global configuration structures.
1063 void
1064 config_free_all(void)
1066 or_options_free(global_options);
1067 global_options = NULL;
1068 or_options_free(global_default_options);
1069 global_default_options = NULL;
1071 parsed_cmdline_free(global_cmdline);
1073 if (configured_ports) {
1074 SMARTLIST_FOREACH(configured_ports,
1075 port_cfg_t *, p, port_cfg_free(p));
1076 smartlist_free(configured_ports);
1077 configured_ports = NULL;
1080 tor_free(torrc_fname);
1081 tor_free(torrc_defaults_fname);
1083 cleanup_protocol_warning_severity_level();
1085 have_set_startup_options = false;
1087 config_mgr_free(options_mgr);
1090 /** Make <b>address</b> -- a piece of information related to our operation as
1091 * a client -- safe to log according to the settings in options->SafeLogging,
1092 * and return it.
1094 * (We return "[scrubbed]" if SafeLogging is "1", and address otherwise.)
1096 const char *
1097 safe_str_client_opts(const or_options_t *options, const char *address)
1099 tor_assert(address);
1100 if (!options) {
1101 options = get_options();
1104 if (options->SafeLogging_ == SAFELOG_SCRUB_ALL)
1105 return "[scrubbed]";
1106 else
1107 return address;
1110 /** Make <b>address</b> -- a piece of information of unspecified sensitivity
1111 * -- safe to log according to the settings in options->SafeLogging, and
1112 * return it.
1114 * (We return "[scrubbed]" if SafeLogging is anything besides "0", and address
1115 * otherwise.)
1117 const char *
1118 safe_str_opts(const or_options_t *options, const char *address)
1120 tor_assert(address);
1121 if (!options) {
1122 options = get_options();
1125 if (options->SafeLogging_ != SAFELOG_SCRUB_NONE)
1126 return "[scrubbed]";
1127 else
1128 return address;
1131 /** Equivalent to escaped(safe_str_client(address)). See reentrancy note on
1132 * escaped(): don't use this outside the main thread, or twice in the same
1133 * log statement. */
1134 const char *
1135 escaped_safe_str_client(const char *address)
1137 if (get_options()->SafeLogging_ == SAFELOG_SCRUB_ALL)
1138 return "[scrubbed]";
1139 else
1140 return escaped(address);
1143 /** Equivalent to escaped(safe_str(address)). See reentrancy note on
1144 * escaped(): don't use this outside the main thread, or twice in the same
1145 * log statement. */
1146 const char *
1147 escaped_safe_str(const char *address)
1149 if (get_options()->SafeLogging_ != SAFELOG_SCRUB_NONE)
1150 return "[scrubbed]";
1151 else
1152 return escaped(address);
1156 * The severity level that should be used for warnings of severity
1157 * LOG_PROTOCOL_WARN.
1159 * We keep this outside the options, and we use an atomic_counter_t, in case
1160 * one thread needs to use LOG_PROTOCOL_WARN while an option transition is
1161 * happening in the main thread.
1163 static atomic_counter_t protocol_warning_severity_level;
1165 /** Return the severity level that should be used for warnings of severity
1166 * LOG_PROTOCOL_WARN. */
1168 get_protocol_warning_severity_level(void)
1170 return (int) atomic_counter_get(&protocol_warning_severity_level);
1173 /** Set the protocol warning severity level to <b>severity</b>. */
1174 static void
1175 set_protocol_warning_severity_level(int warning_severity)
1177 atomic_counter_exchange(&protocol_warning_severity_level,
1178 warning_severity);
1182 * Initialize the log warning severity level for protocol warnings. Call
1183 * only once at startup.
1185 void
1186 init_protocol_warning_severity_level(void)
1188 atomic_counter_init(&protocol_warning_severity_level);
1189 set_protocol_warning_severity_level(LOG_WARN);
1193 * Tear down protocol_warning_severity_level.
1195 static void
1196 cleanup_protocol_warning_severity_level(void)
1198 /* Destroying a locked mutex is undefined behaviour. This mutex may be
1199 * locked, because multiple threads can access it. But we need to destroy
1200 * it, otherwise re-initialisation will trigger undefined behaviour.
1201 * See #31735 for details. */
1202 atomic_counter_destroy(&protocol_warning_severity_level);
1205 /** Add the default directory authorities directly into the trusted dir list,
1206 * but only add them insofar as they share bits with <b>type</b>.
1207 * Each authority's bits are restricted to the bits shared with <b>type</b>.
1208 * If <b>type</b> is ALL_DIRINFO or NO_DIRINFO (zero), add all authorities. */
1209 STATIC void
1210 add_default_trusted_dir_authorities(dirinfo_type_t type)
1212 int i;
1213 for (i=0; default_authorities[i]; i++) {
1214 if (parse_dir_authority_line(default_authorities[i], type, 0)<0) {
1215 log_err(LD_BUG, "Couldn't parse internal DirAuthority line %s",
1216 default_authorities[i]);
1221 /** Add the default fallback directory servers into the fallback directory
1222 * server list. */
1223 MOCK_IMPL(void,
1224 add_default_fallback_dir_servers,(void))
1226 int i;
1227 for (i=0; default_fallbacks[i]; i++) {
1228 if (parse_dir_fallback_line(default_fallbacks[i], 0)<0) {
1229 log_err(LD_BUG, "Couldn't parse internal FallbackDir line %s",
1230 default_fallbacks[i]);
1235 /** Look at all the config options for using alternate directory
1236 * authorities, and make sure none of them are broken. Also, warn the
1237 * user if we changed any dangerous ones.
1239 static int
1240 validate_dir_servers(const or_options_t *options,
1241 const or_options_t *old_options)
1243 config_line_t *cl;
1245 if (options->DirAuthorities &&
1246 (options->AlternateDirAuthority || options->AlternateBridgeAuthority)) {
1247 log_warn(LD_CONFIG,
1248 "You cannot set both DirAuthority and Alternate*Authority.");
1249 return -1;
1252 /* do we want to complain to the user about being partitionable? */
1253 if ((options->DirAuthorities &&
1254 (!old_options ||
1255 !config_lines_eq(options->DirAuthorities,
1256 old_options->DirAuthorities))) ||
1257 (options->AlternateDirAuthority &&
1258 (!old_options ||
1259 !config_lines_eq(options->AlternateDirAuthority,
1260 old_options->AlternateDirAuthority)))) {
1261 log_warn(LD_CONFIG,
1262 "You have used DirAuthority or AlternateDirAuthority to "
1263 "specify alternate directory authorities in "
1264 "your configuration. This is potentially dangerous: it can "
1265 "make you look different from all other Tor users, and hurt "
1266 "your anonymity. Even if you've specified the same "
1267 "authorities as Tor uses by default, the defaults could "
1268 "change in the future. Be sure you know what you're doing.");
1271 /* Now go through the four ways you can configure an alternate
1272 * set of directory authorities, and make sure none are broken. */
1273 for (cl = options->DirAuthorities; cl; cl = cl->next)
1274 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
1275 return -1;
1276 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
1277 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
1278 return -1;
1279 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
1280 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
1281 return -1;
1282 for (cl = options->FallbackDir; cl; cl = cl->next)
1283 if (parse_dir_fallback_line(cl->value, 1)<0)
1284 return -1;
1285 return 0;
1288 /** Look at all the config options and assign new dir authorities
1289 * as appropriate.
1292 consider_adding_dir_servers(const or_options_t *options,
1293 const or_options_t *old_options)
1295 config_line_t *cl;
1296 int need_to_update =
1297 !smartlist_len(router_get_trusted_dir_servers()) ||
1298 !smartlist_len(router_get_fallback_dir_servers()) || !old_options ||
1299 !config_lines_eq(options->DirAuthorities, old_options->DirAuthorities) ||
1300 !config_lines_eq(options->FallbackDir, old_options->FallbackDir) ||
1301 (options->UseDefaultFallbackDirs != old_options->UseDefaultFallbackDirs) ||
1302 !config_lines_eq(options->AlternateBridgeAuthority,
1303 old_options->AlternateBridgeAuthority) ||
1304 !config_lines_eq(options->AlternateDirAuthority,
1305 old_options->AlternateDirAuthority);
1307 if (!need_to_update)
1308 return 0; /* all done */
1310 /* "You cannot set both DirAuthority and Alternate*Authority."
1311 * Checking that this restriction holds allows us to simplify
1312 * the unit tests. */
1313 tor_assert(!(options->DirAuthorities &&
1314 (options->AlternateDirAuthority
1315 || options->AlternateBridgeAuthority)));
1317 /* Start from a clean slate. */
1318 clear_dir_servers();
1320 if (!options->DirAuthorities) {
1321 /* then we may want some of the defaults */
1322 dirinfo_type_t type = NO_DIRINFO;
1323 if (!options->AlternateBridgeAuthority) {
1324 type |= BRIDGE_DIRINFO;
1326 if (!options->AlternateDirAuthority) {
1327 type |= V3_DIRINFO | EXTRAINFO_DIRINFO | MICRODESC_DIRINFO;
1328 /* Only add the default fallback directories when the DirAuthorities,
1329 * AlternateDirAuthority, and FallbackDir directory config options
1330 * are set to their defaults, and when UseDefaultFallbackDirs is 1. */
1331 if (!options->FallbackDir && options->UseDefaultFallbackDirs) {
1332 add_default_fallback_dir_servers();
1335 /* if type == NO_DIRINFO, we don't want to add any of the
1336 * default authorities, because we've replaced them all */
1337 if (type != NO_DIRINFO)
1338 add_default_trusted_dir_authorities(type);
1341 for (cl = options->DirAuthorities; cl; cl = cl->next)
1342 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
1343 return -1;
1344 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
1345 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
1346 return -1;
1347 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
1348 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
1349 return -1;
1350 for (cl = options->FallbackDir; cl; cl = cl->next)
1351 if (parse_dir_fallback_line(cl->value, 0)<0)
1352 return -1;
1353 return 0;
1357 * Make sure that <b>directory</b> exists, with appropriate ownership and
1358 * permissions (as modified by <b>group_readable</b>). If <b>create</b>,
1359 * create the directory if it is missing. Return 0 on success.
1360 * On failure, return -1 and set *<b>msg_out</b>.
1362 static int
1363 check_and_create_data_directory(int create,
1364 const char *directory,
1365 int group_readable,
1366 const char *owner,
1367 char **msg_out)
1369 cpd_check_t cpd_opts = create ? CPD_CREATE : CPD_CHECK;
1370 if (group_readable)
1371 cpd_opts |= CPD_GROUP_READ;
1372 if (check_private_dir(directory,
1373 cpd_opts,
1374 owner) < 0) {
1375 tor_asprintf(msg_out,
1376 "Couldn't %s private data directory \"%s\"",
1377 create ? "create" : "access",
1378 directory);
1379 return -1;
1382 #ifndef _WIN32
1383 if (group_readable) {
1384 /* Only new dirs created get new opts, also enforce group read. */
1385 if (chmod(directory, 0750)) {
1386 log_warn(LD_FS,"Unable to make %s group-readable: %s",
1387 directory, strerror(errno));
1390 #endif /* !defined(_WIN32) */
1392 return 0;
1396 * Ensure that our keys directory exists, with appropriate permissions.
1397 * Return 0 on success, -1 on failure.
1400 create_keys_directory(const or_options_t *options)
1402 /* Make sure DataDirectory exists, and is private. */
1403 cpd_check_t cpd_opts = CPD_CREATE;
1404 if (options->DataDirectoryGroupReadable)
1405 cpd_opts |= CPD_GROUP_READ;
1406 if (check_private_dir(options->DataDirectory, cpd_opts, options->User)) {
1407 log_err(LD_OR, "Can't create/check datadirectory %s",
1408 options->DataDirectory);
1409 return -1;
1412 /* Check the key directory. */
1413 if (check_private_dir(options->KeyDirectory, CPD_CREATE, options->User)) {
1414 return -1;
1416 return 0;
1419 /* Helps determine flags to pass to switch_id. */
1420 static int have_low_ports = -1;
1422 /** Take case of initial startup tasks that must occur before any of the
1423 * transactional option-related changes are allowed. */
1424 static int
1425 options_act_once_on_startup(char **msg_out)
1427 if (have_set_startup_options)
1428 return 0;
1430 const or_options_t *options = get_options();
1431 const bool running_tor = options->command == CMD_RUN_TOR;
1433 if (!running_tor)
1434 return 0;
1436 /* Daemonize _first_, since we only want to open most of this stuff in
1437 * the subprocess. Libevent bases can't be reliably inherited across
1438 * processes. */
1439 if (options->RunAsDaemon) {
1440 if (! start_daemon_has_been_called())
1441 subsystems_prefork();
1442 /* No need to roll back, since you can't change the value. */
1443 if (start_daemon())
1444 subsystems_postfork();
1447 #ifdef HAVE_SYSTEMD
1448 /* Our PID may have changed, inform supervisor */
1449 sd_notifyf(0, "MAINPID=%ld\n", (long int)getpid());
1450 #endif
1452 /* Set up libevent. (We need to do this before we can register the
1453 * listeners as listeners.) */
1454 init_libevent(options);
1456 /* This has to come up after libevent is initialized. */
1457 control_initialize_event_queue();
1460 * Initialize the scheduler - this has to come after
1461 * options_init_from_torrc() sets up libevent - why yes, that seems
1462 * completely sensible to hide the libevent setup in the option parsing
1463 * code! It also needs to happen before init_keys(), so it needs to
1464 * happen here too. How yucky. */
1465 scheduler_init();
1467 /* Attempt to lock all current and future memory with mlockall() only once.
1468 * This must happen before setuid. */
1469 if (options->DisableAllSwap) {
1470 if (tor_mlockall() == -1) {
1471 *msg_out = tor_strdup("DisableAllSwap failure. Do you have proper "
1472 "permissions?");
1473 return -1;
1477 have_set_startup_options = true;
1478 return 0;
1482 * Change our user ID if we're configured to do so.
1484 static int
1485 options_switch_id(char **msg_out)
1487 const or_options_t *options = get_options();
1489 /* Setuid/setgid as appropriate */
1490 if (options->User) {
1491 tor_assert(have_low_ports != -1);
1492 unsigned switch_id_flags = 0;
1493 if (options->KeepBindCapabilities == 1) {
1494 switch_id_flags |= SWITCH_ID_KEEP_BINDLOW;
1495 switch_id_flags |= SWITCH_ID_WARN_IF_NO_CAPS;
1497 if (options->KeepBindCapabilities == -1 && have_low_ports) {
1498 switch_id_flags |= SWITCH_ID_KEEP_BINDLOW;
1500 if (switch_id(options->User, switch_id_flags) != 0) {
1501 /* No need to roll back, since you can't change the value. */
1502 *msg_out = tor_strdup("Problem with User value. See logs for details.");
1503 return -1;
1507 return 0;
1511 * Helper. Given a data directory (<b>datadir</b>) and another directory
1512 * (<b>subdir</b>) with respective group-writable permissions
1513 * <b>datadir_gr</b> and <b>subdir_gr</b>, compute whether the subdir should
1514 * be group-writeable.
1516 static int
1517 compute_group_readable_flag(const char *datadir,
1518 const char *subdir,
1519 int datadir_gr,
1520 int subdir_gr)
1522 if (subdir_gr != -1) {
1523 /* The user specified a default for "subdir", so we always obey it. */
1524 return subdir_gr;
1527 /* The user left the subdir_gr option on "auto." */
1528 if (0 == strcmp(subdir, datadir)) {
1529 /* The directories are the same, so we use the group-readable flag from
1530 * the datadirectory */
1531 return datadir_gr;
1532 } else {
1533 /* The directores are different, so we default to "not group-readable" */
1534 return 0;
1539 * Create our DataDirectory, CacheDirectory, and KeyDirectory, and
1540 * set their permissions correctly.
1542 STATIC int
1543 options_create_directories(char **msg_out)
1545 const or_options_t *options = get_options();
1546 const bool running_tor = options->command == CMD_RUN_TOR;
1548 /* Ensure data directory is private; create if possible. */
1549 /* It's okay to do this in "options_act_reversible()" even though it isn't
1550 * actually reversible, since you can't change the DataDirectory while
1551 * Tor is running. */
1552 if (check_and_create_data_directory(running_tor /* create */,
1553 options->DataDirectory,
1554 options->DataDirectoryGroupReadable,
1555 options->User,
1556 msg_out) < 0) {
1557 return -1;
1560 /* We need to handle the group-readable flag for the cache directory and key
1561 * directory specially, since they may be the same as the data directory */
1562 const int key_dir_group_readable = compute_group_readable_flag(
1563 options->DataDirectory,
1564 options->KeyDirectory,
1565 options->DataDirectoryGroupReadable,
1566 options->KeyDirectoryGroupReadable);
1568 if (check_and_create_data_directory(running_tor /* create */,
1569 options->KeyDirectory,
1570 key_dir_group_readable,
1571 options->User,
1572 msg_out) < 0) {
1573 return -1;
1576 const int cache_dir_group_readable = compute_group_readable_flag(
1577 options->DataDirectory,
1578 options->CacheDirectory,
1579 options->DataDirectoryGroupReadable,
1580 options->CacheDirectoryGroupReadable);
1582 if (check_and_create_data_directory(running_tor /* create */,
1583 options->CacheDirectory,
1584 cache_dir_group_readable,
1585 options->User,
1586 msg_out) < 0) {
1587 return -1;
1590 return 0;
1593 /** Structure to represent an incomplete configuration of a set of
1594 * listeners.
1596 * This structure is generated by options_start_listener_transaction(), and is
1597 * either committed by options_commit_listener_transaction() or rolled back by
1598 * options_rollback_listener_transaction(). */
1599 typedef struct listener_transaction_t {
1600 bool set_conn_limit; /**< True if we've set the connection limit */
1601 unsigned old_conn_limit; /**< If nonzero, previous connlimit value. */
1602 smartlist_t *new_listeners; /**< List of new listeners that we opened. */
1603 } listener_transaction_t;
1606 * Start configuring our listeners based on the current value of
1607 * get_options().
1609 * The value <b>old_options</b> holds either the previous options object,
1610 * or NULL if we're starting for the first time.
1612 * On success, return a listener_transaction_t that we can either roll back or
1613 * commit.
1615 * On failure return NULL and write a message into a newly allocated string in
1616 * *<b>msg_out</b>.
1618 static listener_transaction_t *
1619 options_start_listener_transaction(const or_options_t *old_options,
1620 char **msg_out)
1622 listener_transaction_t *xn = tor_malloc_zero(sizeof(listener_transaction_t));
1623 xn->new_listeners = smartlist_new();
1624 or_options_t *options = get_options_mutable();
1625 const bool running_tor = options->command == CMD_RUN_TOR;
1627 if (! running_tor) {
1628 return xn;
1631 int n_ports=0;
1632 /* We need to set the connection limit before we can open the listeners. */
1633 if (! sandbox_is_active()) {
1634 if (set_max_file_descriptors((unsigned)options->ConnLimit,
1635 &options->ConnLimit_) < 0) {
1636 *msg_out = tor_strdup("Problem with ConnLimit value. "
1637 "See logs for details.");
1638 goto rollback;
1640 xn->set_conn_limit = true;
1641 if (old_options)
1642 xn->old_conn_limit = (unsigned)old_options->ConnLimit;
1643 } else {
1644 tor_assert(old_options);
1645 options->ConnLimit_ = old_options->ConnLimit_;
1648 /* Adjust the port configuration so we can launch listeners. */
1649 /* 31851: some ports are relay-only */
1650 if (parse_ports(options, 0, msg_out, &n_ports, NULL)) {
1651 if (!*msg_out)
1652 *msg_out = tor_strdup("Unexpected problem parsing port config");
1653 goto rollback;
1656 /* Set the hibernation state appropriately.*/
1657 consider_hibernation(time(NULL));
1659 /* Launch the listeners. (We do this before we setuid, so we can bind to
1660 * ports under 1024.) We don't want to rebind if we're hibernating or
1661 * shutting down. If networking is disabled, this will close all but the
1662 * control listeners, but disable those. */
1663 /* 31851: some listeners are relay-only */
1664 if (!we_are_hibernating()) {
1665 if (retry_all_listeners(xn->new_listeners,
1666 options->DisableNetwork) < 0) {
1667 *msg_out = tor_strdup("Failed to bind one of the listener ports.");
1668 goto rollback;
1671 if (options->DisableNetwork) {
1672 /* Aggressively close non-controller stuff, NOW */
1673 log_notice(LD_NET, "DisableNetwork is set. Tor will not make or accept "
1674 "non-control network connections. Shutting down all existing "
1675 "connections.");
1676 connection_mark_all_noncontrol_connections();
1677 /* We can't complete circuits until the network is re-enabled. */
1678 note_that_we_maybe_cant_complete_circuits();
1681 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
1682 /* Open /dev/pf before (possibly) dropping privileges. */
1683 if (options->TransPort_set &&
1684 options->TransProxyType_parsed == TPT_DEFAULT) {
1685 if (get_pf_socket() < 0) {
1686 *msg_out = tor_strdup("Unable to open /dev/pf for transparent proxy.");
1687 goto rollback;
1690 #endif /* defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H) */
1692 return xn;
1694 rollback:
1695 options_rollback_listener_transaction(xn);
1696 return NULL;
1700 * Finish configuring the listeners that started to get configured with
1701 * <b>xn</b>. Frees <b>xn</b>.
1703 static void
1704 options_commit_listener_transaction(listener_transaction_t *xn)
1706 tor_assert(xn);
1707 if (xn->set_conn_limit) {
1708 or_options_t *options = get_options_mutable();
1710 * If we adjusted the conn limit, recompute the OOS threshold too
1712 * How many possible sockets to keep in reserve? If we have lots of
1713 * possible sockets, keep this below a limit and set ConnLimit_high_thresh
1714 * very close to ConnLimit_, but if ConnLimit_ is low, shrink it in
1715 * proportion.
1717 * Somewhat arbitrarily, set socks_in_reserve to 5% of ConnLimit_, but
1718 * cap it at 64.
1720 int socks_in_reserve = options->ConnLimit_ / 20;
1721 if (socks_in_reserve > 64) socks_in_reserve = 64;
1723 options->ConnLimit_high_thresh = options->ConnLimit_ - socks_in_reserve;
1724 options->ConnLimit_low_thresh = (options->ConnLimit_ / 4) * 3;
1725 log_info(LD_GENERAL,
1726 "Recomputed OOS thresholds: ConnLimit %d, ConnLimit_ %d, "
1727 "ConnLimit_high_thresh %d, ConnLimit_low_thresh %d",
1728 options->ConnLimit, options->ConnLimit_,
1729 options->ConnLimit_high_thresh,
1730 options->ConnLimit_low_thresh);
1732 /* Give the OOS handler a chance with the new thresholds */
1733 connection_check_oos(get_n_open_sockets(), 0);
1736 smartlist_free(xn->new_listeners);
1737 tor_free(xn);
1741 * Revert the listener configuration changes that that started to get
1742 * configured with <b>xn</b>. Frees <b>xn</b>.
1744 static void
1745 options_rollback_listener_transaction(listener_transaction_t *xn)
1747 if (! xn)
1748 return;
1750 or_options_t *options = get_options_mutable();
1752 if (xn->set_conn_limit && xn->old_conn_limit)
1753 set_max_file_descriptors(xn->old_conn_limit, &options->ConnLimit_);
1755 SMARTLIST_FOREACH(xn->new_listeners, connection_t *, conn,
1757 log_notice(LD_NET, "Closing partially-constructed %s on %s:%d",
1758 conn_type_to_string(conn->type), conn->address, conn->port);
1759 connection_close_immediate(conn);
1760 connection_mark_for_close(conn);
1763 smartlist_free(xn->new_listeners);
1764 tor_free(xn);
1767 /** Structure to represent an incomplete configuration of a set of logs.
1769 * This structure is generated by options_start_log_transaction(), and is
1770 * either committed by options_commit_log_transaction() or rolled back by
1771 * options_rollback_log_transaction(). */
1772 typedef struct log_transaction_t {
1773 /** Previous lowest severity of any configured log. */
1774 int old_min_log_level;
1775 /** True if we have marked the previous logs to be closed */
1776 bool logs_marked;
1777 /** True if we initialized the new set of logs */
1778 bool logs_initialized;
1779 /** True if our safelogging configuration is different from what it was
1780 * previously (or if we are starting for the first time). */
1781 bool safelogging_changed;
1782 } log_transaction_t;
1785 * Start configuring our logs based on the current value of get_options().
1787 * The value <b>old_options</b> holds either the previous options object,
1788 * or NULL if we're starting for the first time.
1790 * On success, return a log_transaction_t that we can either roll back or
1791 * commit.
1793 * On failure return NULL and write a message into a newly allocated string in
1794 * *<b>msg_out</b>.
1796 STATIC log_transaction_t *
1797 options_start_log_transaction(const or_options_t *old_options,
1798 char **msg_out)
1800 const or_options_t *options = get_options();
1801 const bool running_tor = options->command == CMD_RUN_TOR;
1803 log_transaction_t *xn = tor_malloc_zero(sizeof(log_transaction_t));
1804 xn->old_min_log_level = get_min_log_level();
1805 xn->safelogging_changed = !old_options ||
1806 old_options->SafeLogging_ != options->SafeLogging_;
1808 if (! running_tor)
1809 goto done;
1811 mark_logs_temp(); /* Close current logs once new logs are open. */
1812 xn->logs_marked = true;
1813 /* Configure the tor_log(s) */
1814 if (options_init_logs(old_options, options, 0)<0) {
1815 *msg_out = tor_strdup("Failed to init Log options. See logs for details.");
1816 options_rollback_log_transaction(xn);
1817 xn = NULL;
1818 goto done;
1821 xn->logs_initialized = true;
1823 done:
1824 return xn;
1828 * Finish configuring the logs that started to get configured with <b>xn</b>.
1829 * Frees <b>xn</b>.
1831 STATIC void
1832 options_commit_log_transaction(log_transaction_t *xn)
1834 const or_options_t *options = get_options();
1835 tor_assert(xn);
1837 if (xn->logs_marked) {
1838 log_severity_list_t *severity =
1839 tor_malloc_zero(sizeof(log_severity_list_t));
1840 close_temp_logs();
1841 add_callback_log(severity, control_event_logmsg);
1842 logs_set_pending_callback_callback(control_event_logmsg_pending);
1843 control_adjust_event_log_severity();
1844 tor_free(severity);
1845 tor_log_update_sigsafe_err_fds();
1848 if (xn->logs_initialized) {
1849 flush_log_messages_from_startup();
1853 const char *badness = NULL;
1854 int bad_safelog = 0, bad_severity = 0, new_badness = 0;
1855 if (options->SafeLogging_ != SAFELOG_SCRUB_ALL) {
1856 bad_safelog = 1;
1857 if (xn->safelogging_changed)
1858 new_badness = 1;
1860 if (get_min_log_level() >= LOG_INFO) {
1861 bad_severity = 1;
1862 if (get_min_log_level() != xn->old_min_log_level)
1863 new_badness = 1;
1865 if (bad_safelog && bad_severity)
1866 badness = "you disabled SafeLogging, and "
1867 "you're logging more than \"notice\"";
1868 else if (bad_safelog)
1869 badness = "you disabled SafeLogging";
1870 else
1871 badness = "you're logging more than \"notice\"";
1872 if (new_badness)
1873 log_warn(LD_GENERAL, "Your log may contain sensitive information - %s. "
1874 "Don't log unless it serves an important reason. "
1875 "Overwrite the log afterwards.", badness);
1878 tor_free(xn);
1882 * Revert the log configuration changes that that started to get configured
1883 * with <b>xn</b>. Frees <b>xn</b>.
1885 STATIC void
1886 options_rollback_log_transaction(log_transaction_t *xn)
1888 if (!xn)
1889 return;
1891 if (xn->logs_marked) {
1892 rollback_log_changes();
1893 control_adjust_event_log_severity();
1896 tor_free(xn);
1900 * Fetch the active option list, and take actions based on it. All of
1901 * the things we do in this function should survive being done
1902 * repeatedly, OR be done only once when starting Tor. If present,
1903 * <b>old_options</b> contains the previous value of the options.
1905 * This function is only truly "reversible" _after_ the first time it
1906 * is run. The first time that it runs, it performs some irreversible
1907 * tasks in the correct sequence between the reversible option changes.
1909 * Option changes should only be marked as "reversible" if they cannot
1910 * be validated before switching them, but they can be switched back if
1911 * some other validation fails.
1913 * Return 0 if all goes well, return -1 if things went badly.
1915 MOCK_IMPL(STATIC int,
1916 options_act_reversible,(const or_options_t *old_options, char **msg))
1918 const bool first_time = ! have_set_startup_options;
1919 log_transaction_t *log_transaction = NULL;
1920 listener_transaction_t *listener_transaction = NULL;
1921 int r = -1;
1923 /* The ordering of actions in this function is not free, sadly.
1925 * First of all, we _must_ daemonize before we take all kinds of
1926 * initialization actions, since they need to happen in the
1927 * subprocess.
1929 if (options_act_once_on_startup(msg) < 0)
1930 goto rollback;
1932 /* Once we've handled most of once-off initialization, we need to
1933 * open our listeners before we switch IDs. (If we open listeners first,
1934 * we might not be able to bind to low ports.)
1936 listener_transaction = options_start_listener_transaction(old_options, msg);
1937 if (listener_transaction == NULL)
1938 goto rollback;
1940 if (first_time) {
1941 if (options_switch_id(msg) < 0)
1942 goto rollback;
1945 /* On the other hand, we need to touch the file system _after_ we
1946 * switch IDs: otherwise, we'll be making directories and opening files
1947 * with the wrong permissions.
1949 if (first_time) {
1950 if (options_create_directories(msg) < 0)
1951 goto rollback;
1954 /* Bail out at this point if we're not going to be a client or server:
1955 * we don't run Tor itself. */
1956 log_transaction = options_start_log_transaction(old_options, msg);
1957 if (log_transaction == NULL)
1958 goto rollback;
1960 // Commit!
1961 r = 0;
1963 options_commit_log_transaction(log_transaction);
1965 options_commit_listener_transaction(listener_transaction);
1967 goto done;
1969 rollback:
1970 r = -1;
1971 tor_assert(*msg);
1973 options_rollback_log_transaction(log_transaction);
1974 options_rollback_listener_transaction(listener_transaction);
1976 done:
1977 return r;
1980 /** If we need to have a GEOIP ip-to-country map to run with our configured
1981 * options, return 1 and set *<b>reason_out</b> to a description of why. */
1983 options_need_geoip_info(const or_options_t *options, const char **reason_out)
1985 int bridge_usage = should_record_bridge_info(options);
1986 int routerset_usage =
1987 routerset_needs_geoip(options->EntryNodes) ||
1988 routerset_needs_geoip(options->ExitNodes) ||
1989 routerset_needs_geoip(options->MiddleNodes) ||
1990 routerset_needs_geoip(options->ExcludeExitNodes) ||
1991 routerset_needs_geoip(options->ExcludeNodes) ||
1992 routerset_needs_geoip(options->HSLayer2Nodes) ||
1993 routerset_needs_geoip(options->HSLayer3Nodes);
1995 if (routerset_usage && reason_out) {
1996 *reason_out = "We've been configured to use (or avoid) nodes in certain "
1997 "countries, and we need GEOIP information to figure out which ones they "
1998 "are.";
1999 } else if (bridge_usage && reason_out) {
2000 *reason_out = "We've been configured to see which countries can access "
2001 "us as a bridge, and we need GEOIP information to tell which countries "
2002 "clients are in.";
2004 return bridge_usage || routerset_usage;
2007 /* Used in the various options_transition_affects* functions. */
2008 #define YES_IF_CHANGED_BOOL(opt) \
2009 if (!CFG_EQ_BOOL(old_options, new_options, opt)) return 1;
2010 #define YES_IF_CHANGED_INT(opt) \
2011 if (!CFG_EQ_INT(old_options, new_options, opt)) return 1;
2012 #define YES_IF_CHANGED_STRING(opt) \
2013 if (!CFG_EQ_STRING(old_options, new_options, opt)) return 1;
2014 #define YES_IF_CHANGED_LINELIST(opt) \
2015 if (!CFG_EQ_LINELIST(old_options, new_options, opt)) return 1;
2016 #define YES_IF_CHANGED_SMARTLIST(opt) \
2017 if (!CFG_EQ_SMARTLIST(old_options, new_options, opt)) return 1;
2018 #define YES_IF_CHANGED_ROUTERSET(opt) \
2019 if (!CFG_EQ_ROUTERSET(old_options, new_options, opt)) return 1;
2022 * Return true if changing the configuration from <b>old</b> to <b>new</b>
2023 * affects the guard subsystem.
2025 static int
2026 options_transition_affects_guards(const or_options_t *old_options,
2027 const or_options_t *new_options)
2029 /* NOTE: Make sure this function stays in sync with
2030 * node_passes_guard_filter */
2031 tor_assert(old_options);
2032 tor_assert(new_options);
2034 YES_IF_CHANGED_BOOL(UseEntryGuards);
2035 YES_IF_CHANGED_BOOL(UseBridges);
2036 YES_IF_CHANGED_BOOL(ClientUseIPv4);
2037 YES_IF_CHANGED_BOOL(ClientUseIPv6);
2038 YES_IF_CHANGED_BOOL(FascistFirewall);
2039 YES_IF_CHANGED_ROUTERSET(ExcludeNodes);
2040 YES_IF_CHANGED_ROUTERSET(EntryNodes);
2041 YES_IF_CHANGED_SMARTLIST(FirewallPorts);
2042 YES_IF_CHANGED_LINELIST(Bridges);
2043 YES_IF_CHANGED_LINELIST(ReachableORAddresses);
2044 YES_IF_CHANGED_LINELIST(ReachableDirAddresses);
2046 return 0;
2049 /** Fetch the active option list, and take actions based on it. All of the
2050 * things we do should survive being done repeatedly. If present,
2051 * <b>old_options</b> contains the previous value of the options.
2053 * Return 0 if all goes well, return -1 if it's time to die.
2055 * Note: We haven't moved all the "act on new configuration" logic
2056 * the options_act* functions yet. Some is still in do_hup() and other
2057 * places.
2059 MOCK_IMPL(STATIC int,
2060 options_act,(const or_options_t *old_options))
2062 config_line_t *cl;
2063 or_options_t *options = get_options_mutable();
2064 int running_tor = options->command == CMD_RUN_TOR;
2065 char *msg=NULL;
2066 const int transition_affects_guards =
2067 old_options && options_transition_affects_guards(old_options, options);
2069 if (options->NoExec || options->Sandbox) {
2070 tor_disable_spawning_background_processes();
2073 /* disable ptrace and later, other basic debugging techniques */
2075 /* Remember if we already disabled debugger attachment */
2076 static int disabled_debugger_attach = 0;
2077 /* Remember if we already warned about being configured not to disable
2078 * debugger attachment */
2079 static int warned_debugger_attach = 0;
2080 /* Don't disable debugger attachment when we're running the unit tests. */
2081 if (options->DisableDebuggerAttachment && !disabled_debugger_attach &&
2082 running_tor) {
2083 int ok = tor_disable_debugger_attach();
2084 /* LCOV_EXCL_START the warned_debugger_attach is 0 can't reach inside. */
2085 if (warned_debugger_attach && ok == 1) {
2086 log_notice(LD_CONFIG, "Disabled attaching debuggers for unprivileged "
2087 "users.");
2089 /* LCOV_EXCL_STOP */
2090 disabled_debugger_attach = (ok == 1);
2091 } else if (!options->DisableDebuggerAttachment &&
2092 !warned_debugger_attach) {
2093 log_notice(LD_CONFIG, "Not disabling debugger attaching for "
2094 "unprivileged users.");
2095 warned_debugger_attach = 1;
2099 /* Write control ports to disk as appropriate */
2100 control_ports_write_to_file();
2102 if (running_tor && !have_lockfile()) {
2103 if (try_locking(options, 1) < 0)
2104 return -1;
2108 int warning_severity = options->ProtocolWarnings ? LOG_WARN : LOG_INFO;
2109 set_protocol_warning_severity_level(warning_severity);
2112 if (consider_adding_dir_servers(options, old_options) < 0) {
2113 // XXXX This should get validated earlier, and committed here, to
2114 // XXXX lower opportunities for reaching an error case.
2115 return -1;
2118 if (rend_non_anonymous_mode_enabled(options)) {
2119 log_warn(LD_GENERAL, "This copy of Tor was compiled or configured to run "
2120 "in a non-anonymous mode. It will provide NO ANONYMITY.");
2123 if (options->Bridges) {
2124 mark_bridge_list();
2125 for (cl = options->Bridges; cl; cl = cl->next) {
2126 bridge_line_t *bridge_line = parse_bridge_line(cl->value);
2127 if (!bridge_line) {
2128 // LCOV_EXCL_START
2129 log_warn(LD_BUG,
2130 "Previously validated Bridge line could not be added!");
2131 return -1;
2132 // LCOV_EXCL_STOP
2134 bridge_add_from_config(bridge_line);
2136 sweep_bridge_list();
2139 if (running_tor && hs_config_service_all(options, 0)<0) {
2140 // LCOV_EXCL_START
2141 log_warn(LD_BUG,
2142 "Previously validated hidden services line could not be added!");
2143 return -1;
2144 // LCOV_EXCL_STOP
2147 if (running_tor && hs_config_client_auth_all(options, 0) < 0) {
2148 // LCOV_EXCL_START
2149 log_warn(LD_BUG, "Previously validated client authorization for "
2150 "hidden services could not be added!");
2151 return -1;
2152 // LCOV_EXCL_STOP
2155 if (running_tor && !old_options &&
2156 options->OwningControllerFD != UINT64_MAX) {
2157 const unsigned ctrl_flags =
2158 CC_LOCAL_FD_IS_OWNER |
2159 CC_LOCAL_FD_IS_AUTHENTICATED;
2160 tor_socket_t ctrl_sock = (tor_socket_t)options->OwningControllerFD;
2161 if (control_connection_add_local_fd(ctrl_sock, ctrl_flags) < 0) {
2162 log_warn(LD_CONFIG, "Could not add local controller connection with "
2163 "given FD.");
2164 return -1;
2168 /* Load state */
2169 if (! or_state_loaded() && running_tor) {
2170 if (or_state_load())
2171 return -1;
2172 if (options_act_dirauth_mtbf(options) < 0)
2173 return -1;
2176 /* 31851: some of the code in these functions is relay-only */
2177 mark_transport_list();
2178 pt_prepare_proxy_list_for_config_read();
2179 if (!options->DisableNetwork) {
2180 if (options->ClientTransportPlugin) {
2181 for (cl = options->ClientTransportPlugin; cl; cl = cl->next) {
2182 if (pt_parse_transport_line(options, cl->value, 0, 0) < 0) {
2183 // LCOV_EXCL_START
2184 log_warn(LD_BUG,
2185 "Previously validated ClientTransportPlugin line "
2186 "could not be added!");
2187 return -1;
2188 // LCOV_EXCL_STOP
2194 if (options_act_server_transport(old_options) < 0)
2195 return -1;
2197 sweep_transport_list();
2198 sweep_proxy_list();
2200 /* Start the PT proxy configuration. By doing this configuration
2201 here, we also figure out which proxies need to be restarted and
2202 which not. */
2203 if (pt_proxies_configuration_pending() && !net_is_disabled())
2204 pt_configure_remaining_proxies();
2206 /* Bail out at this point if we're not going to be a client or server:
2207 * we want to not fork, and to log stuff to stderr. */
2208 if (!running_tor)
2209 return 0;
2211 /* Finish backgrounding the process */
2212 if (options->RunAsDaemon) {
2213 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
2214 finish_daemon(options->DataDirectory);
2217 if (options_act_relay(old_options) < 0)
2218 return -1;
2220 /* Write our PID to the PID file. If we do not have write permissions we
2221 * will log a warning and exit. */
2222 if (options->PidFile && !sandbox_is_active()) {
2223 if (write_pidfile(options->PidFile) < 0) {
2224 log_err(LD_CONFIG, "Unable to write PIDFile %s",
2225 escaped(options->PidFile));
2226 return -1;
2230 /* Register addressmap directives */
2231 config_register_addressmaps(options);
2232 parse_virtual_addr_network(options->VirtualAddrNetworkIPv4, AF_INET,0,NULL);
2233 parse_virtual_addr_network(options->VirtualAddrNetworkIPv6, AF_INET6,0,NULL);
2235 /* Update address policies. */
2236 if (policies_parse_from_options(options) < 0) {
2237 /* This should be impossible, but let's be sure. */
2238 log_warn(LD_BUG,"Error parsing already-validated policy options.");
2239 return -1;
2242 if (init_control_cookie_authentication(options->CookieAuthentication) < 0) {
2243 log_warn(LD_CONFIG,"Error creating control cookie authentication file.");
2244 return -1;
2247 monitor_owning_controller_process(options->OwningControllerProcess);
2249 /* reload keys as needed for rendezvous services. */
2250 if (hs_service_load_all_keys() < 0) {
2251 log_warn(LD_GENERAL,"Error loading rendezvous service keys");
2252 return -1;
2255 /* Inform the scheduler subsystem that a configuration changed happened. It
2256 * might be a change of scheduler or parameter. */
2257 scheduler_conf_changed();
2259 if (options_act_relay_accounting(old_options) < 0)
2260 return -1;
2262 /* Change the cell EWMA settings */
2263 cmux_ewma_set_options(options, networkstatus_get_latest_consensus());
2265 /* Update the BridgePassword's hashed version as needed. We store this as a
2266 * digest so that we can do side-channel-proof comparisons on it.
2268 if (options->BridgePassword) {
2269 char *http_authenticator;
2270 http_authenticator = alloc_http_authenticator(options->BridgePassword);
2271 if (!http_authenticator) {
2272 // XXXX This should get validated in options_validate().
2273 log_warn(LD_BUG, "Unable to allocate HTTP authenticator. Not setting "
2274 "BridgePassword.");
2275 return -1;
2277 options->BridgePassword_AuthDigest_ = tor_malloc(DIGEST256_LEN);
2278 crypto_digest256(options->BridgePassword_AuthDigest_,
2279 http_authenticator, strlen(http_authenticator),
2280 DIGEST_SHA256);
2281 tor_free(http_authenticator);
2284 /* 31851: OutboundBindAddressExit is relay-only */
2285 if (parse_outbound_addresses(options, 0, &msg) < 0) {
2286 // LCOV_EXCL_START
2287 log_warn(LD_BUG, "Failed parsing previously validated outbound "
2288 "bind addresses: %s", msg);
2289 tor_free(msg);
2290 return -1;
2291 // LCOV_EXCL_STOP
2294 config_maybe_load_geoip_files_(options, old_options);
2296 if (geoip_is_loaded(AF_INET) && options->GeoIPExcludeUnknown) {
2297 /* ExcludeUnknown is true or "auto" */
2298 const int is_auto = options->GeoIPExcludeUnknown == -1;
2299 int changed;
2301 changed = routerset_add_unknown_ccs(&options->ExcludeNodes, is_auto);
2302 changed += routerset_add_unknown_ccs(&options->ExcludeExitNodes, is_auto);
2304 if (changed)
2305 routerset_add_unknown_ccs(&options->ExcludeExitNodesUnion_, is_auto);
2308 /* Check for transitions that need action. */
2309 if (old_options) {
2310 int revise_trackexithosts = 0;
2311 int revise_automap_entries = 0;
2312 int abandon_circuits = 0;
2313 if ((options->UseEntryGuards && !old_options->UseEntryGuards) ||
2314 options->UseBridges != old_options->UseBridges ||
2315 (options->UseBridges &&
2316 !config_lines_eq(options->Bridges, old_options->Bridges)) ||
2317 !routerset_equal(old_options->ExcludeNodes,options->ExcludeNodes) ||
2318 !routerset_equal(old_options->ExcludeExitNodes,
2319 options->ExcludeExitNodes) ||
2320 !routerset_equal(old_options->EntryNodes, options->EntryNodes) ||
2321 !routerset_equal(old_options->ExitNodes, options->ExitNodes) ||
2322 !routerset_equal(old_options->HSLayer2Nodes,
2323 options->HSLayer2Nodes) ||
2324 !routerset_equal(old_options->HSLayer3Nodes,
2325 options->HSLayer3Nodes) ||
2326 !routerset_equal(old_options->MiddleNodes, options->MiddleNodes) ||
2327 options->StrictNodes != old_options->StrictNodes) {
2328 log_info(LD_CIRC,
2329 "Changed to using entry guards or bridges, or changed "
2330 "preferred or excluded node lists. "
2331 "Abandoning previous circuits.");
2332 abandon_circuits = 1;
2335 if (transition_affects_guards) {
2336 if (guards_update_all()) {
2337 abandon_circuits = 1;
2341 if (abandon_circuits) {
2342 circuit_mark_all_unused_circs();
2343 circuit_mark_all_dirty_circs_as_unusable();
2344 revise_trackexithosts = 1;
2347 if (!smartlist_strings_eq(old_options->TrackHostExits,
2348 options->TrackHostExits))
2349 revise_trackexithosts = 1;
2351 if (revise_trackexithosts)
2352 addressmap_clear_excluded_trackexithosts(options);
2354 if (!options->AutomapHostsOnResolve &&
2355 old_options->AutomapHostsOnResolve) {
2356 revise_automap_entries = 1;
2357 } else {
2358 if (!smartlist_strings_eq(old_options->AutomapHostsSuffixes,
2359 options->AutomapHostsSuffixes))
2360 revise_automap_entries = 1;
2361 else if (!opt_streq(old_options->VirtualAddrNetworkIPv4,
2362 options->VirtualAddrNetworkIPv4) ||
2363 !opt_streq(old_options->VirtualAddrNetworkIPv6,
2364 options->VirtualAddrNetworkIPv6))
2365 revise_automap_entries = 1;
2368 if (revise_automap_entries)
2369 addressmap_clear_invalid_automaps(options);
2371 if (options_act_bridge_stats(old_options) < 0)
2372 return -1;
2374 if (dns_reset())
2375 return -1;
2377 if (options_act_relay_bandwidth(old_options) < 0)
2378 return -1;
2380 if (options->BandwidthRate != old_options->BandwidthRate ||
2381 options->BandwidthBurst != old_options->BandwidthBurst)
2382 connection_bucket_adjust(options);
2384 if (options->MainloopStats != old_options->MainloopStats) {
2385 reset_main_loop_counters();
2389 /* 31851: These options are relay-only, but we need to disable them if we
2390 * are in client mode. In 29211, we will disable all relay options in
2391 * client mode. */
2392 /* Only collect directory-request statistics on relays and bridges. */
2393 options->DirReqStatistics = options->DirReqStatistics_option &&
2394 server_mode(options);
2395 options->HiddenServiceStatistics =
2396 options->HiddenServiceStatistics_option && server_mode(options);
2398 /* Only collect other relay-only statistics on relays. */
2399 if (!public_server_mode(options)) {
2400 options->CellStatistics = 0;
2401 options->EntryStatistics = 0;
2402 options->ConnDirectionStatistics = 0;
2403 options->ExitPortStatistics = 0;
2406 bool print_notice = 0;
2407 if (options_act_relay_stats(old_options, &print_notice) < 0)
2408 return -1;
2409 if (options_act_dirauth_stats(old_options, &print_notice) < 0)
2410 return -1;
2411 if (print_notice)
2412 options_act_relay_stats_msg();
2414 if (options_act_relay_desc(old_options) < 0)
2415 return -1;
2417 if (options_act_dirauth(old_options) < 0)
2418 return -1;
2420 /* We may need to reschedule some directory stuff if our status changed. */
2421 if (old_options) {
2422 if (!bool_eq(dirclient_fetches_dir_info_early(options),
2423 dirclient_fetches_dir_info_early(old_options)) ||
2424 !bool_eq(dirclient_fetches_dir_info_later(options),
2425 dirclient_fetches_dir_info_later(old_options)) ||
2426 !config_lines_eq(old_options->Bridges, options->Bridges)) {
2427 /* Make sure update_router_have_minimum_dir_info() gets called. */
2428 router_dir_info_changed();
2429 /* We might need to download a new consensus status later or sooner than
2430 * we had expected. */
2431 update_consensus_networkstatus_fetch_time(time(NULL));
2435 if (options_act_relay_dos(old_options) < 0)
2436 return -1;
2437 if (options_act_relay_dir(old_options) < 0)
2438 return -1;
2440 return 0;
2444 * Enumeration to describe the syntax for a command-line option.
2446 typedef enum {
2447 /** Describe an option that does not take an argument. */
2448 ARGUMENT_NONE = 0,
2449 /** Describes an option that takes a single argument. */
2450 ARGUMENT_NECESSARY = 1,
2451 /** Describes an option that takes a single optional argument. */
2452 ARGUMENT_OPTIONAL = 2
2453 } takes_argument_t;
2455 /** Table describing arguments that Tor accepts on the command line,
2456 * other than those that are the same as in torrc. */
2457 static const struct {
2458 /** The string that the user has to provide. */
2459 const char *name;
2460 /** Does this option accept an argument? */
2461 takes_argument_t takes_argument;
2462 /** If not CMD_RUN_TOR, what should Tor do when it starts? */
2463 tor_cmdline_mode_t command;
2464 /** If nonzero, set the quiet level to this. 1 is "hush", 2 is "quiet" */
2465 int quiet;
2466 } CMDLINE_ONLY_OPTIONS[] = {
2467 { .name="-f",
2468 .takes_argument=ARGUMENT_NECESSARY },
2469 { .name="--allow-missing-torrc" },
2470 { .name="--defaults-torrc",
2471 .takes_argument=ARGUMENT_NECESSARY },
2472 { .name="--hash-password",
2473 .takes_argument=ARGUMENT_NECESSARY,
2474 .command=CMD_HASH_PASSWORD,
2475 .quiet=QUIET_HUSH },
2476 { .name="--dump-config",
2477 .takes_argument=ARGUMENT_OPTIONAL,
2478 .command=CMD_DUMP_CONFIG,
2479 .quiet=QUIET_SILENT },
2480 { .name="--list-fingerprint",
2481 .command=CMD_LIST_FINGERPRINT },
2482 { .name="--keygen",
2483 .command=CMD_KEYGEN },
2484 { .name="--key-expiration",
2485 .takes_argument=ARGUMENT_OPTIONAL,
2486 .command=CMD_KEY_EXPIRATION },
2487 { .name="--newpass" },
2488 { .name="--no-passphrase" },
2489 { .name="--passphrase-fd",
2490 .takes_argument=ARGUMENT_NECESSARY },
2491 { .name="--verify-config",
2492 .command=CMD_VERIFY_CONFIG },
2493 { .name="--ignore-missing-torrc" },
2494 { .name="--quiet",
2495 .quiet=QUIET_SILENT },
2496 { .name="--hush",
2497 .quiet=QUIET_HUSH },
2498 { .name="--version",
2499 .command=CMD_IMMEDIATE,
2500 .quiet=QUIET_HUSH },
2501 { .name="--list-modules",
2502 .command=CMD_IMMEDIATE,
2503 .quiet=QUIET_HUSH },
2504 { .name="--library-versions",
2505 .command=CMD_IMMEDIATE,
2506 .quiet=QUIET_HUSH },
2507 { .name="-h",
2508 .command=CMD_IMMEDIATE,
2509 .quiet=QUIET_HUSH },
2510 { .name="--help",
2511 .command=CMD_IMMEDIATE,
2512 .quiet=QUIET_HUSH },
2513 { .name="--list-torrc-options",
2514 .command=CMD_IMMEDIATE,
2515 .quiet=QUIET_HUSH },
2516 { .name="--list-deprecated-options",
2517 .command=CMD_IMMEDIATE },
2518 { .name="--nt-service" },
2519 { .name="-nt-service" },
2520 { .name=NULL },
2523 /** Helper: Read a list of configuration options from the command line. If
2524 * successful, return a newly allocated parsed_cmdline_t; otherwise return
2525 * NULL.
2527 * If <b>ignore_errors</b> is set, try to recover from all recoverable
2528 * errors and return the best command line we can.
2530 parsed_cmdline_t *
2531 config_parse_commandline(int argc, char **argv, int ignore_errors)
2533 parsed_cmdline_t *result = tor_malloc_zero(sizeof(parsed_cmdline_t));
2534 result->command = CMD_RUN_TOR;
2535 config_line_t *param = NULL;
2537 config_line_t **new_cmdline = &result->cmdline_opts;
2538 config_line_t **new = &result->other_opts;
2540 char *s, *arg;
2541 int i = 1;
2543 while (i < argc) {
2544 unsigned command = CONFIG_LINE_NORMAL;
2545 takes_argument_t want_arg = ARGUMENT_NECESSARY;
2546 int is_cmdline = 0;
2547 int j;
2548 bool is_a_command = false;
2550 for (j = 0; CMDLINE_ONLY_OPTIONS[j].name != NULL; ++j) {
2551 if (!strcmp(argv[i], CMDLINE_ONLY_OPTIONS[j].name)) {
2552 is_cmdline = 1;
2553 want_arg = CMDLINE_ONLY_OPTIONS[j].takes_argument;
2554 if (CMDLINE_ONLY_OPTIONS[j].command != CMD_RUN_TOR) {
2555 is_a_command = true;
2556 result->command = CMDLINE_ONLY_OPTIONS[j].command;
2558 quiet_level_t quiet = CMDLINE_ONLY_OPTIONS[j].quiet;
2559 if (quiet > result->quiet_level)
2560 result->quiet_level = quiet;
2561 break;
2565 s = argv[i];
2567 /* Each keyword may be prefixed with one or two dashes. */
2568 if (*s == '-')
2569 s++;
2570 if (*s == '-')
2571 s++;
2572 /* Figure out the command, if any. */
2573 if (*s == '+') {
2574 s++;
2575 command = CONFIG_LINE_APPEND;
2576 } else if (*s == '/') {
2577 s++;
2578 command = CONFIG_LINE_CLEAR;
2579 /* A 'clear' command has no argument. */
2580 want_arg = 0;
2583 const int is_last = (i == argc-1);
2585 if (want_arg == ARGUMENT_NECESSARY && is_last) {
2586 if (ignore_errors) {
2587 arg = tor_strdup("");
2588 } else {
2589 log_warn(LD_CONFIG,"Command-line option '%s' with no value. Failing.",
2590 argv[i]);
2591 parsed_cmdline_free(result);
2592 return NULL;
2594 } else if (want_arg == ARGUMENT_OPTIONAL && is_last) {
2595 arg = tor_strdup("");
2596 } else {
2597 arg = (want_arg != ARGUMENT_NONE) ? tor_strdup(argv[i+1]) :
2598 tor_strdup("");
2601 param = tor_malloc_zero(sizeof(config_line_t));
2602 param->key = is_cmdline ? tor_strdup(argv[i]) :
2603 tor_strdup(config_expand_abbrev(get_options_mgr(), s, 1, 1));
2604 param->value = arg;
2605 param->command = command;
2606 param->next = NULL;
2607 log_debug(LD_CONFIG, "command line: parsed keyword '%s', value '%s'",
2608 param->key, param->value);
2610 if (is_a_command) {
2611 result->command_arg = param->value;
2614 if (is_cmdline) {
2615 *new_cmdline = param;
2616 new_cmdline = &((*new_cmdline)->next);
2617 } else {
2618 *new = param;
2619 new = &((*new)->next);
2622 i += want_arg ? 2 : 1;
2625 return result;
2628 /** Release all storage held by <b>cmdline</b>. */
2629 void
2630 parsed_cmdline_free_(parsed_cmdline_t *cmdline)
2632 if (!cmdline)
2633 return;
2634 config_free_lines(cmdline->cmdline_opts);
2635 config_free_lines(cmdline->other_opts);
2636 tor_free(cmdline);
2639 /** Return true iff key is a valid configuration option. */
2641 option_is_recognized(const char *key)
2643 return config_find_option_name(get_options_mgr(), key) != NULL;
2646 /** Return the canonical name of a configuration option, or NULL
2647 * if no such option exists. */
2648 const char *
2649 option_get_canonical_name(const char *key)
2651 return config_find_option_name(get_options_mgr(), key);
2654 /** Return a canonical list of the options assigned for key.
2656 config_line_t *
2657 option_get_assignment(const or_options_t *options, const char *key)
2659 return config_get_assigned_option(get_options_mgr(), options, key, 1);
2662 /** Try assigning <b>list</b> to the global options. You do this by duping
2663 * options, assigning list to the new one, then validating it. If it's
2664 * ok, then throw out the old one and stick with the new one. Else,
2665 * revert to old and return failure. Return SETOPT_OK on success, or
2666 * a setopt_err_t on failure.
2668 * If not success, point *<b>msg</b> to a newly allocated string describing
2669 * what went wrong.
2671 setopt_err_t
2672 options_trial_assign(config_line_t *list, unsigned flags, char **msg)
2674 int r;
2675 or_options_t *trial_options = config_dup(get_options_mgr(), get_options());
2677 if ((r=config_assign(get_options_mgr(), trial_options,
2678 list, flags, msg)) < 0) {
2679 or_options_free(trial_options);
2680 return r;
2682 const or_options_t *cur_options = get_options();
2684 return options_validate_and_set(cur_options, trial_options, msg);
2687 /** Print a usage message for tor. */
2688 static void
2689 print_usage(void)
2691 printf(
2692 "Copyright (c) 2001-2004, Roger Dingledine\n"
2693 "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
2694 "Copyright (c) 2007-2020, The Tor Project, Inc.\n\n"
2695 "tor -f <torrc> [args]\n"
2696 "See man page for options, or https://www.torproject.org/ for "
2697 "documentation.\n");
2700 /** Print all non-obsolete torrc options. */
2701 static void
2702 list_torrc_options(void)
2704 smartlist_t *vars = config_mgr_list_vars(get_options_mgr());
2705 SMARTLIST_FOREACH_BEGIN(vars, const config_var_t *, var) {
2706 /* Possibly this should check listable, rather than (or in addition to)
2707 * settable. See ticket 31654.
2709 if (! config_var_is_settable(var)) {
2710 /* This variable cannot be set, or cannot be set by this name. */
2711 continue;
2713 printf("%s\n", var->member.name);
2714 } SMARTLIST_FOREACH_END(var);
2715 smartlist_free(vars);
2718 /** Print all deprecated but non-obsolete torrc options. */
2719 static void
2720 list_deprecated_options(void)
2722 smartlist_t *deps = config_mgr_list_deprecated_vars(get_options_mgr());
2723 /* Possibly this should check whether the variables are listable,
2724 * but currently it does not. See ticket 31654. */
2725 SMARTLIST_FOREACH(deps, const char *, name,
2726 printf("%s\n", name));
2727 smartlist_free(deps);
2730 /** Print all compile-time modules and their enabled/disabled status. */
2731 static void
2732 list_enabled_modules(void)
2734 printf("%s: %s\n", "relay", have_module_relay() ? "yes" : "no");
2735 printf("%s: %s\n", "dirauth", have_module_dirauth() ? "yes" : "no");
2738 /** Last value actually set by resolve_my_address. */
2739 static uint32_t last_resolved_addr = 0;
2741 /** Accessor for last_resolved_addr from outside this file. */
2742 uint32_t
2743 get_last_resolved_addr(void)
2745 return last_resolved_addr;
2748 /** Reset last_resolved_addr from outside this file. */
2749 void
2750 reset_last_resolved_addr(void)
2752 last_resolved_addr = 0;
2755 /* Return true if <b>options</b> is using the default authorities, and false
2756 * if any authority-related option has been overridden. */
2758 using_default_dir_authorities(const or_options_t *options)
2760 return (!options->DirAuthorities && !options->AlternateDirAuthority);
2764 * Attempt getting our non-local (as judged by tor_addr_is_internal()
2765 * function) IP address using following techniques, listed in
2766 * order from best (most desirable, try first) to worst (least
2767 * desirable, try if everything else fails).
2769 * First, attempt using <b>options-\>Address</b> to get our
2770 * non-local IP address.
2772 * If <b>options-\>Address</b> represents a non-local IP address,
2773 * consider it ours.
2775 * If <b>options-\>Address</b> is a DNS name that resolves to
2776 * a non-local IP address, consider this IP address ours.
2778 * If <b>options-\>Address</b> is NULL, fall back to getting local
2779 * hostname and using it in above-described ways to try and
2780 * get our IP address.
2782 * In case local hostname cannot be resolved to a non-local IP
2783 * address, try getting an IP address of network interface
2784 * in hopes it will be non-local one.
2786 * Fail if one or more of the following is true:
2787 * - DNS name in <b>options-\>Address</b> cannot be resolved.
2788 * - <b>options-\>Address</b> is a local host address.
2789 * - Attempt at getting local hostname fails.
2790 * - Attempt at getting network interface address fails.
2792 * Return 0 if all is well, or -1 if we can't find a suitable
2793 * public IP address.
2795 * If we are returning 0:
2796 * - Put our public IP address (in host order) into *<b>addr_out</b>.
2797 * - If <b>method_out</b> is non-NULL, set *<b>method_out</b> to a static
2798 * string describing how we arrived at our answer.
2799 * - "CONFIGURED" - parsed from IP address string in
2800 * <b>options-\>Address</b>
2801 * - "RESOLVED" - resolved from DNS name in <b>options-\>Address</b>
2802 * - "GETHOSTNAME" - resolved from a local hostname.
2803 * - "INTERFACE" - retrieved from a network interface.
2804 * - If <b>hostname_out</b> is non-NULL, and we resolved a hostname to
2805 * get our address, set *<b>hostname_out</b> to a newly allocated string
2806 * holding that hostname. (If we didn't get our address by resolving a
2807 * hostname, set *<b>hostname_out</b> to NULL.)
2809 * XXXX ipv6
2812 resolve_my_address(int warn_severity, const or_options_t *options,
2813 uint32_t *addr_out,
2814 const char **method_out, char **hostname_out)
2816 struct in_addr in;
2817 uint32_t addr; /* host order */
2818 char hostname[256];
2819 const char *method_used;
2820 const char *hostname_used;
2821 int explicit_ip=1;
2822 int explicit_hostname=1;
2823 int from_interface=0;
2824 char *addr_string = NULL;
2825 const char *address = options->Address;
2826 int notice_severity = warn_severity <= LOG_NOTICE ?
2827 LOG_NOTICE : warn_severity;
2829 tor_addr_t myaddr;
2830 tor_assert(addr_out);
2833 * Step one: Fill in 'hostname' to be our best guess.
2836 if (address && *address) {
2837 strlcpy(hostname, address, sizeof(hostname));
2838 } else { /* then we need to guess our address */
2839 explicit_ip = 0; /* it's implicit */
2840 explicit_hostname = 0; /* it's implicit */
2842 if (tor_gethostname(hostname, sizeof(hostname)) < 0) {
2843 log_fn(warn_severity, LD_NET,"Error obtaining local hostname");
2844 return -1;
2846 log_debug(LD_CONFIG, "Guessed local host name as '%s'", hostname);
2850 * Step two: Now that we know 'hostname', parse it or resolve it. If
2851 * it doesn't parse or resolve, look at the interface address. Set 'addr'
2852 * to be our (host-order) 32-bit answer.
2855 if (tor_inet_aton(hostname, &in) == 0) {
2856 /* then we have to resolve it */
2857 explicit_ip = 0;
2858 if (tor_lookup_hostname(hostname, &addr)) { /* failed to resolve */
2859 uint32_t interface_ip; /* host order */
2861 if (explicit_hostname) {
2862 log_fn(warn_severity, LD_CONFIG,
2863 "Could not resolve local Address '%s'. Failing.", hostname);
2864 return -1;
2866 log_fn(notice_severity, LD_CONFIG,
2867 "Could not resolve guessed local hostname '%s'. "
2868 "Trying something else.", hostname);
2869 if (get_interface_address(warn_severity, &interface_ip)) {
2870 log_fn(warn_severity, LD_CONFIG,
2871 "Could not get local interface IP address. Failing.");
2872 return -1;
2874 from_interface = 1;
2875 addr = interface_ip;
2876 log_fn(notice_severity, LD_CONFIG, "Learned IP address '%s' for "
2877 "local interface. Using that.", fmt_addr32(addr));
2878 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2879 } else { /* resolved hostname into addr */
2880 tor_addr_from_ipv4h(&myaddr, addr);
2882 if (!explicit_hostname &&
2883 tor_addr_is_internal(&myaddr, 0)) {
2884 tor_addr_t interface_ip;
2886 log_fn(notice_severity, LD_CONFIG, "Guessed local hostname '%s' "
2887 "resolves to a private IP address (%s). Trying something "
2888 "else.", hostname, fmt_addr32(addr));
2890 if (get_interface_address6(warn_severity, AF_INET, &interface_ip)<0) {
2891 log_fn(warn_severity, LD_CONFIG,
2892 "Could not get local interface IP address. Too bad.");
2893 } else if (tor_addr_is_internal(&interface_ip, 0)) {
2894 log_fn(notice_severity, LD_CONFIG,
2895 "Interface IP address '%s' is a private address too. "
2896 "Ignoring.", fmt_addr(&interface_ip));
2897 } else {
2898 from_interface = 1;
2899 addr = tor_addr_to_ipv4h(&interface_ip);
2900 log_fn(notice_severity, LD_CONFIG,
2901 "Learned IP address '%s' for local interface."
2902 " Using that.", fmt_addr32(addr));
2903 strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2907 } else {
2908 addr = ntohl(in.s_addr); /* set addr so that addr_string is not
2909 * illformed */
2913 * Step three: Check whether 'addr' is an internal IP address, and error
2914 * out if it is and we don't want that.
2917 tor_addr_from_ipv4h(&myaddr,addr);
2919 addr_string = tor_dup_ip(addr);
2920 if (tor_addr_is_internal(&myaddr, 0)) {
2921 /* make sure we're ok with publishing an internal IP */
2922 if (using_default_dir_authorities(options)) {
2923 /* if they are using the default authorities, disallow internal IPs
2924 * always. */
2925 log_fn(warn_severity, LD_CONFIG,
2926 "Address '%s' resolves to private IP address '%s'. "
2927 "Tor servers that use the default DirAuthorities must have "
2928 "public IP addresses.", hostname, addr_string);
2929 tor_free(addr_string);
2930 return -1;
2932 if (!explicit_ip) {
2933 /* even if they've set their own authorities, require an explicit IP if
2934 * they're using an internal address. */
2935 log_fn(warn_severity, LD_CONFIG, "Address '%s' resolves to private "
2936 "IP address '%s'. Please set the Address config option to be "
2937 "the IP address you want to use.", hostname, addr_string);
2938 tor_free(addr_string);
2939 return -1;
2944 * Step four: We have a winner! 'addr' is our answer for sure, and
2945 * 'addr_string' is its string form. Fill out the various fields to
2946 * say how we decided it.
2949 log_debug(LD_CONFIG, "Resolved Address to '%s'.", addr_string);
2951 if (explicit_ip) {
2952 method_used = "CONFIGURED";
2953 hostname_used = NULL;
2954 } else if (explicit_hostname) {
2955 method_used = "RESOLVED";
2956 hostname_used = hostname;
2957 } else if (from_interface) {
2958 method_used = "INTERFACE";
2959 hostname_used = NULL;
2960 } else {
2961 method_used = "GETHOSTNAME";
2962 hostname_used = hostname;
2965 *addr_out = addr;
2966 if (method_out)
2967 *method_out = method_used;
2968 if (hostname_out)
2969 *hostname_out = hostname_used ? tor_strdup(hostname_used) : NULL;
2972 * Step five: Check if the answer has changed since last time (or if
2973 * there was no last time), and if so call various functions to keep
2974 * us up-to-date.
2977 if (last_resolved_addr && last_resolved_addr != *addr_out) {
2978 /* Leave this as a notice, regardless of the requested severity,
2979 * at least until dynamic IP address support becomes bulletproof. */
2980 log_notice(LD_NET,
2981 "Your IP address seems to have changed to %s "
2982 "(METHOD=%s%s%s). Updating.",
2983 addr_string, method_used,
2984 hostname_used ? " HOSTNAME=" : "",
2985 hostname_used ? hostname_used : "");
2986 ip_address_changed(0);
2989 if (last_resolved_addr != *addr_out) {
2990 control_event_server_status(LOG_NOTICE,
2991 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s%s%s",
2992 addr_string, method_used,
2993 hostname_used ? " HOSTNAME=" : "",
2994 hostname_used ? hostname_used : "");
2996 last_resolved_addr = *addr_out;
2999 * And finally, clean up and return success.
3002 tor_free(addr_string);
3003 return 0;
3006 /** Return true iff <b>addr</b> is judged to be on the same network as us, or
3007 * on a private network.
3009 MOCK_IMPL(int,
3010 is_local_addr, (const tor_addr_t *addr))
3012 if (tor_addr_is_internal(addr, 0))
3013 return 1;
3014 /* Check whether ip is on the same /24 as we are. */
3015 if (get_options()->EnforceDistinctSubnets == 0)
3016 return 0;
3017 if (tor_addr_family(addr) == AF_INET) {
3018 uint32_t ip = tor_addr_to_ipv4h(addr);
3020 /* It's possible that this next check will hit before the first time
3021 * resolve_my_address actually succeeds. (For clients, it is likely that
3022 * resolve_my_address will never be called at all). In those cases,
3023 * last_resolved_addr will be 0, and so checking to see whether ip is on
3024 * the same /24 as last_resolved_addr will be the same as checking whether
3025 * it was on net 0, which is already done by tor_addr_is_internal.
3027 if ((last_resolved_addr & (uint32_t)0xffffff00ul)
3028 == (ip & (uint32_t)0xffffff00ul))
3029 return 1;
3031 return 0;
3034 /** Return a new empty or_options_t. Used for testing. */
3035 or_options_t *
3036 options_new(void)
3038 or_options_t *options = config_new(get_options_mgr());
3039 options->command = CMD_RUN_TOR;
3040 return options;
3043 /** Set <b>options</b> to hold reasonable defaults for most options.
3044 * Each option defaults to zero. */
3045 void
3046 options_init(or_options_t *options)
3048 config_init(get_options_mgr(), options);
3049 config_line_t *dflts = get_options_defaults();
3050 char *msg=NULL;
3051 if (config_assign(get_options_mgr(), options, dflts,
3052 CAL_WARN_DEPRECATIONS, &msg)<0) {
3053 log_err(LD_BUG, "Unable to set default options: %s", msg);
3054 tor_free(msg);
3055 tor_assert_unreached();
3057 config_free_lines(dflts);
3058 tor_free(msg);
3061 /** Return a string containing a possible configuration file that would give
3062 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
3063 * include options that are the same as Tor's defaults.
3065 char *
3066 options_dump(const or_options_t *options, int how_to_dump)
3068 const or_options_t *use_defaults;
3069 int minimal;
3070 switch (how_to_dump) {
3071 case OPTIONS_DUMP_MINIMAL:
3072 use_defaults = global_default_options;
3073 minimal = 1;
3074 break;
3075 case OPTIONS_DUMP_DEFAULTS:
3076 use_defaults = NULL;
3077 minimal = 1;
3078 break;
3079 case OPTIONS_DUMP_ALL:
3080 use_defaults = NULL;
3081 minimal = 0;
3082 break;
3083 default:
3084 log_warn(LD_BUG, "Bogus value for how_to_dump==%d", how_to_dump);
3085 return NULL;
3088 return config_dump(get_options_mgr(), use_defaults, options, minimal, 0);
3091 /** Return 0 if every element of sl is a string holding a decimal
3092 * representation of a port number, or if sl is NULL.
3093 * Otherwise set *msg and return -1. */
3094 static int
3095 validate_ports_csv(smartlist_t *sl, const char *name, char **msg)
3097 int i;
3098 tor_assert(name);
3100 if (!sl)
3101 return 0;
3103 SMARTLIST_FOREACH(sl, const char *, cp,
3105 i = atoi(cp);
3106 if (i < 1 || i > 65535) {
3107 tor_asprintf(msg, "Port '%s' out of range in %s", cp, name);
3108 return -1;
3111 return 0;
3114 /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
3115 * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
3116 * Else return 0.
3119 config_ensure_bandwidth_cap(uint64_t *value, const char *desc, char **msg)
3121 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
3122 /* This handles an understandable special case where somebody says "2gb"
3123 * whereas our actual maximum is 2gb-1 (INT_MAX) */
3124 --*value;
3126 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
3127 tor_asprintf(msg, "%s (%"PRIu64") must be at most %d",
3128 desc, (*value),
3129 ROUTER_MAX_DECLARED_BANDWIDTH);
3130 return -1;
3132 return 0;
3135 /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
3136 * services can overload the directory system. */
3137 #define MIN_REND_POST_PERIOD (10*60)
3138 #define MIN_REND_POST_PERIOD_TESTING (5)
3140 /** Highest allowable value for CircuitsAvailableTimeout.
3141 * If this is too large, client connections will stay open for too long,
3142 * incurring extra padding overhead. */
3143 #define MAX_CIRCS_AVAILABLE_TIME (24*60*60)
3145 /** Highest allowable value for RendPostPeriod. */
3146 #define MAX_DIR_PERIOD ((7*24*60*60)/2)
3148 /** Lowest allowable value for MaxCircuitDirtiness; if this is too low, Tor
3149 * will generate too many circuits and potentially overload the network. */
3150 #define MIN_MAX_CIRCUIT_DIRTINESS 10
3152 /** Highest allowable value for MaxCircuitDirtiness: prevents time_t
3153 * overflows. */
3154 #define MAX_MAX_CIRCUIT_DIRTINESS (30*24*60*60)
3156 /** Lowest allowable value for CircuitStreamTimeout; if this is too low, Tor
3157 * will generate too many circuits and potentially overload the network. */
3158 #define MIN_CIRCUIT_STREAM_TIMEOUT 10
3160 /** Lowest recommended value for CircuitBuildTimeout; if it is set too low
3161 * and LearnCircuitBuildTimeout is off, the failure rate for circuit
3162 * construction may be very high. In that case, if it is set below this
3163 * threshold emit a warning.
3164 * */
3165 #define RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT (10)
3168 * Validate <b>new_options</b>. If it is valid, and it is a reasonable
3169 * replacement for <b>old_options</b>, replace the previous value of the
3170 * global options, and return return SETOPT_OK.
3172 * If it is not valid, then free <b>new_options</b>, set *<b>msg_out</b> to a
3173 * newly allocated error message, and return an error code.
3175 static setopt_err_t
3176 options_validate_and_set(const or_options_t *old_options,
3177 or_options_t *new_options,
3178 char **msg_out)
3180 setopt_err_t rv;
3181 validation_status_t vs;
3183 in_option_validation = 1;
3184 vs = config_validate(get_options_mgr(), old_options, new_options, msg_out);
3186 if (vs == VSTAT_TRANSITION_ERR) {
3187 rv = SETOPT_ERR_TRANSITION;
3188 goto err;
3189 } else if (vs < 0) {
3190 rv = SETOPT_ERR_PARSE;
3191 goto err;
3193 in_option_validation = 0;
3195 if (set_options(new_options, msg_out)) {
3196 rv = SETOPT_ERR_SETTING;
3197 goto err;
3200 rv = SETOPT_OK;
3201 new_options = NULL; /* prevent free */
3202 err:
3203 in_option_validation = 0;
3204 tor_assert(new_options == NULL || rv != SETOPT_OK);
3205 or_options_free(new_options);
3206 return rv;
3209 #ifdef TOR_UNIT_TESTS
3211 * Return 0 if every setting in <b>options</b> is reasonable, is a
3212 * permissible transition from <b>old_options</b>, and none of the
3213 * testing-only settings differ from <b>default_options</b> unless in
3214 * testing mode. Else return -1. Should have no side effects, except for
3215 * normalizing the contents of <b>options</b>.
3217 * On error, tor_strdup an error explanation into *<b>msg</b>.
3220 options_validate(const or_options_t *old_options, or_options_t *options,
3221 char **msg)
3223 validation_status_t vs;
3224 vs = config_validate(get_options_mgr(), old_options, options, msg);
3225 return vs < 0 ? -1 : 0;
3227 #endif /* defined(TOR_UNIT_TESTS) */
3229 #define REJECT(arg) \
3230 STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
3231 #if defined(__GNUC__) && __GNUC__ <= 3
3232 #define COMPLAIN(args...) \
3233 STMT_BEGIN log_warn(LD_CONFIG, args); STMT_END
3234 #else
3235 #define COMPLAIN(args, ...) \
3236 STMT_BEGIN log_warn(LD_CONFIG, args, ##__VA_ARGS__); STMT_END
3237 #endif /* defined(__GNUC__) && __GNUC__ <= 3 */
3239 /** Log a warning message iff <b>filepath</b> is not absolute.
3240 * Warning message must contain option name <b>option</b> and
3241 * an absolute path that <b>filepath</b> will resolve to.
3243 * In case <b>filepath</b> is absolute, do nothing.
3245 * Return 1 if there were relative paths; 0 otherwise.
3247 static int
3248 warn_if_option_path_is_relative(const char *option,
3249 const char *filepath)
3251 if (filepath && path_is_relative(filepath)) {
3252 char *abs_path = make_path_absolute(filepath);
3253 COMPLAIN("Path for %s (%s) is relative and will resolve to %s."
3254 " Is this what you wanted?", option, filepath, abs_path);
3255 tor_free(abs_path);
3256 return 1;
3258 return 0;
3261 /** Scan <b>options</b> for occurrences of relative file/directory
3262 * paths and log a warning whenever one is found.
3264 * Return 1 if there were relative paths; 0 otherwise.
3266 static int
3267 warn_about_relative_paths(const or_options_t *options)
3269 tor_assert(options);
3270 int n = 0;
3271 const config_mgr_t *mgr = get_options_mgr();
3273 smartlist_t *vars = config_mgr_list_vars(mgr);
3274 SMARTLIST_FOREACH_BEGIN(vars, const config_var_t *, cv) {
3275 config_line_t *line;
3276 if (cv->member.type != CONFIG_TYPE_FILENAME)
3277 continue;
3278 const char *name = cv->member.name;
3279 line = config_get_assigned_option(mgr, options, name, 0);
3280 if (line)
3281 n += warn_if_option_path_is_relative(name, line->value);
3282 config_free_lines(line);
3283 } SMARTLIST_FOREACH_END(cv);
3284 smartlist_free(vars);
3286 for (config_line_t *hs_line = options->RendConfigLines; hs_line;
3287 hs_line = hs_line->next) {
3288 if (!strcasecmp(hs_line->key, "HiddenServiceDir"))
3289 n += warn_if_option_path_is_relative("HiddenServiceDir",hs_line->value);
3291 return n != 0;
3294 /* Validate options related to the scheduler. From the Schedulers list, the
3295 * SchedulerTypes_ list is created with int values so once we select the
3296 * scheduler, which can happen anytime at runtime, we don't have to parse
3297 * strings and thus be quick.
3299 * Return 0 on success else -1 and msg is set with an error message. */
3300 static int
3301 options_validate_scheduler(or_options_t *options, char **msg)
3303 tor_assert(options);
3304 tor_assert(msg);
3306 if (!options->Schedulers || smartlist_len(options->Schedulers) == 0) {
3307 REJECT("Empty Schedulers list. Either remove the option so the defaults "
3308 "can be used or set at least one value.");
3310 /* Ok, we do have scheduler types, validate them. */
3311 if (options->SchedulerTypes_) {
3312 SMARTLIST_FOREACH(options->SchedulerTypes_, int *, iptr, tor_free(iptr));
3313 smartlist_free(options->SchedulerTypes_);
3315 options->SchedulerTypes_ = smartlist_new();
3316 SMARTLIST_FOREACH_BEGIN(options->Schedulers, const char *, type) {
3317 int *sched_type;
3318 if (!strcasecmp("KISTLite", type)) {
3319 sched_type = tor_malloc_zero(sizeof(int));
3320 *sched_type = SCHEDULER_KIST_LITE;
3321 smartlist_add(options->SchedulerTypes_, sched_type);
3322 } else if (!strcasecmp("KIST", type)) {
3323 sched_type = tor_malloc_zero(sizeof(int));
3324 *sched_type = SCHEDULER_KIST;
3325 smartlist_add(options->SchedulerTypes_, sched_type);
3326 } else if (!strcasecmp("Vanilla", type)) {
3327 sched_type = tor_malloc_zero(sizeof(int));
3328 *sched_type = SCHEDULER_VANILLA;
3329 smartlist_add(options->SchedulerTypes_, sched_type);
3330 } else {
3331 tor_asprintf(msg, "Unknown type %s in option Schedulers. "
3332 "Possible values are KIST, KISTLite and Vanilla.",
3333 escaped(type));
3334 return -1;
3336 } SMARTLIST_FOREACH_END(type);
3338 if (options->KISTSockBufSizeFactor < 0) {
3339 REJECT("KISTSockBufSizeFactor must be at least 0");
3342 /* Don't need to validate that the Interval is less than anything because
3343 * zero is valid and all negative values are valid. */
3344 if (options->KISTSchedRunInterval > KIST_SCHED_RUN_INTERVAL_MAX) {
3345 tor_asprintf(msg, "KISTSchedRunInterval must not be more than %d (ms)",
3346 KIST_SCHED_RUN_INTERVAL_MAX);
3347 return -1;
3350 return 0;
3353 /* Validate options related to single onion services.
3354 * Modifies some options that are incompatible with single onion services.
3355 * On failure returns -1, and sets *msg to an error string.
3356 * Returns 0 on success. */
3357 STATIC int
3358 options_validate_single_onion(or_options_t *options, char **msg)
3360 /* The two single onion service options must have matching values. */
3361 if (options->HiddenServiceSingleHopMode &&
3362 !options->HiddenServiceNonAnonymousMode) {
3363 REJECT("HiddenServiceSingleHopMode does not provide any server anonymity. "
3364 "It must be used with HiddenServiceNonAnonymousMode set to 1.");
3366 if (options->HiddenServiceNonAnonymousMode &&
3367 !options->HiddenServiceSingleHopMode) {
3368 REJECT("HiddenServiceNonAnonymousMode does not provide any server "
3369 "anonymity. It must be used with HiddenServiceSingleHopMode set to "
3370 "1.");
3373 /* Now that we've checked that the two options are consistent, we can safely
3374 * call the rend_service_* functions that abstract these options. */
3376 /* If you run an anonymous client with an active Single Onion service, the
3377 * client loses anonymity. */
3378 const int client_port_set = (options->SocksPort_set ||
3379 options->TransPort_set ||
3380 options->NATDPort_set ||
3381 options->DNSPort_set ||
3382 options->HTTPTunnelPort_set);
3383 if (rend_service_non_anonymous_mode_enabled(options) && client_port_set) {
3384 REJECT("HiddenServiceNonAnonymousMode is incompatible with using Tor as "
3385 "an anonymous client. Please set Socks/Trans/NATD/DNSPort to 0, or "
3386 "revert HiddenServiceNonAnonymousMode to 0.");
3389 if (rend_service_allow_non_anonymous_connection(options)
3390 && options->UseEntryGuards) {
3391 /* Single Onion services only use entry guards when uploading descriptors;
3392 * all other connections are one-hop. Further, Single Onions causes the
3393 * hidden service code to do things which break the path bias
3394 * detector, and it's far easier to turn off entry guards (and
3395 * thus the path bias detector with it) than to figure out how to
3396 * make path bias compatible with single onions.
3398 log_notice(LD_CONFIG,
3399 "HiddenServiceSingleHopMode is enabled; disabling "
3400 "UseEntryGuards.");
3401 options->UseEntryGuards = 0;
3404 return 0;
3408 * Legacy validation/normalization callback for or_options_t. See
3409 * legacy_validate_fn_t for more information.
3411 static int
3412 options_validate_cb(const void *old_options_, void *options_, char **msg)
3414 if (old_options_)
3415 CHECK_OPTIONS_MAGIC(old_options_);
3416 CHECK_OPTIONS_MAGIC(options_);
3417 const or_options_t *old_options = old_options_;
3418 or_options_t *options = options_;
3420 config_line_t *cl;
3421 int n_ports=0;
3422 int world_writable_control_socket=0;
3424 tor_assert(msg);
3425 *msg = NULL;
3427 if (parse_ports(options, 1, msg, &n_ports,
3428 &world_writable_control_socket) < 0)
3429 return -1;
3431 #ifndef HAVE_SYS_UN_H
3432 if (options->ControlSocket || options->ControlSocketsGroupWritable) {
3433 *msg = tor_strdup("Unix domain sockets (ControlSocket) not supported "
3434 "on this OS/with this build.");
3435 return -1;
3437 #else /* defined(HAVE_SYS_UN_H) */
3438 if (options->ControlSocketsGroupWritable && !options->ControlSocket) {
3439 *msg = tor_strdup("Setting ControlSocketGroupWritable without setting "
3440 "a ControlSocket makes no sense.");
3441 return -1;
3443 #endif /* !defined(HAVE_SYS_UN_H) */
3445 /* Set UseEntryGuards from the configured value, before we check it below.
3446 * We change UseEntryGuards when it's incompatible with other options,
3447 * but leave UseEntryGuards_option with the original value.
3448 * Always use the value of UseEntryGuards, not UseEntryGuards_option. */
3449 options->UseEntryGuards = options->UseEntryGuards_option;
3451 if (options_validate_relay_os(old_options, options, msg) < 0)
3452 return -1;
3454 /* 31851: OutboundBindAddressExit is unused in client mode */
3455 if (parse_outbound_addresses(options, 1, msg) < 0)
3456 return -1;
3458 if (validate_data_directories(options)<0)
3459 REJECT("Invalid DataDirectory");
3461 /* need to check for relative paths after we populate
3462 * options->DataDirectory (just above). */
3463 if (warn_about_relative_paths(options) && options->RunAsDaemon) {
3464 REJECT("You have specified at least one relative path (see above) "
3465 "with the RunAsDaemon option. RunAsDaemon is not compatible "
3466 "with relative paths.");
3469 if (options_validate_relay_info(old_options, options, msg) < 0)
3470 return -1;
3472 /* 31851: this function is currently a no-op in client mode */
3473 check_network_configuration(server_mode(options));
3475 /* Validate the tor_log(s) */
3476 if (options_init_logs(old_options, options, 1)<0)
3477 REJECT("Failed to validate Log options. See logs for details.");
3479 /* XXXX require that the only port not be DirPort? */
3480 /* XXXX require that at least one port be listened-upon. */
3481 if (n_ports == 0 && !options->RendConfigLines)
3482 log_warn(LD_CONFIG,
3483 "SocksPort, TransPort, NATDPort, DNSPort, and ORPort are all "
3484 "undefined, and there aren't any hidden services configured. "
3485 "Tor will still run, but probably won't do anything.");
3487 options->TransProxyType_parsed = TPT_DEFAULT;
3488 #ifdef USE_TRANSPARENT
3489 if (options->TransProxyType) {
3490 if (!strcasecmp(options->TransProxyType, "default")) {
3491 options->TransProxyType_parsed = TPT_DEFAULT;
3492 } else if (!strcasecmp(options->TransProxyType, "pf-divert")) {
3493 #if !defined(OpenBSD) && !defined(DARWIN)
3494 /* Later versions of OS X have pf */
3495 REJECT("pf-divert is a OpenBSD-specific "
3496 "and OS X/Darwin-specific feature.");
3497 #else
3498 options->TransProxyType_parsed = TPT_PF_DIVERT;
3499 #endif /* !defined(OpenBSD) && !defined(DARWIN) */
3500 } else if (!strcasecmp(options->TransProxyType, "tproxy")) {
3501 #if !defined(__linux__)
3502 REJECT("TPROXY is a Linux-specific feature.");
3503 #else
3504 options->TransProxyType_parsed = TPT_TPROXY;
3505 #endif
3506 } else if (!strcasecmp(options->TransProxyType, "ipfw")) {
3507 #ifndef KERNEL_MAY_SUPPORT_IPFW
3508 /* Earlier versions of OS X have ipfw */
3509 REJECT("ipfw is a FreeBSD-specific "
3510 "and OS X/Darwin-specific feature.");
3511 #else
3512 options->TransProxyType_parsed = TPT_IPFW;
3513 #endif /* !defined(KERNEL_MAY_SUPPORT_IPFW) */
3514 } else {
3515 REJECT("Unrecognized value for TransProxyType");
3518 if (strcasecmp(options->TransProxyType, "default") &&
3519 !options->TransPort_set) {
3520 REJECT("Cannot use TransProxyType without any valid TransPort.");
3523 #else /* !defined(USE_TRANSPARENT) */
3524 if (options->TransPort_set)
3525 REJECT("TransPort is disabled in this build.");
3526 #endif /* defined(USE_TRANSPARENT) */
3528 if (options->TokenBucketRefillInterval <= 0
3529 || options->TokenBucketRefillInterval > 1000) {
3530 REJECT("TokenBucketRefillInterval must be between 1 and 1000 inclusive.");
3533 if (options->ExcludeExitNodes || options->ExcludeNodes) {
3534 options->ExcludeExitNodesUnion_ = routerset_new();
3535 routerset_union(options->ExcludeExitNodesUnion_,options->ExcludeExitNodes);
3536 routerset_union(options->ExcludeExitNodesUnion_,options->ExcludeNodes);
3539 if (options->NodeFamilies) {
3540 options->NodeFamilySets = smartlist_new();
3541 for (cl = options->NodeFamilies; cl; cl = cl->next) {
3542 routerset_t *rs = routerset_new();
3543 if (routerset_parse(rs, cl->value, cl->key) == 0) {
3544 smartlist_add(options->NodeFamilySets, rs);
3545 } else {
3546 routerset_free(rs);
3551 if (options->ExcludeNodes && options->StrictNodes) {
3552 COMPLAIN("You have asked to exclude certain relays from all positions "
3553 "in your circuits. Expect hidden services and other Tor "
3554 "features to be broken in unpredictable ways.");
3557 if (options_validate_dirauth_mode(old_options, options, msg) < 0)
3558 return -1;
3560 if (options->FetchDirInfoExtraEarly && !options->FetchDirInfoEarly)
3561 REJECT("FetchDirInfoExtraEarly requires that you also set "
3562 "FetchDirInfoEarly");
3564 if (options->ConnLimit <= 0) {
3565 tor_asprintf(msg,
3566 "ConnLimit must be greater than 0, but was set to %d",
3567 options->ConnLimit);
3568 return -1;
3571 if (options->PathsNeededToBuildCircuits >= 0.0) {
3572 if (options->PathsNeededToBuildCircuits < 0.25) {
3573 log_warn(LD_CONFIG, "PathsNeededToBuildCircuits is too low. Increasing "
3574 "to 0.25");
3575 options->PathsNeededToBuildCircuits = 0.25;
3576 } else if (options->PathsNeededToBuildCircuits > 0.95) {
3577 log_warn(LD_CONFIG, "PathsNeededToBuildCircuits is too high. Decreasing "
3578 "to 0.95");
3579 options->PathsNeededToBuildCircuits = 0.95;
3583 if (options->MaxClientCircuitsPending <= 0 ||
3584 options->MaxClientCircuitsPending > MAX_MAX_CLIENT_CIRCUITS_PENDING) {
3585 tor_asprintf(msg,
3586 "MaxClientCircuitsPending must be between 1 and %d, but "
3587 "was set to %d", MAX_MAX_CLIENT_CIRCUITS_PENDING,
3588 options->MaxClientCircuitsPending);
3589 return -1;
3592 if (validate_ports_csv(options->FirewallPorts, "FirewallPorts", msg) < 0)
3593 return -1;
3595 if (validate_ports_csv(options->LongLivedPorts, "LongLivedPorts", msg) < 0)
3596 return -1;
3598 if (validate_ports_csv(options->RejectPlaintextPorts,
3599 "RejectPlaintextPorts", msg) < 0)
3600 return -1;
3602 if (validate_ports_csv(options->WarnPlaintextPorts,
3603 "WarnPlaintextPorts", msg) < 0)
3604 return -1;
3606 if (options->FascistFirewall && !options->ReachableAddresses) {
3607 if (options->FirewallPorts && smartlist_len(options->FirewallPorts)) {
3608 /* We already have firewall ports set, so migrate them to
3609 * ReachableAddresses, which will set ReachableORAddresses and
3610 * ReachableDirAddresses if they aren't set explicitly. */
3611 smartlist_t *instead = smartlist_new();
3612 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3613 new_line->key = tor_strdup("ReachableAddresses");
3614 /* If we're configured with the old format, we need to prepend some
3615 * open ports. */
3616 SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
3618 int p = atoi(portno);
3619 if (p<0) continue;
3620 smartlist_add_asprintf(instead, "*:%d", p);
3622 new_line->value = smartlist_join_strings(instead,",",0,NULL);
3623 /* These have been deprecated since 0.1.1.5-alpha-cvs */
3624 log_notice(LD_CONFIG,
3625 "Converting FascistFirewall and FirewallPorts "
3626 "config options to new format: \"ReachableAddresses %s\"",
3627 new_line->value);
3628 options->ReachableAddresses = new_line;
3629 SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
3630 smartlist_free(instead);
3631 } else {
3632 /* We do not have FirewallPorts set, so add 80 to
3633 * ReachableDirAddresses, and 443 to ReachableORAddresses. */
3634 if (!options->ReachableDirAddresses) {
3635 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3636 new_line->key = tor_strdup("ReachableDirAddresses");
3637 new_line->value = tor_strdup("*:80");
3638 options->ReachableDirAddresses = new_line;
3639 log_notice(LD_CONFIG, "Converting FascistFirewall config option "
3640 "to new format: \"ReachableDirAddresses *:80\"");
3642 if (!options->ReachableORAddresses) {
3643 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3644 new_line->key = tor_strdup("ReachableORAddresses");
3645 new_line->value = tor_strdup("*:443");
3646 options->ReachableORAddresses = new_line;
3647 log_notice(LD_CONFIG, "Converting FascistFirewall config option "
3648 "to new format: \"ReachableORAddresses *:443\"");
3653 if ((options->ReachableAddresses ||
3654 options->ReachableORAddresses ||
3655 options->ReachableDirAddresses ||
3656 options->ClientUseIPv4 == 0) &&
3657 server_mode(options))
3658 REJECT("Servers must be able to freely connect to the rest "
3659 "of the Internet, so they must not set Reachable*Addresses "
3660 "or FascistFirewall or FirewallPorts or ClientUseIPv4 0.");
3662 if (options->UseBridges &&
3663 server_mode(options))
3664 REJECT("Servers must be able to freely connect to the rest "
3665 "of the Internet, so they must not set UseBridges.");
3667 /* If both of these are set, we'll end up with funny behavior where we
3668 * demand enough entrynodes be up and running else we won't build
3669 * circuits, yet we never actually use them. */
3670 if (options->UseBridges && options->EntryNodes)
3671 REJECT("You cannot set both UseBridges and EntryNodes.");
3673 /* If we have UseBridges as 1 and UseEntryGuards as 0, we end up bypassing
3674 * the use of bridges */
3675 if (options->UseBridges && !options->UseEntryGuards)
3676 REJECT("Setting UseBridges requires also setting UseEntryGuards.");
3678 options->MaxMemInQueues =
3679 compute_real_max_mem_in_queues(options->MaxMemInQueues_raw,
3680 server_mode(options));
3681 options->MaxMemInQueues_low_threshold = (options->MaxMemInQueues / 4) * 3;
3683 if (!options->SafeLogging ||
3684 !strcasecmp(options->SafeLogging, "0")) {
3685 options->SafeLogging_ = SAFELOG_SCRUB_NONE;
3686 } else if (!strcasecmp(options->SafeLogging, "relay")) {
3687 options->SafeLogging_ = SAFELOG_SCRUB_RELAY;
3688 } else if (!strcasecmp(options->SafeLogging, "1")) {
3689 options->SafeLogging_ = SAFELOG_SCRUB_ALL;
3690 } else {
3691 tor_asprintf(msg,
3692 "Unrecognized value '%s' in SafeLogging",
3693 escaped(options->SafeLogging));
3694 return -1;
3697 if (options_validate_publish_server(old_options, options, msg) < 0)
3698 return -1;
3700 if (options_validate_relay_padding(old_options, options, msg) < 0)
3701 return -1;
3703 const int min_rendpostperiod =
3704 options->TestingTorNetwork ?
3705 MIN_REND_POST_PERIOD_TESTING : MIN_REND_POST_PERIOD;
3706 if (options->RendPostPeriod < min_rendpostperiod) {
3707 log_warn(LD_CONFIG, "RendPostPeriod option is too short; "
3708 "raising to %d seconds.", min_rendpostperiod);
3709 options->RendPostPeriod = min_rendpostperiod;
3712 if (options->RendPostPeriod > MAX_DIR_PERIOD) {
3713 log_warn(LD_CONFIG, "RendPostPeriod is too large; clipping to %ds.",
3714 MAX_DIR_PERIOD);
3715 options->RendPostPeriod = MAX_DIR_PERIOD;
3718 /* Check the Single Onion Service options */
3719 if (options_validate_single_onion(options, msg) < 0)
3720 return -1;
3722 if (options->CircuitsAvailableTimeout > MAX_CIRCS_AVAILABLE_TIME) {
3723 // options_t is immutable for new code (the above code is older),
3724 // so just make the user fix the value themselves rather than
3725 // silently keep a shadow value lower than what they asked for.
3726 REJECT("CircuitsAvailableTimeout is too large. Max is 24 hours.");
3729 if (options->EntryNodes && !options->UseEntryGuards) {
3730 REJECT("If EntryNodes is set, UseEntryGuards must be enabled.");
3733 if (!(options->UseEntryGuards) &&
3734 (options->RendConfigLines != NULL) &&
3735 !rend_service_allow_non_anonymous_connection(options)) {
3736 log_warn(LD_CONFIG,
3737 "UseEntryGuards is disabled, but you have configured one or more "
3738 "hidden services on this Tor instance. Your hidden services "
3739 "will be very easy to locate using a well-known attack -- see "
3740 "http://freehaven.net/anonbib/#hs-attack06 for details.");
3743 if (options->NumPrimaryGuards && options->NumEntryGuards &&
3744 options->NumEntryGuards > options->NumPrimaryGuards) {
3745 REJECT("NumEntryGuards must not be greater than NumPrimaryGuards.");
3748 if (options->EntryNodes &&
3749 routerset_is_list(options->EntryNodes) &&
3750 (routerset_len(options->EntryNodes) == 1) &&
3751 (options->RendConfigLines != NULL)) {
3752 tor_asprintf(msg,
3753 "You have one single EntryNodes and at least one hidden service "
3754 "configured. This is bad because it's very easy to locate your "
3755 "entry guard which can then lead to the deanonymization of your "
3756 "hidden service -- for more details, see "
3757 "https://trac.torproject.org/projects/tor/ticket/14917. "
3758 "For this reason, the use of one EntryNodes with an hidden "
3759 "service is prohibited until a better solution is found.");
3760 return -1;
3763 /* Inform the hidden service operator that pinning EntryNodes can possibly
3764 * be harmful for the service anonymity. */
3765 if (options->EntryNodes &&
3766 routerset_is_list(options->EntryNodes) &&
3767 (options->RendConfigLines != NULL)) {
3768 log_warn(LD_CONFIG,
3769 "EntryNodes is set with multiple entries and at least one "
3770 "hidden service is configured. Pinning entry nodes can possibly "
3771 "be harmful to the service anonymity. Because of this, we "
3772 "recommend you either don't do that or make sure you know what "
3773 "you are doing. For more details, please look at "
3774 "https://trac.torproject.org/projects/tor/ticket/21155.");
3777 /* Single Onion Services: non-anonymous hidden services */
3778 if (rend_service_non_anonymous_mode_enabled(options)) {
3779 log_warn(LD_CONFIG,
3780 "HiddenServiceNonAnonymousMode is set. Every hidden service on "
3781 "this tor instance is NON-ANONYMOUS. If "
3782 "the HiddenServiceNonAnonymousMode option is changed, Tor will "
3783 "refuse to launch hidden services from the same directories, to "
3784 "protect your anonymity against config errors. This setting is "
3785 "for experimental use only.");
3788 if (!options->LearnCircuitBuildTimeout && options->CircuitBuildTimeout &&
3789 options->CircuitBuildTimeout < RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT) {
3790 log_warn(LD_CONFIG,
3791 "CircuitBuildTimeout is shorter (%d seconds) than the recommended "
3792 "minimum (%d seconds), and LearnCircuitBuildTimeout is disabled. "
3793 "If tor isn't working, raise this value or enable "
3794 "LearnCircuitBuildTimeout.",
3795 options->CircuitBuildTimeout,
3796 RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT );
3797 } else if (!options->LearnCircuitBuildTimeout &&
3798 !options->CircuitBuildTimeout) {
3799 int severity = LOG_NOTICE;
3800 /* Be a little quieter if we've deliberately disabled
3801 * LearnCircuitBuildTimeout. */
3802 if (circuit_build_times_disabled_(options, 1)) {
3803 severity = LOG_INFO;
3805 log_fn(severity, LD_CONFIG, "You disabled LearnCircuitBuildTimeout, but "
3806 "didn't specify a CircuitBuildTimeout. I'll pick a plausible "
3807 "default.");
3810 if (options->DormantClientTimeout < 10*60 && !options->TestingTorNetwork) {
3811 REJECT("DormantClientTimeout is too low. It must be at least 10 minutes.");
3814 if (options->PathBiasNoticeRate > 1.0) {
3815 tor_asprintf(msg,
3816 "PathBiasNoticeRate is too high. "
3817 "It must be between 0 and 1.0");
3818 return -1;
3820 if (options->PathBiasWarnRate > 1.0) {
3821 tor_asprintf(msg,
3822 "PathBiasWarnRate is too high. "
3823 "It must be between 0 and 1.0");
3824 return -1;
3826 if (options->PathBiasExtremeRate > 1.0) {
3827 tor_asprintf(msg,
3828 "PathBiasExtremeRate is too high. "
3829 "It must be between 0 and 1.0");
3830 return -1;
3832 if (options->PathBiasNoticeUseRate > 1.0) {
3833 tor_asprintf(msg,
3834 "PathBiasNoticeUseRate is too high. "
3835 "It must be between 0 and 1.0");
3836 return -1;
3838 if (options->PathBiasExtremeUseRate > 1.0) {
3839 tor_asprintf(msg,
3840 "PathBiasExtremeUseRate is too high. "
3841 "It must be between 0 and 1.0");
3842 return -1;
3845 if (options->MaxCircuitDirtiness < MIN_MAX_CIRCUIT_DIRTINESS) {
3846 log_warn(LD_CONFIG, "MaxCircuitDirtiness option is too short; "
3847 "raising to %d seconds.", MIN_MAX_CIRCUIT_DIRTINESS);
3848 options->MaxCircuitDirtiness = MIN_MAX_CIRCUIT_DIRTINESS;
3851 if (options->MaxCircuitDirtiness > MAX_MAX_CIRCUIT_DIRTINESS) {
3852 log_warn(LD_CONFIG, "MaxCircuitDirtiness option is too high; "
3853 "setting to %d days.", MAX_MAX_CIRCUIT_DIRTINESS/86400);
3854 options->MaxCircuitDirtiness = MAX_MAX_CIRCUIT_DIRTINESS;
3857 if (options->CircuitStreamTimeout &&
3858 options->CircuitStreamTimeout < MIN_CIRCUIT_STREAM_TIMEOUT) {
3859 log_warn(LD_CONFIG, "CircuitStreamTimeout option is too short; "
3860 "raising to %d seconds.", MIN_CIRCUIT_STREAM_TIMEOUT);
3861 options->CircuitStreamTimeout = MIN_CIRCUIT_STREAM_TIMEOUT;
3864 if (options->HeartbeatPeriod &&
3865 options->HeartbeatPeriod < MIN_HEARTBEAT_PERIOD &&
3866 !options->TestingTorNetwork) {
3867 log_warn(LD_CONFIG, "HeartbeatPeriod option is too short; "
3868 "raising to %d seconds.", MIN_HEARTBEAT_PERIOD);
3869 options->HeartbeatPeriod = MIN_HEARTBEAT_PERIOD;
3872 if (options->KeepalivePeriod < 1)
3873 REJECT("KeepalivePeriod option must be positive.");
3875 if (config_ensure_bandwidth_cap(&options->BandwidthRate,
3876 "BandwidthRate", msg) < 0)
3877 return -1;
3878 if (config_ensure_bandwidth_cap(&options->BandwidthBurst,
3879 "BandwidthBurst", msg) < 0)
3880 return -1;
3882 if (options_validate_relay_bandwidth(old_options, options, msg) < 0)
3883 return -1;
3884 if (options_validate_dirauth_bandwidth(old_options, options, msg) < 0)
3885 return -1;
3887 if (options->BandwidthRate > options->BandwidthBurst)
3888 REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
3890 if (options_validate_relay_accounting(old_options, options, msg) < 0)
3891 return -1;
3893 if (options_validate_relay_mode(old_options, options, msg) < 0)
3894 return -1;
3896 if (options->HTTPProxy) { /* parse it now */
3897 if (tor_addr_port_lookup(options->HTTPProxy,
3898 &options->HTTPProxyAddr, &options->HTTPProxyPort) < 0)
3899 REJECT("HTTPProxy failed to parse or resolve. Please fix.");
3900 if (options->HTTPProxyPort == 0) { /* give it a default */
3901 options->HTTPProxyPort = 80;
3905 if (options->HTTPProxyAuthenticator) {
3906 if (strlen(options->HTTPProxyAuthenticator) >= 512)
3907 REJECT("HTTPProxyAuthenticator is too long (>= 512 chars).");
3910 if (options->HTTPSProxy) { /* parse it now */
3911 if (tor_addr_port_lookup(options->HTTPSProxy,
3912 &options->HTTPSProxyAddr, &options->HTTPSProxyPort) <0)
3913 REJECT("HTTPSProxy failed to parse or resolve. Please fix.");
3914 if (options->HTTPSProxyPort == 0) { /* give it a default */
3915 options->HTTPSProxyPort = 443;
3919 if (options->HTTPSProxyAuthenticator) {
3920 if (strlen(options->HTTPSProxyAuthenticator) >= 512)
3921 REJECT("HTTPSProxyAuthenticator is too long (>= 512 chars).");
3924 if (options->Socks4Proxy) { /* parse it now */
3925 if (tor_addr_port_lookup(options->Socks4Proxy,
3926 &options->Socks4ProxyAddr,
3927 &options->Socks4ProxyPort) <0)
3928 REJECT("Socks4Proxy failed to parse or resolve. Please fix.");
3929 if (options->Socks4ProxyPort == 0) { /* give it a default */
3930 options->Socks4ProxyPort = 1080;
3934 if (options->Socks5Proxy) { /* parse it now */
3935 if (tor_addr_port_lookup(options->Socks5Proxy,
3936 &options->Socks5ProxyAddr,
3937 &options->Socks5ProxyPort) <0)
3938 REJECT("Socks5Proxy failed to parse or resolve. Please fix.");
3939 if (options->Socks5ProxyPort == 0) { /* give it a default */
3940 options->Socks5ProxyPort = 1080;
3944 if (options->TCPProxy) {
3945 int res = parse_tcp_proxy_line(options->TCPProxy, options, msg);
3946 if (res < 0) {
3947 return res;
3951 /* Check if more than one exclusive proxy type has been enabled. */
3952 if (!!options->Socks4Proxy + !!options->Socks5Proxy +
3953 !!options->HTTPSProxy + !!options->TCPProxy > 1)
3954 REJECT("You have configured more than one proxy type. "
3955 "(Socks4Proxy|Socks5Proxy|HTTPSProxy|TCPProxy)");
3957 /* Check if the proxies will give surprising behavior. */
3958 if (options->HTTPProxy && !(options->Socks4Proxy ||
3959 options->Socks5Proxy ||
3960 options->HTTPSProxy ||
3961 options->TCPProxy)) {
3962 log_warn(LD_CONFIG, "HTTPProxy configured, but no SOCKS proxy, "
3963 "HTTPS proxy, or any other TCP proxy configured. Watch out: "
3964 "this configuration will proxy unencrypted directory "
3965 "connections only.");
3968 if (options->Socks5ProxyUsername) {
3969 size_t len;
3971 len = strlen(options->Socks5ProxyUsername);
3972 if (len < 1 || len > MAX_SOCKS5_AUTH_FIELD_SIZE)
3973 REJECT("Socks5ProxyUsername must be between 1 and 255 characters.");
3975 if (!options->Socks5ProxyPassword)
3976 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
3978 len = strlen(options->Socks5ProxyPassword);
3979 if (len < 1 || len > MAX_SOCKS5_AUTH_FIELD_SIZE)
3980 REJECT("Socks5ProxyPassword must be between 1 and 255 characters.");
3981 } else if (options->Socks5ProxyPassword)
3982 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
3984 if (options->HashedControlPassword) {
3985 smartlist_t *sl = decode_hashed_passwords(options->HashedControlPassword);
3986 if (!sl) {
3987 REJECT("Bad HashedControlPassword: wrong length or bad encoding");
3988 } else {
3989 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3990 smartlist_free(sl);
3994 if (options->HashedControlSessionPassword) {
3995 smartlist_t *sl = decode_hashed_passwords(
3996 options->HashedControlSessionPassword);
3997 if (!sl) {
3998 REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
3999 } else {
4000 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
4001 smartlist_free(sl);
4005 if (options->OwningControllerProcess) {
4006 const char *validate_pspec_msg = NULL;
4007 if (tor_validate_process_specifier(options->OwningControllerProcess,
4008 &validate_pspec_msg)) {
4009 tor_asprintf(msg, "Bad OwningControllerProcess: %s",
4010 validate_pspec_msg);
4011 return -1;
4015 if ((options->ControlPort_set || world_writable_control_socket) &&
4016 !options->HashedControlPassword &&
4017 !options->HashedControlSessionPassword &&
4018 !options->CookieAuthentication) {
4019 log_warn(LD_CONFIG, "Control%s is %s, but no authentication method "
4020 "has been configured. This means that any program on your "
4021 "computer can reconfigure your Tor. That's bad! You should "
4022 "upgrade your Tor controller as soon as possible.",
4023 options->ControlPort_set ? "Port" : "Socket",
4024 options->ControlPort_set ? "open" : "world writable");
4027 if (options->CookieAuthFileGroupReadable && !options->CookieAuthFile) {
4028 log_warn(LD_CONFIG, "CookieAuthFileGroupReadable is set, but will have "
4029 "no effect: you must specify an explicit CookieAuthFile to "
4030 "have it group-readable.");
4033 for (cl = options->NodeFamilies; cl; cl = cl->next) {
4034 routerset_t *rs = routerset_new();
4035 if (routerset_parse(rs, cl->value, cl->key)) {
4036 routerset_free(rs);
4037 return -1;
4039 routerset_free(rs);
4042 if (validate_addr_policies(options, msg) < 0)
4043 return -1;
4045 /* If FallbackDir is set, we don't UseDefaultFallbackDirs */
4046 if (options->UseDefaultFallbackDirs && options->FallbackDir) {
4047 log_info(LD_CONFIG, "You have set UseDefaultFallbackDirs 1 and "
4048 "FallbackDir(s). Ignoring UseDefaultFallbackDirs, and "
4049 "using the FallbackDir(s) you have set.");
4052 if (validate_dir_servers(options, old_options) < 0)
4053 REJECT("Directory authority/fallback line did not parse. See logs "
4054 "for details.");
4056 if (options->UseBridges && !options->Bridges)
4057 REJECT("If you set UseBridges, you must specify at least one bridge.");
4059 for (cl = options->Bridges; cl; cl = cl->next) {
4060 bridge_line_t *bridge_line = parse_bridge_line(cl->value);
4061 if (!bridge_line)
4062 REJECT("Bridge line did not parse. See logs for details.");
4063 bridge_line_free(bridge_line);
4066 for (cl = options->ClientTransportPlugin; cl; cl = cl->next) {
4067 if (pt_parse_transport_line(options, cl->value, 1, 0) < 0)
4068 REJECT("Invalid client transport line. See logs for details.");
4071 if (options_validate_server_transport(old_options, options, msg) < 0)
4072 return -1;
4074 if (options->ConstrainedSockets) {
4075 /* If the user wants to constrain socket buffer use, make sure the desired
4076 * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
4077 if (options->ConstrainedSockSize < MIN_CONSTRAINED_TCP_BUFFER ||
4078 options->ConstrainedSockSize > MAX_CONSTRAINED_TCP_BUFFER ||
4079 options->ConstrainedSockSize % 1024) {
4080 tor_asprintf(msg,
4081 "ConstrainedSockSize is invalid. Must be a value between %d and %d "
4082 "in 1024 byte increments.",
4083 MIN_CONSTRAINED_TCP_BUFFER, MAX_CONSTRAINED_TCP_BUFFER);
4084 return -1;
4088 if (options_validate_dirauth_schedule(old_options, options, msg) < 0)
4089 return -1;
4091 if (hs_config_service_all(options, 1) < 0)
4092 REJECT("Failed to configure rendezvous options. See logs for details.");
4094 /* Parse client-side authorization for hidden services. */
4095 if (hs_config_client_auth_all(options, 1) < 0)
4096 REJECT("Failed to configure client authorization for hidden services. "
4097 "See logs for details.");
4099 if (parse_virtual_addr_network(options->VirtualAddrNetworkIPv4,
4100 AF_INET, 1, msg)<0)
4101 return -1;
4102 if (parse_virtual_addr_network(options->VirtualAddrNetworkIPv6,
4103 AF_INET6, 1, msg)<0)
4104 return -1;
4106 if (options->TestingTorNetwork &&
4107 !(options->DirAuthorities ||
4108 (options->AlternateDirAuthority &&
4109 options->AlternateBridgeAuthority))) {
4110 REJECT("TestingTorNetwork may only be configured in combination with "
4111 "a non-default set of DirAuthority or both of "
4112 "AlternateDirAuthority and AlternateBridgeAuthority configured.");
4115 #define CHECK_DEFAULT(arg) \
4116 STMT_BEGIN \
4117 if (!config_is_same(get_options_mgr(),options, \
4118 dflt_options,#arg)) { \
4119 or_options_free(dflt_options); \
4120 REJECT(#arg " may only be changed in testing Tor " \
4121 "networks!"); \
4123 STMT_END
4125 /* Check for options that can only be changed from the defaults in testing
4126 networks. */
4127 if (! options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
4128 or_options_t *dflt_options = options_new();
4129 options_init(dflt_options);
4130 /* 31851: some of these options are dirauth or relay only */
4131 CHECK_DEFAULT(TestingV3AuthInitialVotingInterval);
4132 CHECK_DEFAULT(TestingV3AuthInitialVoteDelay);
4133 CHECK_DEFAULT(TestingV3AuthInitialDistDelay);
4134 CHECK_DEFAULT(TestingV3AuthVotingStartOffset);
4135 CHECK_DEFAULT(TestingAuthDirTimeToLearnReachability);
4136 CHECK_DEFAULT(TestingServerDownloadInitialDelay);
4137 CHECK_DEFAULT(TestingClientDownloadInitialDelay);
4138 CHECK_DEFAULT(TestingServerConsensusDownloadInitialDelay);
4139 CHECK_DEFAULT(TestingClientConsensusDownloadInitialDelay);
4140 CHECK_DEFAULT(TestingBridgeDownloadInitialDelay);
4141 CHECK_DEFAULT(TestingBridgeBootstrapDownloadInitialDelay);
4142 CHECK_DEFAULT(TestingClientMaxIntervalWithoutRequest);
4143 CHECK_DEFAULT(TestingDirConnectionMaxStall);
4144 CHECK_DEFAULT(TestingAuthKeyLifetime);
4145 CHECK_DEFAULT(TestingLinkCertLifetime);
4146 CHECK_DEFAULT(TestingSigningKeySlop);
4147 CHECK_DEFAULT(TestingAuthKeySlop);
4148 CHECK_DEFAULT(TestingLinkKeySlop);
4149 or_options_free(dflt_options);
4151 #undef CHECK_DEFAULT
4153 if (!options->ClientDNSRejectInternalAddresses &&
4154 !(options->DirAuthorities ||
4155 (options->AlternateDirAuthority && options->AlternateBridgeAuthority)))
4156 REJECT("ClientDNSRejectInternalAddresses used for default network.");
4158 if (options_validate_relay_testing(old_options, options, msg) < 0)
4159 return -1;
4160 if (options_validate_dirauth_testing(old_options, options, msg) < 0)
4161 return -1;
4163 if (options->TestingClientMaxIntervalWithoutRequest < 1) {
4164 REJECT("TestingClientMaxIntervalWithoutRequest is way too low.");
4165 } else if (options->TestingClientMaxIntervalWithoutRequest > 3600) {
4166 COMPLAIN("TestingClientMaxIntervalWithoutRequest is insanely high.");
4169 if (options->TestingDirConnectionMaxStall < 5) {
4170 REJECT("TestingDirConnectionMaxStall is way too low.");
4171 } else if (options->TestingDirConnectionMaxStall > 3600) {
4172 COMPLAIN("TestingDirConnectionMaxStall is insanely high.");
4175 if (options->ClientBootstrapConsensusMaxInProgressTries < 1) {
4176 REJECT("ClientBootstrapConsensusMaxInProgressTries must be greater "
4177 "than 0.");
4178 } else if (options->ClientBootstrapConsensusMaxInProgressTries
4179 > 100) {
4180 COMPLAIN("ClientBootstrapConsensusMaxInProgressTries is insanely "
4181 "high.");
4184 if (options->TestingEnableConnBwEvent &&
4185 !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
4186 REJECT("TestingEnableConnBwEvent may only be changed in testing "
4187 "Tor networks!");
4190 if (options->TestingEnableCellStatsEvent &&
4191 !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
4192 REJECT("TestingEnableCellStatsEvent may only be changed in testing "
4193 "Tor networks!");
4196 if (options->TestingTorNetwork) {
4197 log_warn(LD_CONFIG, "TestingTorNetwork is set. This will make your node "
4198 "almost unusable in the public Tor network, and is "
4199 "therefore only advised if you are building a "
4200 "testing Tor network!");
4203 if (options_validate_scheduler(options, msg) < 0) {
4204 return -1;
4207 return 0;
4210 #undef REJECT
4211 #undef COMPLAIN
4213 /* Given the value that the user has set for MaxMemInQueues, compute the
4214 * actual maximum value. We clip this value if it's too low, and autodetect
4215 * it if it's set to 0. */
4216 STATIC uint64_t
4217 compute_real_max_mem_in_queues(const uint64_t val, int log_guess)
4219 uint64_t result;
4221 if (val == 0) {
4222 #define ONE_GIGABYTE (UINT64_C(1) << 30)
4223 #define ONE_MEGABYTE (UINT64_C(1) << 20)
4224 /* The user didn't pick a memory limit. Choose a very large one
4225 * that is still smaller than the system memory */
4226 static int notice_sent = 0;
4227 size_t ram = 0;
4228 if (get_total_system_memory(&ram) < 0) {
4229 /* We couldn't determine our total system memory! */
4230 #if SIZEOF_VOID_P >= 8
4231 /* 64-bit system. Let's hope for 8 GB. */
4232 result = 8 * ONE_GIGABYTE;
4233 #else
4234 /* (presumably) 32-bit system. Let's hope for 1 GB. */
4235 result = ONE_GIGABYTE;
4236 #endif /* SIZEOF_VOID_P >= 8 */
4237 } else {
4238 /* We detected the amount of memory available. */
4239 uint64_t avail = 0;
4241 #if SIZEOF_SIZE_T > 4
4242 /* On a 64-bit platform, we consider 8GB "very large". */
4243 #define RAM_IS_VERY_LARGE(x) ((x) >= (8 * ONE_GIGABYTE))
4244 #else
4245 /* On a 32-bit platform, we can't have 8GB of ram. */
4246 #define RAM_IS_VERY_LARGE(x) (0)
4247 #endif /* SIZEOF_SIZE_T > 4 */
4249 if (RAM_IS_VERY_LARGE(ram)) {
4250 /* If we have 8 GB, or more, RAM available, we set the MaxMemInQueues
4251 * to 0.4 * RAM. The idea behind this value is that the amount of RAM
4252 * is more than enough for a single relay and should allow the relay
4253 * operator to run two relays if they have additional bandwidth
4254 * available.
4256 avail = (ram / 5) * 2;
4257 } else {
4258 /* If we have less than 8 GB of RAM available, we use the "old" default
4259 * for MaxMemInQueues of 0.75 * RAM.
4261 avail = (ram / 4) * 3;
4264 /* Make sure it's in range from 0.25 GB to 8 GB for 64-bit and 0.25 to 2
4265 * GB for 32-bit. */
4266 if (avail > MAX_DEFAULT_MEMORY_QUEUE_SIZE) {
4267 /* If you want to use more than this much RAM, you need to configure
4268 it yourself */
4269 result = MAX_DEFAULT_MEMORY_QUEUE_SIZE;
4270 } else if (avail < ONE_GIGABYTE / 4) {
4271 result = ONE_GIGABYTE / 4;
4272 } else {
4273 result = avail;
4276 if (log_guess && ! notice_sent) {
4277 log_notice(LD_CONFIG, "%sMaxMemInQueues is set to %"PRIu64" MB. "
4278 "You can override this by setting MaxMemInQueues by hand.",
4279 ram ? "Based on detected system memory, " : "",
4280 (result / ONE_MEGABYTE));
4281 notice_sent = 1;
4283 return result;
4284 } else if (val < ONE_GIGABYTE / 4) {
4285 log_warn(LD_CONFIG, "MaxMemInQueues must be at least 256 MB for now. "
4286 "Ideally, have it as large as you can afford.");
4287 return ONE_GIGABYTE / 4;
4288 } else {
4289 /* The value was fine all along */
4290 return val;
4294 /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
4295 * equal strings. */
4296 static int
4297 opt_streq(const char *s1, const char *s2)
4299 return 0 == strcmp_opt(s1, s2);
4302 /** Check if any config options have changed but aren't allowed to. */
4303 static int
4304 options_check_transition_cb(const void *old_,
4305 const void *new_val_,
4306 char **msg)
4308 CHECK_OPTIONS_MAGIC(old_);
4309 CHECK_OPTIONS_MAGIC(new_val_);
4311 const or_options_t *old = old_;
4312 const or_options_t *new_val = new_val_;
4314 if (BUG(!old))
4315 return 0;
4317 #define BAD_CHANGE_TO(opt, how) do { \
4318 *msg = tor_strdup("While Tor is running"how", changing " #opt \
4319 " is not allowed"); \
4320 return -1; \
4321 } while (0)
4323 if (sandbox_is_active()) {
4324 #define SB_NOCHANGE_STR(opt) \
4325 if (! CFG_EQ_STRING(old, new_val, opt)) \
4326 BAD_CHANGE_TO(opt," with Sandbox active")
4327 #define SB_NOCHANGE_LINELIST(opt) \
4328 if (! CFG_EQ_LINELIST(old, new_val, opt)) \
4329 BAD_CHANGE_TO(opt," with Sandbox active")
4330 #define SB_NOCHANGE_INT(opt) \
4331 if (! CFG_EQ_INT(old, new_val, opt)) \
4332 BAD_CHANGE_TO(opt," with Sandbox active")
4334 SB_NOCHANGE_STR(Address);
4335 SB_NOCHANGE_STR(ServerDNSResolvConfFile);
4336 SB_NOCHANGE_STR(DirPortFrontPage);
4337 SB_NOCHANGE_STR(CookieAuthFile);
4338 SB_NOCHANGE_STR(ExtORPortCookieAuthFile);
4339 SB_NOCHANGE_LINELIST(Logs);
4340 SB_NOCHANGE_INT(ConnLimit);
4342 if (server_mode(old) != server_mode(new_val)) {
4343 *msg = tor_strdup("Can't start/stop being a server while "
4344 "Sandbox is active");
4345 return -1;
4349 #undef SB_NOCHANGE_LINELIST
4350 #undef SB_NOCHANGE_STR
4351 #undef SB_NOCHANGE_INT
4352 #undef BAD_CHANGE_TO
4353 #undef NO_CHANGE_BOOL
4354 #undef NO_CHANGE_INT
4355 #undef NO_CHANGE_STRING
4356 return 0;
4359 #ifdef _WIN32
4360 /** Return the directory on windows where we expect to find our application
4361 * data. */
4362 static char *
4363 get_windows_conf_root(void)
4365 static int is_set = 0;
4366 static char path[MAX_PATH*2+1];
4367 TCHAR tpath[MAX_PATH] = {0};
4369 LPITEMIDLIST idl;
4370 IMalloc *m;
4371 HRESULT result;
4373 if (is_set)
4374 return path;
4376 /* Find X:\documents and settings\username\application data\ .
4377 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
4379 #ifdef ENABLE_LOCAL_APPDATA
4380 #define APPDATA_PATH CSIDL_LOCAL_APPDATA
4381 #else
4382 #define APPDATA_PATH CSIDL_APPDATA
4383 #endif
4384 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, APPDATA_PATH, &idl))) {
4385 getcwd(path,MAX_PATH);
4386 is_set = 1;
4387 log_warn(LD_CONFIG,
4388 "I couldn't find your application data folder: are you "
4389 "running an ancient version of Windows 95? Defaulting to \"%s\"",
4390 path);
4391 return path;
4393 /* Convert the path from an "ID List" (whatever that is!) to a path. */
4394 result = SHGetPathFromIDList(idl, tpath);
4395 #ifdef UNICODE
4396 wcstombs(path,tpath,sizeof(path));
4397 path[sizeof(path)-1] = '\0';
4398 #else
4399 strlcpy(path,tpath,sizeof(path));
4400 #endif /* defined(UNICODE) */
4402 /* Now we need to free the memory that the path-idl was stored in. In
4403 * typical Windows fashion, we can't just call 'free()' on it. */
4404 SHGetMalloc(&m);
4405 if (m) {
4406 m->lpVtbl->Free(m, idl);
4407 m->lpVtbl->Release(m);
4409 if (!SUCCEEDED(result)) {
4410 return NULL;
4412 strlcat(path,"\\tor",MAX_PATH);
4413 is_set = 1;
4414 return path;
4416 #endif /* defined(_WIN32) */
4418 /** Return the default location for our torrc file (if <b>defaults_file</b> is
4419 * false), or for the torrc-defaults file (if <b>defaults_file</b> is true). */
4420 static const char *
4421 get_default_conf_file(int defaults_file)
4423 #ifdef DISABLE_SYSTEM_TORRC
4424 (void) defaults_file;
4425 return NULL;
4426 #elif defined(_WIN32)
4427 if (defaults_file) {
4428 static char defaults_path[MAX_PATH+1];
4429 tor_snprintf(defaults_path, MAX_PATH, "%s\\torrc-defaults",
4430 get_windows_conf_root());
4431 return defaults_path;
4432 } else {
4433 static char path[MAX_PATH+1];
4434 tor_snprintf(path, MAX_PATH, "%s\\torrc",
4435 get_windows_conf_root());
4436 return path;
4438 #else
4439 return defaults_file ? CONFDIR "/torrc-defaults" : CONFDIR "/torrc";
4440 #endif /* defined(DISABLE_SYSTEM_TORRC) || ... */
4443 /** Learn config file name from command line arguments, or use the default.
4445 * If <b>defaults_file</b> is true, we're looking for torrc-defaults;
4446 * otherwise, we're looking for the regular torrc_file.
4448 * Set *<b>using_default_fname</b> to true if we're using the default
4449 * configuration file name; or false if we've set it from the command line.
4451 * Set *<b>ignore_missing_torrc</b> to true if we should ignore the resulting
4452 * filename if it doesn't exist.
4454 static char *
4455 find_torrc_filename(const config_line_t *cmd_arg,
4456 int defaults_file,
4457 int *using_default_fname, int *ignore_missing_torrc)
4459 char *fname=NULL;
4460 const config_line_t *p_index;
4461 const char *fname_opt = defaults_file ? "--defaults-torrc" : "-f";
4462 const char *ignore_opt = defaults_file ? NULL : "--ignore-missing-torrc";
4464 if (defaults_file)
4465 *ignore_missing_torrc = 1;
4467 for (p_index = cmd_arg; p_index; p_index = p_index->next) {
4468 if (!strcmp(p_index->key, fname_opt)) {
4469 if (fname) {
4470 log_warn(LD_CONFIG, "Duplicate %s options on command line.",
4471 fname_opt);
4472 tor_free(fname);
4474 fname = expand_filename(p_index->value);
4477 char *absfname;
4478 absfname = make_path_absolute(fname);
4479 tor_free(fname);
4480 fname = absfname;
4483 *using_default_fname = 0;
4484 } else if (ignore_opt && !strcmp(p_index->key,ignore_opt)) {
4485 *ignore_missing_torrc = 1;
4489 if (*using_default_fname) {
4490 /* didn't find one, try CONFDIR */
4491 const char *dflt = get_default_conf_file(defaults_file);
4492 file_status_t st = file_status(dflt);
4493 if (dflt && (st == FN_FILE || st == FN_EMPTY)) {
4494 fname = tor_strdup(dflt);
4495 } else {
4496 #ifndef _WIN32
4497 char *fn = NULL;
4498 if (!defaults_file) {
4499 fn = expand_filename("~/.torrc");
4501 if (fn) {
4502 file_status_t hmst = file_status(fn);
4503 if (hmst == FN_FILE || hmst == FN_EMPTY || dflt == NULL) {
4504 fname = fn;
4505 } else {
4506 tor_free(fn);
4507 fname = tor_strdup(dflt);
4509 } else {
4510 fname = dflt ? tor_strdup(dflt) : NULL;
4512 #else /* defined(_WIN32) */
4513 fname = dflt ? tor_strdup(dflt) : NULL;
4514 #endif /* !defined(_WIN32) */
4517 return fname;
4520 /** Read the torrc from standard input and return it as a string.
4521 * Upon failure, return NULL.
4523 static char *
4524 load_torrc_from_stdin(void)
4526 size_t sz_out;
4528 return read_file_to_str_until_eof(STDIN_FILENO,SIZE_MAX,&sz_out);
4531 /** Load a configuration file from disk, setting torrc_fname or
4532 * torrc_defaults_fname if successful.
4534 * If <b>defaults_file</b> is true, load torrc-defaults; otherwise load torrc.
4536 * Return the contents of the file on success, and NULL on failure.
4538 static char *
4539 load_torrc_from_disk(const config_line_t *cmd_arg, int defaults_file)
4541 char *fname=NULL;
4542 char *cf = NULL;
4543 int using_default_torrc = 1;
4544 int ignore_missing_torrc = 0;
4545 char **fname_var = defaults_file ? &torrc_defaults_fname : &torrc_fname;
4547 if (*fname_var == NULL) {
4548 fname = find_torrc_filename(cmd_arg, defaults_file,
4549 &using_default_torrc, &ignore_missing_torrc);
4550 tor_free(*fname_var);
4551 *fname_var = fname;
4552 } else {
4553 fname = *fname_var;
4555 log_debug(LD_CONFIG, "Opening config file \"%s\"", fname?fname:"<NULL>");
4557 /* Open config file */
4558 file_status_t st = fname ? file_status(fname) : FN_EMPTY;
4559 if (fname == NULL ||
4560 !(st == FN_FILE || st == FN_EMPTY) ||
4561 !(cf = read_file_to_str(fname,0,NULL))) {
4562 if (using_default_torrc == 1 || ignore_missing_torrc) {
4563 if (!defaults_file)
4564 log_notice(LD_CONFIG, "Configuration file \"%s\" not present, "
4565 "using reasonable defaults.", fname);
4566 tor_free(fname); /* sets fname to NULL */
4567 *fname_var = NULL;
4568 cf = tor_strdup("");
4569 } else {
4570 log_warn(LD_CONFIG,
4571 "Unable to open configuration file \"%s\".", fname);
4572 goto err;
4574 } else {
4575 log_notice(LD_CONFIG, "Read configuration file \"%s\".", fname);
4578 return cf;
4579 err:
4580 tor_free(fname);
4581 *fname_var = NULL;
4582 return NULL;
4585 /** Read a configuration file into <b>options</b>, finding the configuration
4586 * file location based on the command line. After loading the file
4587 * call options_init_from_string() to load the config.
4588 * Return 0 if success, -1 if failure, and 1 if we succeeded but should exit
4589 * anyway. */
4591 options_init_from_torrc(int argc, char **argv)
4593 char *cf=NULL, *cf_defaults=NULL;
4594 int retval = -1;
4595 char *errmsg=NULL;
4596 const config_line_t *cmdline_only_options;
4598 /* Go through command-line variables */
4599 if (global_cmdline == NULL) {
4600 /* Or we could redo the list every time we pass this place.
4601 * It does not really matter */
4602 global_cmdline = config_parse_commandline(argc, argv, 0);
4603 if (global_cmdline == NULL) {
4604 goto err;
4607 cmdline_only_options = global_cmdline->cmdline_opts;
4609 if (config_line_find(cmdline_only_options, "-h") ||
4610 config_line_find(cmdline_only_options, "--help")) {
4611 print_usage();
4612 return 1;
4614 if (config_line_find(cmdline_only_options, "--list-torrc-options")) {
4615 /* For validating whether we've documented everything. */
4616 list_torrc_options();
4617 return 1;
4619 if (config_line_find(cmdline_only_options, "--list-deprecated-options")) {
4620 /* For validating whether what we have deprecated really exists. */
4621 list_deprecated_options();
4622 return 1;
4625 if (config_line_find(cmdline_only_options, "--version")) {
4626 printf("Tor version %s.\n",get_version());
4627 return 1;
4630 if (config_line_find(cmdline_only_options, "--list-modules")) {
4631 list_enabled_modules();
4632 return 1;
4635 if (config_line_find(cmdline_only_options, "--library-versions")) {
4636 printf("Tor version %s. \n", get_version());
4637 printf("Library versions\tCompiled\t\tRuntime\n");
4638 printf("Libevent\t\t%-15s\t\t%s\n",
4639 tor_libevent_get_header_version_str(),
4640 tor_libevent_get_version_str());
4641 #ifdef ENABLE_OPENSSL
4642 printf("OpenSSL \t\t%-15s\t\t%s\n",
4643 crypto_openssl_get_header_version_str(),
4644 crypto_openssl_get_version_str());
4645 #endif
4646 #ifdef ENABLE_NSS
4647 printf("NSS \t\t%-15s\t\t%s\n",
4648 crypto_nss_get_header_version_str(),
4649 crypto_nss_get_version_str());
4650 #endif
4651 if (tor_compress_supports_method(ZLIB_METHOD)) {
4652 printf("Zlib \t\t%-15s\t\t%s\n",
4653 tor_compress_version_str(ZLIB_METHOD),
4654 tor_compress_header_version_str(ZLIB_METHOD));
4656 if (tor_compress_supports_method(LZMA_METHOD)) {
4657 printf("Liblzma \t\t%-15s\t\t%s\n",
4658 tor_compress_version_str(LZMA_METHOD),
4659 tor_compress_header_version_str(LZMA_METHOD));
4661 if (tor_compress_supports_method(ZSTD_METHOD)) {
4662 printf("Libzstd \t\t%-15s\t\t%s\n",
4663 tor_compress_version_str(ZSTD_METHOD),
4664 tor_compress_header_version_str(ZSTD_METHOD));
4666 //TODO: Hex versions?
4667 return 1;
4670 int command = global_cmdline->command;
4671 const char *command_arg = global_cmdline->command_arg;
4672 /* "immediate" has already been handled by this point. */
4673 tor_assert(command != CMD_IMMEDIATE);
4675 if (command == CMD_HASH_PASSWORD) {
4676 cf_defaults = tor_strdup("");
4677 cf = tor_strdup("");
4678 } else {
4679 cf_defaults = load_torrc_from_disk(cmdline_only_options, 1);
4681 const config_line_t *f_line = config_line_find(cmdline_only_options,
4682 "-f");
4684 const int read_torrc_from_stdin =
4685 (f_line != NULL && strcmp(f_line->value, "-") == 0);
4687 if (read_torrc_from_stdin) {
4688 cf = load_torrc_from_stdin();
4689 } else {
4690 cf = load_torrc_from_disk(cmdline_only_options, 0);
4693 if (!cf) {
4694 if (config_line_find(cmdline_only_options, "--allow-missing-torrc")) {
4695 cf = tor_strdup("");
4696 } else {
4697 goto err;
4702 retval = options_init_from_string(cf_defaults, cf, command, command_arg,
4703 &errmsg);
4705 if (retval < 0)
4706 goto err;
4708 if (config_line_find(cmdline_only_options, "--no-passphrase")) {
4709 if (command == CMD_KEYGEN) {
4710 get_options_mutable()->keygen_force_passphrase = FORCE_PASSPHRASE_OFF;
4711 } else {
4712 log_err(LD_CONFIG, "--no-passphrase specified without --keygen!");
4713 retval = -1;
4714 goto err;
4718 if (config_line_find(cmdline_only_options, "--newpass")) {
4719 if (command == CMD_KEYGEN) {
4720 get_options_mutable()->change_key_passphrase = 1;
4721 } else {
4722 log_err(LD_CONFIG, "--newpass specified without --keygen!");
4723 retval = -1;
4724 goto err;
4729 const config_line_t *fd_line = config_line_find(cmdline_only_options,
4730 "--passphrase-fd");
4731 if (fd_line) {
4732 if (get_options()->keygen_force_passphrase == FORCE_PASSPHRASE_OFF) {
4733 log_err(LD_CONFIG, "--no-passphrase specified with --passphrase-fd!");
4734 retval = -1;
4735 goto err;
4736 } else if (command != CMD_KEYGEN) {
4737 log_err(LD_CONFIG, "--passphrase-fd specified without --keygen!");
4738 retval = -1;
4739 goto err;
4740 } else {
4741 const char *v = fd_line->value;
4742 int ok = 1;
4743 long fd = tor_parse_long(v, 10, 0, INT_MAX, &ok, NULL);
4744 if (fd < 0 || ok == 0) {
4745 log_err(LD_CONFIG, "Invalid --passphrase-fd value %s", escaped(v));
4746 retval = -1;
4747 goto err;
4749 get_options_mutable()->keygen_passphrase_fd = (int)fd;
4750 get_options_mutable()->use_keygen_passphrase_fd = 1;
4751 get_options_mutable()->keygen_force_passphrase = FORCE_PASSPHRASE_ON;
4757 const config_line_t *key_line = config_line_find(cmdline_only_options,
4758 "--master-key");
4759 if (key_line) {
4760 if (command != CMD_KEYGEN) {
4761 log_err(LD_CONFIG, "--master-key without --keygen!");
4762 retval = -1;
4763 goto err;
4764 } else {
4765 get_options_mutable()->master_key_fname = tor_strdup(key_line->value);
4770 err:
4772 tor_free(cf);
4773 tor_free(cf_defaults);
4774 if (errmsg) {
4775 log_warn(LD_CONFIG,"%s", errmsg);
4776 tor_free(errmsg);
4778 return retval < 0 ? -1 : 0;
4781 /** Load the options from the configuration in <b>cf</b>, validate
4782 * them for consistency and take actions based on them.
4784 * Return 0 if success, negative on error:
4785 * * -1 for general errors.
4786 * * -2 for failure to parse/validate,
4787 * * -3 for transition not allowed
4788 * * -4 for error while setting the new options
4790 setopt_err_t
4791 options_init_from_string(const char *cf_defaults, const char *cf,
4792 int command, const char *command_arg,
4793 char **msg)
4795 bool retry = false;
4796 or_options_t *oldoptions, *newoptions, *newdefaultoptions=NULL;
4797 config_line_t *cl;
4798 int retval;
4799 setopt_err_t err = SETOPT_ERR_MISC;
4800 int cf_has_include = 0;
4801 tor_assert(msg);
4803 oldoptions = global_options; /* get_options unfortunately asserts if
4804 this is the first time we run*/
4806 newoptions = options_new();
4807 options_init(newoptions);
4808 newoptions->command = command;
4809 newoptions->command_arg = command_arg ? tor_strdup(command_arg) : NULL;
4811 smartlist_t *opened_files = smartlist_new();
4812 for (int i = 0; i < 2; ++i) {
4813 const char *body = i==0 ? cf_defaults : cf;
4814 if (!body)
4815 continue;
4817 /* get config lines, assign them */
4818 retval = config_get_lines_include(body, &cl, 1,
4819 body == cf ? &cf_has_include : NULL,
4820 opened_files);
4821 if (retval < 0) {
4822 err = SETOPT_ERR_PARSE;
4823 goto err;
4825 retval = config_assign(get_options_mgr(), newoptions, cl,
4826 CAL_WARN_DEPRECATIONS, msg);
4827 config_free_lines(cl);
4828 if (retval < 0) {
4829 err = SETOPT_ERR_PARSE;
4830 goto err;
4832 if (i==0)
4833 newdefaultoptions = config_dup(get_options_mgr(), newoptions);
4836 if (newdefaultoptions == NULL) {
4837 newdefaultoptions = config_dup(get_options_mgr(), global_default_options);
4840 /* Go through command-line variables too */
4842 config_line_t *other_opts = NULL;
4843 if (global_cmdline) {
4844 other_opts = global_cmdline->other_opts;
4846 retval = config_assign(get_options_mgr(), newoptions,
4847 other_opts,
4848 CAL_WARN_DEPRECATIONS, msg);
4850 if (retval < 0) {
4851 err = SETOPT_ERR_PARSE;
4852 goto err;
4855 newoptions->IncludeUsed = cf_has_include;
4856 newoptions->FilesOpenedByIncludes = opened_files;
4857 opened_files = NULL; // prevent double-free.
4859 /* If this is a testing network configuration, change defaults
4860 * for a list of dependent config options, and try this function again. */
4861 if (newoptions->TestingTorNetwork && ! testing_network_configured) {
4862 // retry with the testing defaults.
4863 testing_network_configured = true;
4864 retry = true;
4865 goto err;
4868 err = options_validate_and_set(oldoptions, newoptions, msg);
4869 if (err < 0) {
4870 newoptions = NULL; // This was already freed in options_validate_and_set.
4871 goto err;
4874 or_options_free(global_default_options);
4875 global_default_options = newdefaultoptions;
4877 return SETOPT_OK;
4879 err:
4880 in_option_validation = 0;
4881 if (opened_files) {
4882 SMARTLIST_FOREACH(opened_files, char *, f, tor_free(f));
4883 smartlist_free(opened_files);
4885 or_options_free(newdefaultoptions);
4886 or_options_free(newoptions);
4887 if (*msg) {
4888 char *old_msg = *msg;
4889 tor_asprintf(msg, "Failed to parse/validate config: %s", old_msg);
4890 tor_free(old_msg);
4892 if (retry)
4893 return options_init_from_string(cf_defaults, cf, command, command_arg,
4894 msg);
4895 return err;
4898 /** Return the location for our configuration file. May return NULL.
4900 const char *
4901 get_torrc_fname(int defaults_fname)
4903 const char *fname = defaults_fname ? torrc_defaults_fname : torrc_fname;
4905 if (fname)
4906 return fname;
4907 else
4908 return get_default_conf_file(defaults_fname);
4911 /** Adjust the address map based on the MapAddress elements in the
4912 * configuration <b>options</b>
4914 void
4915 config_register_addressmaps(const or_options_t *options)
4917 smartlist_t *elts;
4918 config_line_t *opt;
4919 const char *from, *to, *msg;
4921 addressmap_clear_configured();
4922 elts = smartlist_new();
4923 for (opt = options->AddressMap; opt; opt = opt->next) {
4924 smartlist_split_string(elts, opt->value, NULL,
4925 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
4926 if (smartlist_len(elts) < 2) {
4927 log_warn(LD_CONFIG,"MapAddress '%s' has too few arguments. Ignoring.",
4928 opt->value);
4929 goto cleanup;
4932 from = smartlist_get(elts,0);
4933 to = smartlist_get(elts,1);
4935 if (to[0] == '.' || from[0] == '.') {
4936 log_warn(LD_CONFIG,"MapAddress '%s' is ambiguous - address starts with a"
4937 "'.'. Ignoring.",opt->value);
4938 goto cleanup;
4941 if (addressmap_register_auto(from, to, 0, ADDRMAPSRC_TORRC, &msg) < 0) {
4942 log_warn(LD_CONFIG,"MapAddress '%s' failed: %s. Ignoring.", opt->value,
4943 msg);
4944 goto cleanup;
4947 if (smartlist_len(elts) > 2)
4948 log_warn(LD_CONFIG,"Ignoring extra arguments to MapAddress.");
4950 cleanup:
4951 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
4952 smartlist_clear(elts);
4954 smartlist_free(elts);
4957 /** As addressmap_register(), but detect the wildcarded status of "from" and
4958 * "to", and do not steal a reference to <b>to</b>. */
4959 /* XXXX move to connection_edge.c */
4961 addressmap_register_auto(const char *from, const char *to,
4962 time_t expires,
4963 addressmap_entry_source_t addrmap_source,
4964 const char **msg)
4966 int from_wildcard = 0, to_wildcard = 0;
4968 *msg = "whoops, forgot the error message";
4970 if (!strcmp(to, "*") || !strcmp(from, "*")) {
4971 *msg = "can't remap from or to *";
4972 return -1;
4974 /* Detect asterisks in expressions of type: '*.example.com' */
4975 if (!strncmp(from,"*.",2)) {
4976 from += 2;
4977 from_wildcard = 1;
4979 if (!strncmp(to,"*.",2)) {
4980 to += 2;
4981 to_wildcard = 1;
4984 if (to_wildcard && !from_wildcard) {
4985 *msg = "can only use wildcard (i.e. '*.') if 'from' address "
4986 "uses wildcard also";
4987 return -1;
4990 if (address_is_invalid_destination(to, 1)) {
4991 *msg = "destination is invalid";
4992 return -1;
4995 addressmap_register(from, tor_strdup(to), expires, addrmap_source,
4996 from_wildcard, to_wildcard);
4998 return 0;
5002 * As add_file_log, but open the file as appropriate.
5004 STATIC int
5005 open_and_add_file_log(const log_severity_list_t *severity,
5006 const char *filename, int truncate_log)
5008 int open_flags = O_WRONLY|O_CREAT;
5009 open_flags |= truncate_log ? O_TRUNC : O_APPEND;
5011 int fd = tor_open_cloexec(filename, open_flags, 0640);
5012 if (fd < 0)
5013 return -1;
5015 return add_file_log(severity, filename, fd);
5019 * Try to set our global log granularity from `options->LogGranularity`,
5020 * adjusting it as needed so that we are an even divisor of a second, or an
5021 * even multiple of seconds. Return 0 on success, -1 on failure.
5023 static int
5024 options_init_log_granularity(const or_options_t *options,
5025 int validate_only)
5027 if (options->LogTimeGranularity <= 0) {
5028 log_warn(LD_CONFIG, "Log time granularity '%d' has to be positive.",
5029 options->LogTimeGranularity);
5030 return -1;
5031 } else if (1000 % options->LogTimeGranularity != 0 &&
5032 options->LogTimeGranularity % 1000 != 0) {
5033 int granularity = options->LogTimeGranularity;
5034 if (granularity < 40) {
5035 do granularity++;
5036 while (1000 % granularity != 0);
5037 } else if (granularity < 1000) {
5038 granularity = 1000 / granularity;
5039 while (1000 % granularity != 0)
5040 granularity--;
5041 granularity = 1000 / granularity;
5042 } else {
5043 granularity = 1000 * ((granularity / 1000) + 1);
5045 log_warn(LD_CONFIG, "Log time granularity '%d' has to be either a "
5046 "divisor or a multiple of 1 second. Changing to "
5047 "'%d'.",
5048 options->LogTimeGranularity, granularity);
5049 if (!validate_only)
5050 set_log_time_granularity(granularity);
5051 } else {
5052 if (!validate_only)
5053 set_log_time_granularity(options->LogTimeGranularity);
5056 return 0;
5060 * Initialize the logs based on the configuration file.
5062 STATIC int
5063 options_init_logs(const or_options_t *old_options, const or_options_t *options,
5064 int validate_only)
5066 config_line_t *opt;
5067 int ok;
5068 smartlist_t *elts;
5069 int run_as_daemon =
5070 #ifdef _WIN32
5072 #else
5073 options->RunAsDaemon;
5074 #endif
5076 if (options_init_log_granularity(options, validate_only) < 0)
5077 return -1;
5079 ok = 1;
5080 elts = smartlist_new();
5082 if (options->Logs == NULL && !run_as_daemon && !validate_only) {
5083 /* When no logs are given, the default behavior is to log nothing (if
5084 RunAsDaemon is set) or to log based on the quiet level otherwise. */
5085 add_default_log_for_quiet_level(quiet_level);
5088 for (opt = options->Logs; opt; opt = opt->next) {
5089 log_severity_list_t *severity;
5090 const char *cfg = opt->value;
5091 severity = tor_malloc_zero(sizeof(log_severity_list_t));
5092 if (parse_log_severity_config(&cfg, severity) < 0) {
5093 log_warn(LD_CONFIG, "Couldn't parse log levels in Log option 'Log %s'",
5094 opt->value);
5095 ok = 0; goto cleanup;
5098 smartlist_split_string(elts, cfg, NULL,
5099 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
5101 if (smartlist_len(elts) == 0)
5102 smartlist_add_strdup(elts, "stdout");
5104 if (smartlist_len(elts) == 1 &&
5105 (!strcasecmp(smartlist_get(elts,0), "stdout") ||
5106 !strcasecmp(smartlist_get(elts,0), "stderr"))) {
5107 int err = smartlist_len(elts) &&
5108 !strcasecmp(smartlist_get(elts,0), "stderr");
5109 if (!validate_only) {
5110 if (run_as_daemon) {
5111 log_warn(LD_CONFIG,
5112 "Can't log to %s with RunAsDaemon set; skipping stdout",
5113 err?"stderr":"stdout");
5114 } else {
5115 add_stream_log(severity, err?"<stderr>":"<stdout>",
5116 fileno(err?stderr:stdout));
5119 goto cleanup;
5121 if (smartlist_len(elts) == 1) {
5122 if (!strcasecmp(smartlist_get(elts,0), "syslog")) {
5123 #ifdef HAVE_SYSLOG_H
5124 if (!validate_only) {
5125 add_syslog_log(severity, options->SyslogIdentityTag);
5127 #else
5128 log_warn(LD_CONFIG, "Syslog is not supported on this system. Sorry.");
5129 #endif /* defined(HAVE_SYSLOG_H) */
5130 goto cleanup;
5133 if (!strcasecmp(smartlist_get(elts, 0), "android")) {
5134 #ifdef HAVE_ANDROID_LOG_H
5135 if (!validate_only) {
5136 add_android_log(severity, options->AndroidIdentityTag);
5138 #else
5139 log_warn(LD_CONFIG, "Android logging is not supported"
5140 " on this system. Sorry.");
5141 #endif /* defined(HAVE_ANDROID_LOG_H) */
5142 goto cleanup;
5146 if (smartlist_len(elts) == 2 &&
5147 !strcasecmp(smartlist_get(elts,0), "file")) {
5148 if (!validate_only) {
5149 char *fname = expand_filename(smartlist_get(elts, 1));
5150 /* Truncate if TruncateLogFile is set and we haven't seen this option
5151 line before. */
5152 int truncate_log = 0;
5153 if (options->TruncateLogFile) {
5154 truncate_log = 1;
5155 if (old_options) {
5156 config_line_t *opt2;
5157 for (opt2 = old_options->Logs; opt2; opt2 = opt2->next)
5158 if (!strcmp(opt->value, opt2->value)) {
5159 truncate_log = 0;
5160 break;
5164 if (open_and_add_file_log(severity, fname, truncate_log) < 0) {
5165 log_warn(LD_CONFIG, "Couldn't open file for 'Log %s': %s",
5166 opt->value, strerror(errno));
5167 ok = 0;
5169 tor_free(fname);
5171 goto cleanup;
5174 log_warn(LD_CONFIG, "Bad syntax on file Log option 'Log %s'",
5175 opt->value);
5176 ok = 0; goto cleanup;
5178 cleanup:
5179 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
5180 smartlist_clear(elts);
5181 tor_free(severity);
5183 smartlist_free(elts);
5185 if (ok && !validate_only)
5186 logs_set_domain_logging(options->LogMessageDomains);
5188 return ok?0:-1;
5191 /** Given a smartlist of SOCKS arguments to be passed to a transport
5192 * proxy in <b>args</b>, validate them and return -1 if they are
5193 * corrupted. Return 0 if they seem OK. */
5194 static int
5195 validate_transport_socks_arguments(const smartlist_t *args)
5197 char *socks_string = NULL;
5198 size_t socks_string_len;
5200 tor_assert(args);
5201 tor_assert(smartlist_len(args) > 0);
5203 SMARTLIST_FOREACH_BEGIN(args, const char *, s) {
5204 if (!string_is_key_value(LOG_WARN, s)) { /* items should be k=v items */
5205 log_warn(LD_CONFIG, "'%s' is not a k=v item.", s);
5206 return -1;
5208 } SMARTLIST_FOREACH_END(s);
5210 socks_string = pt_stringify_socks_args(args);
5211 if (!socks_string)
5212 return -1;
5214 socks_string_len = strlen(socks_string);
5215 tor_free(socks_string);
5217 if (socks_string_len > MAX_SOCKS5_AUTH_SIZE_TOTAL) {
5218 log_warn(LD_CONFIG, "SOCKS arguments can't be more than %u bytes (%lu).",
5219 MAX_SOCKS5_AUTH_SIZE_TOTAL,
5220 (unsigned long) socks_string_len);
5221 return -1;
5224 return 0;
5227 /** Deallocate a bridge_line_t structure. */
5228 /* private */ void
5229 bridge_line_free_(bridge_line_t *bridge_line)
5231 if (!bridge_line)
5232 return;
5234 if (bridge_line->socks_args) {
5235 SMARTLIST_FOREACH(bridge_line->socks_args, char*, s, tor_free(s));
5236 smartlist_free(bridge_line->socks_args);
5238 tor_free(bridge_line->transport_name);
5239 tor_free(bridge_line);
5242 /** Parse the contents of a string, <b>line</b>, containing a Bridge line,
5243 * into a bridge_line_t.
5245 * Validates that the IP:PORT, fingerprint, and SOCKS arguments (given to the
5246 * Pluggable Transport, if a one was specified) are well-formed.
5248 * Returns NULL If the Bridge line could not be validated, and returns a
5249 * bridge_line_t containing the parsed information otherwise.
5251 * Bridge line format:
5252 * Bridge [transport] IP:PORT [id-fingerprint] [k=v] [k=v] ...
5254 /* private */ bridge_line_t *
5255 parse_bridge_line(const char *line)
5257 smartlist_t *items = NULL;
5258 char *addrport=NULL, *fingerprint=NULL;
5259 char *field=NULL;
5260 bridge_line_t *bridge_line = tor_malloc_zero(sizeof(bridge_line_t));
5262 items = smartlist_new();
5263 smartlist_split_string(items, line, NULL,
5264 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5265 if (smartlist_len(items) < 1) {
5266 log_warn(LD_CONFIG, "Too few arguments to Bridge line.");
5267 goto err;
5270 /* first field is either a transport name or addrport */
5271 field = smartlist_get(items, 0);
5272 smartlist_del_keeporder(items, 0);
5274 if (string_is_C_identifier(field)) {
5275 /* It's a transport name. */
5276 bridge_line->transport_name = field;
5277 if (smartlist_len(items) < 1) {
5278 log_warn(LD_CONFIG, "Too few items to Bridge line.");
5279 goto err;
5281 addrport = smartlist_get(items, 0); /* Next field is addrport then. */
5282 smartlist_del_keeporder(items, 0);
5283 } else {
5284 addrport = field;
5287 if (tor_addr_port_parse(LOG_INFO, addrport,
5288 &bridge_line->addr, &bridge_line->port, 443)<0) {
5289 log_warn(LD_CONFIG, "Error parsing Bridge address '%s'", addrport);
5290 goto err;
5293 /* If transports are enabled, next field could be a fingerprint or a
5294 socks argument. If transports are disabled, next field must be
5295 a fingerprint. */
5296 if (smartlist_len(items)) {
5297 if (bridge_line->transport_name) { /* transports enabled: */
5298 field = smartlist_get(items, 0);
5299 smartlist_del_keeporder(items, 0);
5301 /* If it's a key=value pair, then it's a SOCKS argument for the
5302 transport proxy... */
5303 if (string_is_key_value(LOG_DEBUG, field)) {
5304 bridge_line->socks_args = smartlist_new();
5305 smartlist_add(bridge_line->socks_args, field);
5306 } else { /* ...otherwise, it's the bridge fingerprint. */
5307 fingerprint = field;
5310 } else { /* transports disabled: */
5311 fingerprint = smartlist_join_strings(items, "", 0, NULL);
5315 /* Handle fingerprint, if it was provided. */
5316 if (fingerprint) {
5317 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
5318 log_warn(LD_CONFIG, "Key digest for Bridge is wrong length.");
5319 goto err;
5321 if (base16_decode(bridge_line->digest, DIGEST_LEN,
5322 fingerprint, HEX_DIGEST_LEN) != DIGEST_LEN) {
5323 log_warn(LD_CONFIG, "Unable to decode Bridge key digest.");
5324 goto err;
5328 /* If we are using transports, any remaining items in the smartlist
5329 should be k=v values. */
5330 if (bridge_line->transport_name && smartlist_len(items)) {
5331 if (!bridge_line->socks_args)
5332 bridge_line->socks_args = smartlist_new();
5334 /* append remaining items of 'items' to 'socks_args' */
5335 smartlist_add_all(bridge_line->socks_args, items);
5336 smartlist_clear(items);
5338 tor_assert(smartlist_len(bridge_line->socks_args) > 0);
5341 if (bridge_line->socks_args) {
5342 if (validate_transport_socks_arguments(bridge_line->socks_args) < 0)
5343 goto err;
5346 goto done;
5348 err:
5349 bridge_line_free(bridge_line);
5350 bridge_line = NULL;
5352 done:
5353 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5354 smartlist_free(items);
5355 tor_free(addrport);
5356 tor_free(fingerprint);
5358 return bridge_line;
5361 /** Parse the contents of a TCPProxy line from <b>line</b> and put it
5362 * in <b>options</b>. Return 0 if the line is well-formed, and -1 if it
5363 * isn't.
5365 * This will mutate only options->TCPProxyProtocol, options->TCPProxyAddr,
5366 * and options->TCPProxyPort.
5368 * On error, tor_strdup an error explanation into *<b>msg</b>.
5370 STATIC int
5371 parse_tcp_proxy_line(const char *line, or_options_t *options, char **msg)
5373 int ret = 0;
5374 tor_assert(line);
5375 tor_assert(options);
5376 tor_assert(msg);
5378 smartlist_t *sl = smartlist_new();
5379 /* Split between the protocol and the address/port. */
5380 smartlist_split_string(sl, line, " ",
5381 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
5383 /* The address/port is not specified. */
5384 if (smartlist_len(sl) < 2) {
5385 *msg = tor_strdup("TCPProxy has no address/port. Please fix.");
5386 goto err;
5389 char *protocol_string = smartlist_get(sl, 0);
5390 char *addrport_string = smartlist_get(sl, 1);
5392 /* The only currently supported protocol is 'haproxy'. */
5393 if (strcasecmp(protocol_string, "haproxy")) {
5394 *msg = tor_strdup("TCPProxy protocol is not supported. Currently "
5395 "the only supported protocol is 'haproxy'. "
5396 "Please fix.");
5397 goto err;
5398 } else {
5399 /* Otherwise, set the correct protocol. */
5400 options->TCPProxyProtocol = TCP_PROXY_PROTOCOL_HAPROXY;
5403 /* Parse the address/port. */
5404 if (tor_addr_port_lookup(addrport_string, &options->TCPProxyAddr,
5405 &options->TCPProxyPort) < 0) {
5406 *msg = tor_strdup("TCPProxy address/port failed to parse or resolve. "
5407 "Please fix.");
5408 goto err;
5411 /* Success. */
5412 ret = 0;
5413 goto end;
5415 err:
5416 ret = -1;
5417 end:
5418 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
5419 smartlist_free(sl);
5420 return ret;
5423 /** Read the contents of a ClientTransportPlugin or ServerTransportPlugin
5424 * line from <b>line</b>, depending on the value of <b>server</b>. Return 0
5425 * if the line is well-formed, and -1 if it isn't.
5427 * If <b>validate_only</b> is 0, the line is well-formed, and the transport is
5428 * needed by some bridge:
5429 * - If it's an external proxy line, add the transport described in the line to
5430 * our internal transport list.
5431 * - If it's a managed proxy line, launch the managed proxy.
5434 pt_parse_transport_line(const or_options_t *options,
5435 const char *line, int validate_only,
5436 int server)
5439 smartlist_t *items = NULL;
5440 int r;
5441 const char *transports = NULL;
5442 smartlist_t *transport_list = NULL;
5443 char *type = NULL;
5444 char *addrport = NULL;
5445 tor_addr_t addr;
5446 uint16_t port = 0;
5447 int socks_ver = PROXY_NONE;
5449 /* managed proxy options */
5450 int is_managed = 0;
5451 char **proxy_argv = NULL;
5452 char **tmp = NULL;
5453 int proxy_argc, i;
5454 int is_useless_proxy = 1;
5456 int line_length;
5458 /* Split the line into space-separated tokens */
5459 items = smartlist_new();
5460 smartlist_split_string(items, line, NULL,
5461 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5462 line_length = smartlist_len(items);
5464 if (line_length < 3) {
5465 log_warn(LD_CONFIG,
5466 "Too few arguments on %sTransportPlugin line.",
5467 server ? "Server" : "Client");
5468 goto err;
5471 /* Get the first line element, split it to commas into
5472 transport_list (in case it's multiple transports) and validate
5473 the transport names. */
5474 transports = smartlist_get(items, 0);
5475 transport_list = smartlist_new();
5476 smartlist_split_string(transport_list, transports, ",",
5477 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
5478 SMARTLIST_FOREACH_BEGIN(transport_list, const char *, transport_name) {
5479 /* validate transport names */
5480 if (!string_is_C_identifier(transport_name)) {
5481 log_warn(LD_CONFIG, "Transport name is not a C identifier (%s).",
5482 transport_name);
5483 goto err;
5486 /* see if we actually need the transports provided by this proxy */
5487 if (!validate_only && transport_is_needed(transport_name))
5488 is_useless_proxy = 0;
5489 } SMARTLIST_FOREACH_END(transport_name);
5491 type = smartlist_get(items, 1);
5492 if (!strcmp(type, "exec")) {
5493 is_managed = 1;
5494 } else if (server && !strcmp(type, "proxy")) {
5495 /* 'proxy' syntax only with ServerTransportPlugin */
5496 is_managed = 0;
5497 } else if (!server && !strcmp(type, "socks4")) {
5498 /* 'socks4' syntax only with ClientTransportPlugin */
5499 is_managed = 0;
5500 socks_ver = PROXY_SOCKS4;
5501 } else if (!server && !strcmp(type, "socks5")) {
5502 /* 'socks5' syntax only with ClientTransportPlugin */
5503 is_managed = 0;
5504 socks_ver = PROXY_SOCKS5;
5505 } else {
5506 log_warn(LD_CONFIG,
5507 "Strange %sTransportPlugin type '%s'",
5508 server ? "Server" : "Client", type);
5509 goto err;
5512 if (is_managed && options->Sandbox) {
5513 log_warn(LD_CONFIG,
5514 "Managed proxies are not compatible with Sandbox mode."
5515 "(%sTransportPlugin line was %s)",
5516 server ? "Server" : "Client", escaped(line));
5517 goto err;
5520 if (is_managed && options->NoExec) {
5521 log_warn(LD_CONFIG,
5522 "Managed proxies are not compatible with NoExec mode; ignoring."
5523 "(%sTransportPlugin line was %s)",
5524 server ? "Server" : "Client", escaped(line));
5525 r = 0;
5526 goto done;
5529 if (is_managed) {
5530 /* managed */
5532 if (!server && !validate_only && is_useless_proxy) {
5533 log_info(LD_GENERAL,
5534 "Pluggable transport proxy (%s) does not provide "
5535 "any needed transports and will not be launched.",
5536 line);
5540 * If we are not just validating, use the rest of the line as the
5541 * argv of the proxy to be launched. Also, make sure that we are
5542 * only launching proxies that contribute useful transports.
5545 if (!validate_only && (server || !is_useless_proxy)) {
5546 proxy_argc = line_length - 2;
5547 tor_assert(proxy_argc > 0);
5548 proxy_argv = tor_calloc((proxy_argc + 1), sizeof(char *));
5549 tmp = proxy_argv;
5551 for (i = 0; i < proxy_argc; i++) {
5552 /* store arguments */
5553 *tmp++ = smartlist_get(items, 2);
5554 smartlist_del_keeporder(items, 2);
5556 *tmp = NULL; /* terminated with NULL, just like execve() likes it */
5558 /* kickstart the thing */
5559 if (server) {
5560 pt_kickstart_server_proxy(transport_list, proxy_argv);
5561 } else {
5562 pt_kickstart_client_proxy(transport_list, proxy_argv);
5565 } else {
5566 /* external */
5568 /* ClientTransportPlugins connecting through a proxy is managed only. */
5569 if (!server && (options->Socks4Proxy || options->Socks5Proxy ||
5570 options->HTTPSProxy || options->TCPProxy)) {
5571 log_warn(LD_CONFIG, "You have configured an external proxy with another "
5572 "proxy type. (Socks4Proxy|Socks5Proxy|HTTPSProxy|"
5573 "TCPProxy)");
5574 goto err;
5577 if (smartlist_len(transport_list) != 1) {
5578 log_warn(LD_CONFIG,
5579 "You can't have an external proxy with more than "
5580 "one transport.");
5581 goto err;
5584 addrport = smartlist_get(items, 2);
5586 if (tor_addr_port_lookup(addrport, &addr, &port) < 0) {
5587 log_warn(LD_CONFIG,
5588 "Error parsing transport address '%s'", addrport);
5589 goto err;
5592 if (!port) {
5593 log_warn(LD_CONFIG,
5594 "Transport address '%s' has no port.", addrport);
5595 goto err;
5598 if (!validate_only) {
5599 log_info(LD_DIR, "%s '%s' at %s.",
5600 server ? "Server transport" : "Transport",
5601 transports, fmt_addrport(&addr, port));
5603 if (!server) {
5604 transport_add_from_config(&addr, port,
5605 smartlist_get(transport_list, 0),
5606 socks_ver);
5611 r = 0;
5612 goto done;
5614 err:
5615 r = -1;
5617 done:
5618 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5619 smartlist_free(items);
5620 if (transport_list) {
5621 SMARTLIST_FOREACH(transport_list, char*, s, tor_free(s));
5622 smartlist_free(transport_list);
5625 return r;
5628 /** Read the contents of a DirAuthority line from <b>line</b>. If
5629 * <b>validate_only</b> is 0, and the line is well-formed, and it
5630 * shares any bits with <b>required_type</b> or <b>required_type</b>
5631 * is NO_DIRINFO (zero), then add the dirserver described in the line
5632 * (minus whatever bits it's missing) as a valid authority.
5633 * Return 0 on success or filtering out by type,
5634 * or -1 if the line isn't well-formed or if we can't add it. */
5635 STATIC int
5636 parse_dir_authority_line(const char *line, dirinfo_type_t required_type,
5637 int validate_only)
5639 smartlist_t *items = NULL;
5640 int r;
5641 char *addrport=NULL, *address=NULL, *nickname=NULL, *fingerprint=NULL;
5642 tor_addr_port_t ipv6_addrport, *ipv6_addrport_ptr = NULL;
5643 uint16_t dir_port = 0, or_port = 0;
5644 char digest[DIGEST_LEN];
5645 char v3_digest[DIGEST_LEN];
5646 dirinfo_type_t type = 0;
5647 double weight = 1.0;
5649 memset(v3_digest, 0, sizeof(v3_digest));
5651 items = smartlist_new();
5652 smartlist_split_string(items, line, NULL,
5653 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5654 if (smartlist_len(items) < 1) {
5655 log_warn(LD_CONFIG, "No arguments on DirAuthority line.");
5656 goto err;
5659 if (is_legal_nickname(smartlist_get(items, 0))) {
5660 nickname = smartlist_get(items, 0);
5661 smartlist_del_keeporder(items, 0);
5664 while (smartlist_len(items)) {
5665 char *flag = smartlist_get(items, 0);
5666 if (TOR_ISDIGIT(flag[0]))
5667 break;
5668 if (!strcasecmp(flag, "hs") ||
5669 !strcasecmp(flag, "no-hs")) {
5670 log_warn(LD_CONFIG, "The DirAuthority options 'hs' and 'no-hs' are "
5671 "obsolete; you don't need them any more.");
5672 } else if (!strcasecmp(flag, "bridge")) {
5673 type |= BRIDGE_DIRINFO;
5674 } else if (!strcasecmp(flag, "no-v2")) {
5675 /* obsolete, but may still be contained in DirAuthority lines generated
5676 by various tools */;
5677 } else if (!strcasecmpstart(flag, "orport=")) {
5678 int ok;
5679 char *portstring = flag + strlen("orport=");
5680 or_port = (uint16_t) tor_parse_long(portstring, 10, 1, 65535, &ok, NULL);
5681 if (!ok)
5682 log_warn(LD_CONFIG, "Invalid orport '%s' on DirAuthority line.",
5683 portstring);
5684 } else if (!strcmpstart(flag, "weight=")) {
5685 int ok;
5686 const char *wstring = flag + strlen("weight=");
5687 weight = tor_parse_double(wstring, 0, (double)UINT64_MAX, &ok, NULL);
5688 if (!ok) {
5689 log_warn(LD_CONFIG, "Invalid weight '%s' on DirAuthority line.",flag);
5690 weight=1.0;
5692 } else if (!strcasecmpstart(flag, "v3ident=")) {
5693 char *idstr = flag + strlen("v3ident=");
5694 if (strlen(idstr) != HEX_DIGEST_LEN ||
5695 base16_decode(v3_digest, DIGEST_LEN,
5696 idstr, HEX_DIGEST_LEN) != DIGEST_LEN) {
5697 log_warn(LD_CONFIG, "Bad v3 identity digest '%s' on DirAuthority line",
5698 flag);
5699 } else {
5700 type |= V3_DIRINFO|EXTRAINFO_DIRINFO|MICRODESC_DIRINFO;
5702 } else if (!strcasecmpstart(flag, "ipv6=")) {
5703 if (ipv6_addrport_ptr) {
5704 log_warn(LD_CONFIG, "Redundant ipv6 addr/port on DirAuthority line");
5705 } else {
5706 if (tor_addr_port_parse(LOG_WARN, flag+strlen("ipv6="),
5707 &ipv6_addrport.addr, &ipv6_addrport.port,
5708 -1) < 0
5709 || tor_addr_family(&ipv6_addrport.addr) != AF_INET6) {
5710 log_warn(LD_CONFIG, "Bad ipv6 addr/port %s on DirAuthority line",
5711 escaped(flag));
5712 goto err;
5714 ipv6_addrport_ptr = &ipv6_addrport;
5716 } else {
5717 log_warn(LD_CONFIG, "Unrecognized flag '%s' on DirAuthority line",
5718 flag);
5720 tor_free(flag);
5721 smartlist_del_keeporder(items, 0);
5724 if (smartlist_len(items) < 2) {
5725 log_warn(LD_CONFIG, "Too few arguments to DirAuthority line.");
5726 goto err;
5728 addrport = smartlist_get(items, 0);
5729 smartlist_del_keeporder(items, 0);
5731 if (tor_addr_port_split(LOG_WARN, addrport, &address, &dir_port) < 0) {
5732 log_warn(LD_CONFIG, "Error parsing DirAuthority address '%s'.", addrport);
5733 goto err;
5736 if (!string_is_valid_ipv4_address(address)) {
5737 log_warn(LD_CONFIG, "Error parsing DirAuthority address '%s' "
5738 "(invalid IPv4 address)", address);
5739 goto err;
5742 if (!dir_port) {
5743 log_warn(LD_CONFIG, "Missing port in DirAuthority address '%s'",addrport);
5744 goto err;
5747 fingerprint = smartlist_join_strings(items, "", 0, NULL);
5748 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
5749 log_warn(LD_CONFIG, "Key digest '%s' for DirAuthority is wrong length %d.",
5750 fingerprint, (int)strlen(fingerprint));
5751 goto err;
5753 if (base16_decode(digest, DIGEST_LEN,
5754 fingerprint, HEX_DIGEST_LEN) != DIGEST_LEN) {
5755 log_warn(LD_CONFIG, "Unable to decode DirAuthority key digest.");
5756 goto err;
5759 if (!validate_only && (!required_type || required_type & type)) {
5760 dir_server_t *ds;
5761 if (required_type)
5762 type &= required_type; /* pare down what we think of them as an
5763 * authority for. */
5764 log_debug(LD_DIR, "Trusted %d dirserver at %s:%d (%s)", (int)type,
5765 address, (int)dir_port, (char*)smartlist_get(items,0));
5766 if (!(ds = trusted_dir_server_new(nickname, address, dir_port, or_port,
5767 ipv6_addrport_ptr,
5768 digest, v3_digest, type, weight)))
5769 goto err;
5770 dir_server_add(ds);
5773 r = 0;
5774 goto done;
5776 err:
5777 r = -1;
5779 done:
5780 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5781 smartlist_free(items);
5782 tor_free(addrport);
5783 tor_free(address);
5784 tor_free(nickname);
5785 tor_free(fingerprint);
5786 return r;
5789 /** Read the contents of a FallbackDir line from <b>line</b>. If
5790 * <b>validate_only</b> is 0, and the line is well-formed, then add the
5791 * dirserver described in the line as a fallback directory. Return 0 on
5792 * success, or -1 if the line isn't well-formed or if we can't add it. */
5794 parse_dir_fallback_line(const char *line,
5795 int validate_only)
5797 int r = -1;
5798 smartlist_t *items = smartlist_new(), *positional = smartlist_new();
5799 int orport = -1;
5800 uint16_t dirport;
5801 tor_addr_t addr;
5802 int ok;
5803 char id[DIGEST_LEN];
5804 char *address=NULL;
5805 tor_addr_port_t ipv6_addrport, *ipv6_addrport_ptr = NULL;
5806 double weight=1.0;
5808 memset(id, 0, sizeof(id));
5809 smartlist_split_string(items, line, NULL,
5810 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5811 SMARTLIST_FOREACH_BEGIN(items, const char *, cp) {
5812 const char *eq = strchr(cp, '=');
5813 ok = 1;
5814 if (! eq) {
5815 smartlist_add(positional, (char*)cp);
5816 continue;
5818 if (!strcmpstart(cp, "orport=")) {
5819 orport = (int)tor_parse_long(cp+strlen("orport="), 10,
5820 1, 65535, &ok, NULL);
5821 } else if (!strcmpstart(cp, "id=")) {
5822 ok = base16_decode(id, DIGEST_LEN, cp+strlen("id="),
5823 strlen(cp)-strlen("id=")) == DIGEST_LEN;
5824 } else if (!strcasecmpstart(cp, "ipv6=")) {
5825 if (ipv6_addrport_ptr) {
5826 log_warn(LD_CONFIG, "Redundant ipv6 addr/port on FallbackDir line");
5827 } else {
5828 if (tor_addr_port_parse(LOG_WARN, cp+strlen("ipv6="),
5829 &ipv6_addrport.addr, &ipv6_addrport.port,
5830 -1) < 0
5831 || tor_addr_family(&ipv6_addrport.addr) != AF_INET6) {
5832 log_warn(LD_CONFIG, "Bad ipv6 addr/port %s on FallbackDir line",
5833 escaped(cp));
5834 goto end;
5836 ipv6_addrport_ptr = &ipv6_addrport;
5838 } else if (!strcmpstart(cp, "weight=")) {
5839 int num_ok;
5840 const char *wstring = cp + strlen("weight=");
5841 weight = tor_parse_double(wstring, 0, (double)UINT64_MAX, &num_ok, NULL);
5842 if (!num_ok) {
5843 log_warn(LD_CONFIG, "Invalid weight '%s' on FallbackDir line.", cp);
5844 weight=1.0;
5848 if (!ok) {
5849 log_warn(LD_CONFIG, "Bad FallbackDir option %s", escaped(cp));
5850 goto end;
5852 } SMARTLIST_FOREACH_END(cp);
5854 if (smartlist_len(positional) != 1) {
5855 log_warn(LD_CONFIG, "Couldn't parse FallbackDir line %s", escaped(line));
5856 goto end;
5859 if (tor_digest_is_zero(id)) {
5860 log_warn(LD_CONFIG, "Missing identity on FallbackDir line");
5861 goto end;
5864 if (orport <= 0) {
5865 log_warn(LD_CONFIG, "Missing orport on FallbackDir line");
5866 goto end;
5869 if (tor_addr_port_split(LOG_INFO, smartlist_get(positional, 0),
5870 &address, &dirport) < 0 ||
5871 tor_addr_parse(&addr, address)<0) {
5872 log_warn(LD_CONFIG, "Couldn't parse address:port %s on FallbackDir line",
5873 (const char*)smartlist_get(positional, 0));
5874 goto end;
5877 if (!validate_only) {
5878 dir_server_t *ds;
5879 ds = fallback_dir_server_new(&addr, dirport, orport, ipv6_addrport_ptr,
5880 id, weight);
5881 if (!ds) {
5882 log_warn(LD_CONFIG, "Couldn't create FallbackDir %s", escaped(line));
5883 goto end;
5885 dir_server_add(ds);
5888 r = 0;
5890 end:
5891 SMARTLIST_FOREACH(items, char *, cp, tor_free(cp));
5892 smartlist_free(items);
5893 smartlist_free(positional);
5894 tor_free(address);
5895 return r;
5898 /** Allocate and return a new port_cfg_t with reasonable defaults. */
5899 port_cfg_t *
5900 port_cfg_new(size_t namelen)
5902 tor_assert(namelen <= SIZE_T_CEILING - sizeof(port_cfg_t) - 1);
5903 port_cfg_t *cfg = tor_malloc_zero(sizeof(port_cfg_t) + namelen + 1);
5904 cfg->entry_cfg.ipv4_traffic = 1;
5905 cfg->entry_cfg.ipv6_traffic = 1;
5906 cfg->entry_cfg.dns_request = 1;
5907 cfg->entry_cfg.onion_traffic = 1;
5908 cfg->entry_cfg.prefer_ipv6_virtaddr = 1;
5909 return cfg;
5912 /** Free all storage held in <b>port</b> */
5913 void
5914 port_cfg_free_(port_cfg_t *port)
5916 tor_free(port);
5919 /** Warn for every port in <b>ports</b> of type <b>listener_type</b> that is
5920 * on a publicly routable address. */
5921 static void
5922 warn_nonlocal_client_ports(const smartlist_t *ports,
5923 const char *portname,
5924 const int listener_type)
5926 SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
5927 if (port->type != listener_type)
5928 continue;
5929 if (port->is_unix_addr) {
5930 /* Unix sockets aren't accessible over a network. */
5931 } else if (!tor_addr_is_internal(&port->addr, 1)) {
5932 log_warn(LD_CONFIG, "You specified a public address '%s' for %sPort. "
5933 "Other people on the Internet might find your computer and "
5934 "use it as an open proxy. Please don't allow this unless you "
5935 "have a good reason.",
5936 fmt_addrport(&port->addr, port->port), portname);
5937 } else if (!tor_addr_is_loopback(&port->addr)) {
5938 log_notice(LD_CONFIG, "You configured a non-loopback address '%s' "
5939 "for %sPort. This allows everybody on your local network to "
5940 "use your machine as a proxy. Make sure this is what you "
5941 "wanted.",
5942 fmt_addrport(&port->addr, port->port), portname);
5944 } SMARTLIST_FOREACH_END(port);
5947 /** Given a list of port_cfg_t in <b>ports</b>, warn if any controller port
5948 * there is listening on any non-loopback address. If <b>forbid_nonlocal</b>
5949 * is true, then emit a stronger warning and remove the port from the list.
5951 static void
5952 warn_nonlocal_controller_ports(smartlist_t *ports, unsigned forbid_nonlocal)
5954 int warned = 0;
5955 SMARTLIST_FOREACH_BEGIN(ports, port_cfg_t *, port) {
5956 if (port->type != CONN_TYPE_CONTROL_LISTENER)
5957 continue;
5958 if (port->is_unix_addr)
5959 continue;
5960 if (!tor_addr_is_loopback(&port->addr)) {
5961 if (forbid_nonlocal) {
5962 if (!warned)
5963 log_warn(LD_CONFIG,
5964 "You have a ControlPort set to accept "
5965 "unauthenticated connections from a non-local address. "
5966 "This means that programs not running on your computer "
5967 "can reconfigure your Tor, without even having to guess a "
5968 "password. That's so bad that I'm closing your ControlPort "
5969 "for you. If you need to control your Tor remotely, try "
5970 "enabling authentication and using a tool like stunnel or "
5971 "ssh to encrypt remote access.");
5972 warned = 1;
5973 port_cfg_free(port);
5974 SMARTLIST_DEL_CURRENT(ports, port);
5975 } else {
5976 log_warn(LD_CONFIG, "You have a ControlPort set to accept "
5977 "connections from a non-local address. This means that "
5978 "programs not running on your computer can reconfigure your "
5979 "Tor. That's pretty bad, since the controller "
5980 "protocol isn't encrypted! Maybe you should just listen on "
5981 "127.0.0.1 and use a tool like stunnel or ssh to encrypt "
5982 "remote connections to your control port.");
5983 return; /* No point in checking the rest */
5986 } SMARTLIST_FOREACH_END(port);
5990 * Take a string (<b>line</b>) that begins with either an address:port, a
5991 * port, or an AF_UNIX address, optionally quoted, prefixed with
5992 * "unix:". Parse that line, and on success, set <b>addrport_out</b> to a new
5993 * string containing the beginning portion (without prefix). Iff there was a
5994 * unix: prefix, set <b>is_unix_out</b> to true. On success, also set
5995 * <b>rest_out</b> to point to the part of the line after the address portion.
5997 * Return 0 on success, -1 on failure.
6000 port_cfg_line_extract_addrport(const char *line,
6001 char **addrport_out,
6002 int *is_unix_out,
6003 const char **rest_out)
6005 tor_assert(line);
6006 tor_assert(addrport_out);
6007 tor_assert(is_unix_out);
6008 tor_assert(rest_out);
6010 line = eat_whitespace(line);
6012 if (!strcmpstart(line, unix_q_socket_prefix)) {
6013 // It starts with unix:"
6014 size_t sz;
6015 *is_unix_out = 1;
6016 *addrport_out = NULL;
6017 line += strlen(unix_socket_prefix); /*No q: Keep the quote */
6018 *rest_out = unescape_string(line, addrport_out, &sz);
6019 if (!*rest_out || (*addrport_out && sz != strlen(*addrport_out))) {
6020 tor_free(*addrport_out);
6021 return -1;
6023 *rest_out = eat_whitespace(*rest_out);
6024 return 0;
6025 } else {
6026 // Is there a unix: prefix?
6027 if (!strcmpstart(line, unix_socket_prefix)) {
6028 line += strlen(unix_socket_prefix);
6029 *is_unix_out = 1;
6030 } else {
6031 *is_unix_out = 0;
6034 const char *end = find_whitespace(line);
6035 if (BUG(!end)) {
6036 end = strchr(line, '\0'); // LCOV_EXCL_LINE -- this can't be NULL
6038 tor_assert(end && end >= line);
6039 *addrport_out = tor_strndup(line, end - line);
6040 *rest_out = eat_whitespace(end);
6041 return 0;
6045 static void
6046 warn_client_dns_cache(const char *option, int disabling)
6048 if (disabling)
6049 return;
6051 warn_deprecated_option(option,
6052 "Client-side DNS cacheing enables a wide variety of route-"
6053 "capture attacks. If a single bad exit node lies to you about "
6054 "an IP address, cacheing that address would make you visit "
6055 "an address of the attacker's choice every time you connected "
6056 "to your destination.");
6060 * Parse port configuration for a single port type.
6062 * Read entries of the "FooPort" type from the list <b>ports</b>. Syntax is
6063 * that FooPort can have any number of entries of the format
6064 * "[Address:][Port] IsolationOptions".
6066 * In log messages, describe the port type as <b>portname</b>.
6068 * If no address is specified, default to <b>defaultaddr</b>. If no
6069 * FooPort is given, default to defaultport (if 0, there is no default).
6071 * If CL_PORT_NO_STREAM_OPTIONS is set in <b>flags</b>, do not allow stream
6072 * isolation options in the FooPort entries.
6074 * If CL_PORT_WARN_NONLOCAL is set in <b>flags</b>, warn if any of the
6075 * ports are not on a local address. If CL_PORT_FORBID_NONLOCAL is set,
6076 * this is a control port with no password set: don't even allow it.
6078 * If CL_PORT_SERVER_OPTIONS is set in <b>flags</b>, do not allow stream
6079 * isolation options in the FooPort entries; instead allow the
6080 * server-port option set.
6082 * If CL_PORT_TAKES_HOSTNAMES is set in <b>flags</b>, allow the options
6083 * {No,}IPv{4,6}Traffic.
6085 * On success, if <b>out</b> is given, add a new port_cfg_t entry to
6086 * <b>out</b> for every port that the client should listen on. Return 0
6087 * on success, -1 on failure.
6090 port_parse_config(smartlist_t *out,
6091 const config_line_t *ports,
6092 const char *portname,
6093 int listener_type,
6094 const char *defaultaddr,
6095 int defaultport,
6096 const unsigned flags)
6098 smartlist_t *elts;
6099 int retval = -1;
6100 const unsigned is_control = (listener_type == CONN_TYPE_CONTROL_LISTENER);
6101 const unsigned is_ext_orport = (listener_type == CONN_TYPE_EXT_OR_LISTENER);
6102 const unsigned allow_no_stream_options = flags & CL_PORT_NO_STREAM_OPTIONS;
6103 const unsigned use_server_options = flags & CL_PORT_SERVER_OPTIONS;
6104 const unsigned warn_nonlocal = flags & CL_PORT_WARN_NONLOCAL;
6105 const unsigned forbid_nonlocal = flags & CL_PORT_FORBID_NONLOCAL;
6106 const unsigned default_to_group_writable =
6107 flags & CL_PORT_DFLT_GROUP_WRITABLE;
6108 const unsigned takes_hostnames = flags & CL_PORT_TAKES_HOSTNAMES;
6109 const unsigned is_unix_socket = flags & CL_PORT_IS_UNIXSOCKET;
6110 int got_zero_port=0, got_nonzero_port=0;
6111 char *unix_socket_path = NULL;
6113 /* If there's no FooPort, then maybe make a default one. */
6114 if (! ports) {
6115 if (defaultport && defaultaddr && out) {
6116 port_cfg_t *cfg = port_cfg_new(is_unix_socket ? strlen(defaultaddr) : 0);
6117 cfg->type = listener_type;
6118 if (is_unix_socket) {
6119 tor_addr_make_unspec(&cfg->addr);
6120 memcpy(cfg->unix_addr, defaultaddr, strlen(defaultaddr) + 1);
6121 cfg->is_unix_addr = 1;
6122 } else {
6123 cfg->port = defaultport;
6124 tor_addr_parse(&cfg->addr, defaultaddr);
6126 cfg->entry_cfg.session_group = SESSION_GROUP_UNSET;
6127 cfg->entry_cfg.isolation_flags = ISO_DEFAULT;
6128 smartlist_add(out, cfg);
6130 return 0;
6133 /* At last we can actually parse the FooPort lines. The syntax is:
6134 * [Addr:](Port|auto) [Options].*/
6135 elts = smartlist_new();
6136 char *addrport = NULL;
6138 for (; ports; ports = ports->next) {
6139 tor_addr_t addr;
6140 tor_addr_make_unspec(&addr);
6142 int port;
6143 int sessiongroup = SESSION_GROUP_UNSET;
6144 unsigned isolation = ISO_DEFAULT;
6145 int prefer_no_auth = 0;
6146 int socks_iso_keep_alive = 0;
6148 uint16_t ptmp=0;
6149 int ok;
6150 /* This must be kept in sync with port_cfg_new's defaults */
6151 int no_listen = 0, no_advertise = 0, all_addrs = 0,
6152 bind_ipv4_only = 0, bind_ipv6_only = 0,
6153 ipv4_traffic = 1, ipv6_traffic = 1, prefer_ipv6 = 0, dns_request = 1,
6154 onion_traffic = 1,
6155 cache_ipv4 = 0, use_cached_ipv4 = 0,
6156 cache_ipv6 = 0, use_cached_ipv6 = 0,
6157 prefer_ipv6_automap = 1, world_writable = 0, group_writable = 0,
6158 relax_dirmode_check = 0,
6159 has_used_unix_socket_only_option = 0, extended_errors = 0;
6161 int is_unix_tagged_addr = 0;
6162 const char *rest_of_line = NULL;
6163 if (port_cfg_line_extract_addrport(ports->value,
6164 &addrport, &is_unix_tagged_addr, &rest_of_line)<0) {
6165 log_warn(LD_CONFIG, "Invalid %sPort line with unparsable address",
6166 portname);
6167 goto err;
6169 if (strlen(addrport) == 0) {
6170 log_warn(LD_CONFIG, "Invalid %sPort line with no address", portname);
6171 goto err;
6174 /* Split the remainder... */
6175 smartlist_split_string(elts, rest_of_line, NULL,
6176 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
6178 /* Let's start to check if it's a Unix socket path. */
6179 if (is_unix_tagged_addr) {
6180 #ifndef HAVE_SYS_UN_H
6181 log_warn(LD_CONFIG, "Unix sockets not supported on this system.");
6182 goto err;
6183 #endif
6184 unix_socket_path = addrport;
6185 addrport = NULL;
6188 if (unix_socket_path &&
6189 ! conn_listener_type_supports_af_unix(listener_type)) {
6190 log_warn(LD_CONFIG, "%sPort does not support unix sockets", portname);
6191 goto err;
6194 if (unix_socket_path) {
6195 port = 1;
6196 } else if (is_unix_socket) {
6197 if (BUG(!addrport))
6198 goto err; // LCOV_EXCL_LINE unreachable, but coverity can't tell that
6199 unix_socket_path = tor_strdup(addrport);
6200 if (!strcmp(addrport, "0"))
6201 port = 0;
6202 else
6203 port = 1;
6204 } else if (!strcasecmp(addrport, "auto")) {
6205 port = CFG_AUTO_PORT;
6206 int af = tor_addr_parse(&addr, defaultaddr);
6207 tor_assert(af >= 0);
6208 } else if (!strcasecmpend(addrport, ":auto")) {
6209 char *addrtmp = tor_strndup(addrport, strlen(addrport)-5);
6210 port = CFG_AUTO_PORT;
6211 if (tor_addr_port_lookup(addrtmp, &addr, &ptmp)<0 || ptmp) {
6212 log_warn(LD_CONFIG, "Invalid address '%s' for %sPort",
6213 escaped(addrport), portname);
6214 tor_free(addrtmp);
6215 goto err;
6217 tor_free(addrtmp);
6218 } else {
6219 /* Try parsing integer port before address, because, who knows?
6220 "9050" might be a valid address. */
6221 port = (int) tor_parse_long(addrport, 10, 0, 65535, &ok, NULL);
6222 if (ok) {
6223 int af = tor_addr_parse(&addr, defaultaddr);
6224 tor_assert(af >= 0);
6225 } else if (tor_addr_port_lookup(addrport, &addr, &ptmp) == 0) {
6226 if (ptmp == 0) {
6227 log_warn(LD_CONFIG, "%sPort line has address but no port", portname);
6228 goto err;
6230 port = ptmp;
6231 } else {
6232 log_warn(LD_CONFIG, "Couldn't parse address %s for %sPort",
6233 escaped(addrport), portname);
6234 goto err;
6238 if (unix_socket_path && default_to_group_writable)
6239 group_writable = 1;
6241 /* Now parse the rest of the options, if any. */
6242 if (use_server_options) {
6243 /* This is a server port; parse advertising options */
6244 SMARTLIST_FOREACH_BEGIN(elts, char *, elt) {
6245 if (!strcasecmp(elt, "NoAdvertise")) {
6246 no_advertise = 1;
6247 } else if (!strcasecmp(elt, "NoListen")) {
6248 no_listen = 1;
6249 #if 0
6250 /* not implemented yet. */
6251 } else if (!strcasecmp(elt, "AllAddrs")) {
6253 all_addrs = 1;
6254 #endif /* 0 */
6255 } else if (!strcasecmp(elt, "IPv4Only")) {
6256 bind_ipv4_only = 1;
6257 } else if (!strcasecmp(elt, "IPv6Only")) {
6258 bind_ipv6_only = 1;
6259 } else {
6260 log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
6261 portname, escaped(elt));
6263 } SMARTLIST_FOREACH_END(elt);
6265 if (no_advertise && no_listen) {
6266 log_warn(LD_CONFIG, "Tried to set both NoListen and NoAdvertise "
6267 "on %sPort line '%s'",
6268 portname, escaped(ports->value));
6269 goto err;
6271 if (bind_ipv4_only && bind_ipv6_only) {
6272 log_warn(LD_CONFIG, "Tried to set both IPv4Only and IPv6Only "
6273 "on %sPort line '%s'",
6274 portname, escaped(ports->value));
6275 goto err;
6277 if (bind_ipv4_only && tor_addr_family(&addr) != AF_INET) {
6278 log_warn(LD_CONFIG, "Could not interpret %sPort address as IPv4",
6279 portname);
6280 goto err;
6282 if (bind_ipv6_only && tor_addr_family(&addr) != AF_INET6) {
6283 log_warn(LD_CONFIG, "Could not interpret %sPort address as IPv6",
6284 portname);
6285 goto err;
6287 } else {
6288 /* This is a client port; parse isolation options */
6289 SMARTLIST_FOREACH_BEGIN(elts, char *, elt) {
6290 int no = 0, isoflag = 0;
6291 const char *elt_orig = elt;
6293 if (!strcasecmpstart(elt, "SessionGroup=")) {
6294 int group = (int)tor_parse_long(elt+strlen("SessionGroup="),
6295 10, 0, INT_MAX, &ok, NULL);
6296 if (!ok || allow_no_stream_options) {
6297 log_warn(LD_CONFIG, "Invalid %sPort option '%s'",
6298 portname, escaped(elt));
6299 goto err;
6301 if (sessiongroup >= 0) {
6302 log_warn(LD_CONFIG, "Multiple SessionGroup options on %sPort",
6303 portname);
6304 goto err;
6306 sessiongroup = group;
6307 continue;
6310 if (!strcasecmpstart(elt, "No")) {
6311 no = 1;
6312 elt += 2;
6315 if (!strcasecmp(elt, "GroupWritable")) {
6316 group_writable = !no;
6317 has_used_unix_socket_only_option = 1;
6318 continue;
6319 } else if (!strcasecmp(elt, "WorldWritable")) {
6320 world_writable = !no;
6321 has_used_unix_socket_only_option = 1;
6322 continue;
6323 } else if (!strcasecmp(elt, "RelaxDirModeCheck")) {
6324 relax_dirmode_check = !no;
6325 has_used_unix_socket_only_option = 1;
6326 continue;
6329 if (allow_no_stream_options) {
6330 log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
6331 portname, escaped(elt));
6332 continue;
6335 if (takes_hostnames) {
6336 if (!strcasecmp(elt, "IPv4Traffic")) {
6337 ipv4_traffic = ! no;
6338 continue;
6339 } else if (!strcasecmp(elt, "IPv6Traffic")) {
6340 ipv6_traffic = ! no;
6341 continue;
6342 } else if (!strcasecmp(elt, "PreferIPv6")) {
6343 prefer_ipv6 = ! no;
6344 continue;
6345 } else if (!strcasecmp(elt, "DNSRequest")) {
6346 dns_request = ! no;
6347 continue;
6348 } else if (!strcasecmp(elt, "OnionTraffic")) {
6349 onion_traffic = ! no;
6350 continue;
6351 } else if (!strcasecmp(elt, "OnionTrafficOnly")) {
6352 /* Only connect to .onion addresses. Equivalent to
6353 * NoDNSRequest, NoIPv4Traffic, NoIPv6Traffic. The option
6354 * NoOnionTrafficOnly is not supported, it's too confusing. */
6355 if (no) {
6356 log_warn(LD_CONFIG, "Unsupported %sPort option 'No%s'. Use "
6357 "DNSRequest, IPv4Traffic, and/or IPv6Traffic instead.",
6358 portname, escaped(elt));
6359 } else {
6360 ipv4_traffic = ipv6_traffic = dns_request = 0;
6362 continue;
6365 if (!strcasecmp(elt, "CacheIPv4DNS")) {
6366 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
6367 cache_ipv4 = ! no;
6368 continue;
6369 } else if (!strcasecmp(elt, "CacheIPv6DNS")) {
6370 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
6371 cache_ipv6 = ! no;
6372 continue;
6373 } else if (!strcasecmp(elt, "CacheDNS")) {
6374 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
6375 cache_ipv4 = cache_ipv6 = ! no;
6376 continue;
6377 } else if (!strcasecmp(elt, "UseIPv4Cache")) {
6378 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
6379 use_cached_ipv4 = ! no;
6380 continue;
6381 } else if (!strcasecmp(elt, "UseIPv6Cache")) {
6382 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
6383 use_cached_ipv6 = ! no;
6384 continue;
6385 } else if (!strcasecmp(elt, "UseDNSCache")) {
6386 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
6387 use_cached_ipv4 = use_cached_ipv6 = ! no;
6388 continue;
6389 } else if (!strcasecmp(elt, "PreferIPv6Automap")) {
6390 prefer_ipv6_automap = ! no;
6391 continue;
6392 } else if (!strcasecmp(elt, "PreferSOCKSNoAuth")) {
6393 prefer_no_auth = ! no;
6394 continue;
6395 } else if (!strcasecmp(elt, "KeepAliveIsolateSOCKSAuth")) {
6396 socks_iso_keep_alive = ! no;
6397 continue;
6398 } else if (!strcasecmp(elt, "ExtendedErrors")) {
6399 extended_errors = ! no;
6400 continue;
6403 if (!strcasecmpend(elt, "s"))
6404 elt[strlen(elt)-1] = '\0'; /* kill plurals. */
6406 if (!strcasecmp(elt, "IsolateDestPort")) {
6407 isoflag = ISO_DESTPORT;
6408 } else if (!strcasecmp(elt, "IsolateDestAddr")) {
6409 isoflag = ISO_DESTADDR;
6410 } else if (!strcasecmp(elt, "IsolateSOCKSAuth")) {
6411 isoflag = ISO_SOCKSAUTH;
6412 } else if (!strcasecmp(elt, "IsolateClientProtocol")) {
6413 isoflag = ISO_CLIENTPROTO;
6414 } else if (!strcasecmp(elt, "IsolateClientAddr")) {
6415 isoflag = ISO_CLIENTADDR;
6416 } else {
6417 log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
6418 portname, escaped(elt_orig));
6421 if (no) {
6422 isolation &= ~isoflag;
6423 } else {
6424 isolation |= isoflag;
6426 } SMARTLIST_FOREACH_END(elt);
6429 if (port)
6430 got_nonzero_port = 1;
6431 else
6432 got_zero_port = 1;
6434 if (dns_request == 0 && listener_type == CONN_TYPE_AP_DNS_LISTENER) {
6435 log_warn(LD_CONFIG, "You have a %sPort entry with DNS disabled; that "
6436 "won't work.", portname);
6437 goto err;
6440 if (ipv4_traffic == 0 && ipv6_traffic == 0 && onion_traffic == 0
6441 && listener_type != CONN_TYPE_AP_DNS_LISTENER) {
6442 log_warn(LD_CONFIG, "You have a %sPort entry with all of IPv4 and "
6443 "IPv6 and .onion disabled; that won't work.", portname);
6444 goto err;
6447 if (dns_request == 1 && ipv4_traffic == 0 && ipv6_traffic == 0
6448 && listener_type != CONN_TYPE_AP_DNS_LISTENER) {
6449 log_warn(LD_CONFIG, "You have a %sPort entry with DNSRequest enabled, "
6450 "but IPv4 and IPv6 disabled; DNS-based sites won't work.",
6451 portname);
6452 goto err;
6455 if ( has_used_unix_socket_only_option && ! unix_socket_path) {
6456 log_warn(LD_CONFIG, "You have a %sPort entry with GroupWritable, "
6457 "WorldWritable, or RelaxDirModeCheck, but it is not a "
6458 "unix socket.", portname);
6459 goto err;
6462 if (!(isolation & ISO_SOCKSAUTH) && socks_iso_keep_alive) {
6463 log_warn(LD_CONFIG, "You have a %sPort entry with both "
6464 "NoIsolateSOCKSAuth and KeepAliveIsolateSOCKSAuth set.",
6465 portname);
6466 goto err;
6469 if (unix_socket_path && (isolation & ISO_CLIENTADDR)) {
6470 /* `IsolateClientAddr` is nonsensical in the context of AF_LOCAL.
6471 * just silently remove the isolation flag.
6473 isolation &= ~ISO_CLIENTADDR;
6476 if (out && port) {
6477 size_t namelen = unix_socket_path ? strlen(unix_socket_path) : 0;
6478 port_cfg_t *cfg = port_cfg_new(namelen);
6479 if (unix_socket_path) {
6480 tor_addr_make_unspec(&cfg->addr);
6481 memcpy(cfg->unix_addr, unix_socket_path, namelen + 1);
6482 cfg->is_unix_addr = 1;
6483 tor_free(unix_socket_path);
6484 } else {
6485 tor_addr_copy(&cfg->addr, &addr);
6486 cfg->port = port;
6488 cfg->type = listener_type;
6489 cfg->is_world_writable = world_writable;
6490 cfg->is_group_writable = group_writable;
6491 cfg->relax_dirmode_check = relax_dirmode_check;
6492 cfg->entry_cfg.isolation_flags = isolation;
6493 cfg->entry_cfg.session_group = sessiongroup;
6494 cfg->server_cfg.no_advertise = no_advertise;
6495 cfg->server_cfg.no_listen = no_listen;
6496 cfg->server_cfg.all_addrs = all_addrs;
6497 cfg->server_cfg.bind_ipv4_only = bind_ipv4_only;
6498 cfg->server_cfg.bind_ipv6_only = bind_ipv6_only;
6499 cfg->entry_cfg.ipv4_traffic = ipv4_traffic;
6500 cfg->entry_cfg.ipv6_traffic = ipv6_traffic;
6501 cfg->entry_cfg.prefer_ipv6 = prefer_ipv6;
6502 cfg->entry_cfg.dns_request = dns_request;
6503 cfg->entry_cfg.onion_traffic = onion_traffic;
6504 cfg->entry_cfg.cache_ipv4_answers = cache_ipv4;
6505 cfg->entry_cfg.cache_ipv6_answers = cache_ipv6;
6506 cfg->entry_cfg.use_cached_ipv4_answers = use_cached_ipv4;
6507 cfg->entry_cfg.use_cached_ipv6_answers = use_cached_ipv6;
6508 cfg->entry_cfg.prefer_ipv6_virtaddr = prefer_ipv6_automap;
6509 cfg->entry_cfg.socks_prefer_no_auth = prefer_no_auth;
6510 if (! (isolation & ISO_SOCKSAUTH))
6511 cfg->entry_cfg.socks_prefer_no_auth = 1;
6512 cfg->entry_cfg.socks_iso_keep_alive = socks_iso_keep_alive;
6513 cfg->entry_cfg.extended_socks5_codes = extended_errors;
6515 smartlist_add(out, cfg);
6517 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
6518 smartlist_clear(elts);
6519 tor_free(addrport);
6520 tor_free(unix_socket_path);
6523 if (warn_nonlocal && out) {
6524 if (is_control)
6525 warn_nonlocal_controller_ports(out, forbid_nonlocal);
6526 else if (is_ext_orport)
6527 port_warn_nonlocal_ext_orports(out, portname);
6528 else
6529 warn_nonlocal_client_ports(out, portname, listener_type);
6532 if (got_zero_port && got_nonzero_port) {
6533 log_warn(LD_CONFIG, "You specified a nonzero %sPort along with '%sPort 0' "
6534 "in the same configuration. Did you mean to disable %sPort or "
6535 "not?", portname, portname, portname);
6536 goto err;
6539 retval = 0;
6540 err:
6541 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
6542 smartlist_free(elts);
6543 tor_free(unix_socket_path);
6544 tor_free(addrport);
6545 return retval;
6548 /** Return the number of ports which are actually going to listen with type
6549 * <b>listenertype</b>. Do not count no_listen ports. Only count unix
6550 * sockets if count_sockets is true. */
6552 port_count_real_listeners(const smartlist_t *ports, int listenertype,
6553 int count_sockets)
6555 int n = 0;
6556 SMARTLIST_FOREACH_BEGIN(ports, port_cfg_t *, port) {
6557 if (port->server_cfg.no_listen)
6558 continue;
6559 if (!count_sockets && port->is_unix_addr)
6560 continue;
6561 if (port->type != listenertype)
6562 continue;
6563 ++n;
6564 } SMARTLIST_FOREACH_END(port);
6565 return n;
6568 /** Parse all ports from <b>options</b>. On success, set *<b>n_ports_out</b>
6569 * to the number of ports that are listed, update the *Port_set values in
6570 * <b>options</b>, and return 0. On failure, set *<b>msg</b> to a
6571 * description of the problem and return -1.
6573 * If <b>validate_only</b> is false, set configured_client_ports to the
6574 * new list of ports parsed from <b>options</b>.
6576 static int
6577 parse_ports(or_options_t *options, int validate_only,
6578 char **msg, int *n_ports_out,
6579 int *world_writable_control_socket)
6581 smartlist_t *ports;
6582 int retval = -1;
6584 ports = smartlist_new();
6586 *n_ports_out = 0;
6588 const unsigned gw_flag = options->UnixSocksGroupWritable ?
6589 CL_PORT_DFLT_GROUP_WRITABLE : 0;
6590 if (port_parse_config(ports,
6591 options->SocksPort_lines,
6592 "Socks", CONN_TYPE_AP_LISTENER,
6593 "127.0.0.1", 9050,
6594 ((validate_only ? 0 : CL_PORT_WARN_NONLOCAL)
6595 | CL_PORT_TAKES_HOSTNAMES | gw_flag)) < 0) {
6596 *msg = tor_strdup("Invalid SocksPort configuration");
6597 goto err;
6599 if (port_parse_config(ports,
6600 options->DNSPort_lines,
6601 "DNS", CONN_TYPE_AP_DNS_LISTENER,
6602 "127.0.0.1", 0,
6603 CL_PORT_WARN_NONLOCAL|CL_PORT_TAKES_HOSTNAMES) < 0) {
6604 *msg = tor_strdup("Invalid DNSPort configuration");
6605 goto err;
6607 if (port_parse_config(ports,
6608 options->TransPort_lines,
6609 "Trans", CONN_TYPE_AP_TRANS_LISTENER,
6610 "127.0.0.1", 0,
6611 CL_PORT_WARN_NONLOCAL) < 0) {
6612 *msg = tor_strdup("Invalid TransPort configuration");
6613 goto err;
6615 if (port_parse_config(ports,
6616 options->NATDPort_lines,
6617 "NATD", CONN_TYPE_AP_NATD_LISTENER,
6618 "127.0.0.1", 0,
6619 CL_PORT_WARN_NONLOCAL) < 0) {
6620 *msg = tor_strdup("Invalid NatdPort configuration");
6621 goto err;
6623 if (port_parse_config(ports,
6624 options->HTTPTunnelPort_lines,
6625 "HTTP Tunnel", CONN_TYPE_AP_HTTP_CONNECT_LISTENER,
6626 "127.0.0.1", 0,
6627 ((validate_only ? 0 : CL_PORT_WARN_NONLOCAL)
6628 | CL_PORT_TAKES_HOSTNAMES | gw_flag)) < 0) {
6629 *msg = tor_strdup("Invalid HTTPTunnelPort configuration");
6630 goto err;
6633 unsigned control_port_flags = CL_PORT_NO_STREAM_OPTIONS |
6634 CL_PORT_WARN_NONLOCAL;
6635 const int any_passwords = (options->HashedControlPassword ||
6636 options->HashedControlSessionPassword ||
6637 options->CookieAuthentication);
6638 if (! any_passwords)
6639 control_port_flags |= CL_PORT_FORBID_NONLOCAL;
6640 if (options->ControlSocketsGroupWritable)
6641 control_port_flags |= CL_PORT_DFLT_GROUP_WRITABLE;
6643 if (port_parse_config(ports,
6644 options->ControlPort_lines,
6645 "Control", CONN_TYPE_CONTROL_LISTENER,
6646 "127.0.0.1", 0,
6647 control_port_flags) < 0) {
6648 *msg = tor_strdup("Invalid ControlPort configuration");
6649 goto err;
6652 if (port_parse_config(ports, options->ControlSocket,
6653 "ControlSocket",
6654 CONN_TYPE_CONTROL_LISTENER, NULL, 0,
6655 control_port_flags | CL_PORT_IS_UNIXSOCKET) < 0) {
6656 *msg = tor_strdup("Invalid ControlSocket configuration");
6657 goto err;
6661 if (port_parse_ports_relay(options, msg, ports, &have_low_ports) < 0)
6662 goto err;
6664 *n_ports_out = smartlist_len(ports);
6666 retval = 0;
6668 /* Update the *Port_set options. The !! here is to force a boolean out of
6669 an integer. */
6670 port_update_port_set_relay(options, ports);
6671 options->SocksPort_set =
6672 !! port_count_real_listeners(ports, CONN_TYPE_AP_LISTENER, 1);
6673 options->TransPort_set =
6674 !! port_count_real_listeners(ports, CONN_TYPE_AP_TRANS_LISTENER, 1);
6675 options->NATDPort_set =
6676 !! port_count_real_listeners(ports, CONN_TYPE_AP_NATD_LISTENER, 1);
6677 options->HTTPTunnelPort_set =
6678 !! port_count_real_listeners(ports, CONN_TYPE_AP_HTTP_CONNECT_LISTENER, 1);
6679 /* Use options->ControlSocket to test if a control socket is set */
6680 options->ControlPort_set =
6681 !! port_count_real_listeners(ports, CONN_TYPE_CONTROL_LISTENER, 0);
6682 options->DNSPort_set =
6683 !! port_count_real_listeners(ports, CONN_TYPE_AP_DNS_LISTENER, 1);
6685 if (world_writable_control_socket) {
6686 SMARTLIST_FOREACH(ports, port_cfg_t *, p,
6687 if (p->type == CONN_TYPE_CONTROL_LISTENER &&
6688 p->is_unix_addr &&
6689 p->is_world_writable) {
6690 *world_writable_control_socket = 1;
6691 break;
6695 if (!validate_only) {
6696 if (configured_ports) {
6697 SMARTLIST_FOREACH(configured_ports,
6698 port_cfg_t *, p, port_cfg_free(p));
6699 smartlist_free(configured_ports);
6701 configured_ports = ports;
6702 ports = NULL; /* prevent free below. */
6705 err:
6706 if (ports) {
6707 SMARTLIST_FOREACH(ports, port_cfg_t *, p, port_cfg_free(p));
6708 smartlist_free(ports);
6710 return retval;
6713 /* Does port bind to IPv4? */
6715 port_binds_ipv4(const port_cfg_t *port)
6717 return tor_addr_family(&port->addr) == AF_INET ||
6718 (tor_addr_family(&port->addr) == AF_UNSPEC
6719 && !port->server_cfg.bind_ipv6_only);
6722 /* Does port bind to IPv6? */
6724 port_binds_ipv6(const port_cfg_t *port)
6726 return tor_addr_family(&port->addr) == AF_INET6 ||
6727 (tor_addr_family(&port->addr) == AF_UNSPEC
6728 && !port->server_cfg.bind_ipv4_only);
6731 /** Return a list of port_cfg_t for client ports parsed from the
6732 * options. */
6733 MOCK_IMPL(const smartlist_t *,
6734 get_configured_ports,(void))
6736 if (!configured_ports)
6737 configured_ports = smartlist_new();
6738 return configured_ports;
6741 /** Return an address:port string representation of the address
6742 * where the first <b>listener_type</b> listener waits for
6743 * connections. Return NULL if we couldn't find a listener. The
6744 * string is allocated on the heap and it's the responsibility of the
6745 * caller to free it after use.
6747 * This function is meant to be used by the pluggable transport proxy
6748 * spawning code, please make sure that it fits your purposes before
6749 * using it. */
6750 char *
6751 get_first_listener_addrport_string(int listener_type)
6753 static const char *ipv4_localhost = "127.0.0.1";
6754 static const char *ipv6_localhost = "[::1]";
6755 const char *address;
6756 uint16_t port;
6757 char *string = NULL;
6759 if (!configured_ports)
6760 return NULL;
6762 SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
6763 if (cfg->server_cfg.no_listen)
6764 continue;
6766 if (cfg->type == listener_type &&
6767 tor_addr_family(&cfg->addr) != AF_UNSPEC) {
6769 /* We found the first listener of the type we are interested in! */
6771 /* If a listener is listening on INADDR_ANY, assume that it's
6772 also listening on 127.0.0.1, and point the transport proxy
6773 there: */
6774 if (tor_addr_is_null(&cfg->addr))
6775 address = tor_addr_is_v4(&cfg->addr) ? ipv4_localhost : ipv6_localhost;
6776 else
6777 address = fmt_and_decorate_addr(&cfg->addr);
6779 /* If a listener is configured with port 'auto', we are forced
6780 to iterate all listener connections and find out in which
6781 port it ended up listening: */
6782 if (cfg->port == CFG_AUTO_PORT) {
6783 port = router_get_active_listener_port_by_type_af(listener_type,
6784 tor_addr_family(&cfg->addr));
6785 if (!port)
6786 return NULL;
6787 } else {
6788 port = cfg->port;
6791 tor_asprintf(&string, "%s:%u", address, port);
6793 return string;
6796 } SMARTLIST_FOREACH_END(cfg);
6798 return NULL;
6801 /** Return the first advertised port of type <b>listener_type</b> in
6802 * <b>address_family</b>. Returns 0 when no port is found, and when passed
6803 * AF_UNSPEC. */
6805 get_first_advertised_port_by_type_af(int listener_type, int address_family)
6807 if (address_family == AF_UNSPEC)
6808 return 0;
6810 const smartlist_t *conf_ports = get_configured_ports();
6811 SMARTLIST_FOREACH_BEGIN(conf_ports, const port_cfg_t *, cfg) {
6812 if (cfg->type == listener_type &&
6813 !cfg->server_cfg.no_advertise) {
6814 if ((address_family == AF_INET && port_binds_ipv4(cfg)) ||
6815 (address_family == AF_INET6 && port_binds_ipv6(cfg))) {
6816 return cfg->port;
6819 } SMARTLIST_FOREACH_END(cfg);
6820 return 0;
6823 /** Return the first advertised address of type <b>listener_type</b> in
6824 * <b>address_family</b>. Returns NULL if there is no advertised address,
6825 * and when passed AF_UNSPEC. */
6826 const tor_addr_t *
6827 get_first_advertised_addr_by_type_af(int listener_type, int address_family)
6829 if (address_family == AF_UNSPEC)
6830 return NULL;
6831 if (!configured_ports)
6832 return NULL;
6833 SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
6834 if (cfg->type == listener_type &&
6835 !cfg->server_cfg.no_advertise) {
6836 if ((address_family == AF_INET && port_binds_ipv4(cfg)) ||
6837 (address_family == AF_INET6 && port_binds_ipv6(cfg))) {
6838 return &cfg->addr;
6841 } SMARTLIST_FOREACH_END(cfg);
6842 return NULL;
6845 /** Return 1 if a port exists of type <b>listener_type</b> on <b>addr</b> and
6846 * <b>port</b>. If <b>check_wildcard</b> is true, INADDR[6]_ANY and AF_UNSPEC
6847 * addresses match any address of the appropriate family; and port -1 matches
6848 * any port.
6849 * To match auto ports, pass CFG_PORT_AUTO. (Does not match on the actual
6850 * automatically chosen listener ports.) */
6852 port_exists_by_type_addr_port(int listener_type, const tor_addr_t *addr,
6853 int port, int check_wildcard)
6855 if (!configured_ports || !addr)
6856 return 0;
6857 SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
6858 if (cfg->type == listener_type) {
6859 if (cfg->port == port || (check_wildcard && port == -1)) {
6860 /* Exact match */
6861 if (tor_addr_eq(&cfg->addr, addr)) {
6862 return 1;
6864 /* Skip wildcard matches if we're not doing them */
6865 if (!check_wildcard) {
6866 continue;
6868 /* Wildcard matches IPv4 */
6869 const int cfg_v4 = port_binds_ipv4(cfg);
6870 const int cfg_any_v4 = tor_addr_is_null(&cfg->addr) && cfg_v4;
6871 const int addr_v4 = tor_addr_family(addr) == AF_INET ||
6872 tor_addr_family(addr) == AF_UNSPEC;
6873 const int addr_any_v4 = tor_addr_is_null(&cfg->addr) && addr_v4;
6874 if ((cfg_any_v4 && addr_v4) || (cfg_v4 && addr_any_v4)) {
6875 return 1;
6877 /* Wildcard matches IPv6 */
6878 const int cfg_v6 = port_binds_ipv6(cfg);
6879 const int cfg_any_v6 = tor_addr_is_null(&cfg->addr) && cfg_v6;
6880 const int addr_v6 = tor_addr_family(addr) == AF_INET6 ||
6881 tor_addr_family(addr) == AF_UNSPEC;
6882 const int addr_any_v6 = tor_addr_is_null(&cfg->addr) && addr_v6;
6883 if ((cfg_any_v6 && addr_v6) || (cfg_v6 && addr_any_v6)) {
6884 return 1;
6888 } SMARTLIST_FOREACH_END(cfg);
6889 return 0;
6892 /* Like port_exists_by_type_addr_port, but accepts a host-order IPv4 address
6893 * instead. */
6895 port_exists_by_type_addr32h_port(int listener_type, uint32_t addr_ipv4h,
6896 int port, int check_wildcard)
6898 tor_addr_t ipv4;
6899 tor_addr_from_ipv4h(&ipv4, addr_ipv4h);
6900 return port_exists_by_type_addr_port(listener_type, &ipv4, port,
6901 check_wildcard);
6904 /** Allocate and return a good value for the DataDirectory based on
6905 * <b>val</b>, which may be NULL. Return NULL on failure. */
6906 static char *
6907 get_data_directory(const char *val)
6909 #ifdef _WIN32
6910 if (val) {
6911 return tor_strdup(val);
6912 } else {
6913 return tor_strdup(get_windows_conf_root());
6915 #else /* !defined(_WIN32) */
6916 const char *d = val;
6917 if (!d)
6918 d = "~/.tor";
6920 if (!strcmpstart(d, "~/")) {
6921 char *fn = expand_filename(d);
6922 if (!fn) {
6923 log_warn(LD_CONFIG,"Failed to expand filename \"%s\".", d);
6924 return NULL;
6926 if (!val && !strcmp(fn,"/.tor")) {
6927 /* If our homedir is /, we probably don't want to use it. */
6928 /* Default to LOCALSTATEDIR/tor which is probably closer to what we
6929 * want. */
6930 log_warn(LD_CONFIG,
6931 "Default DataDirectory is \"~/.tor\". This expands to "
6932 "\"%s\", which is probably not what you want. Using "
6933 "\"%s"PATH_SEPARATOR"tor\" instead", fn, LOCALSTATEDIR);
6934 tor_free(fn);
6935 fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor");
6937 return fn;
6939 return tor_strdup(d);
6940 #endif /* defined(_WIN32) */
6943 /** Check and normalize the values of options->{Key,Data,Cache}Directory;
6944 * return 0 if it is sane, -1 otherwise. */
6945 static int
6946 validate_data_directories(or_options_t *options)
6948 tor_free(options->DataDirectory);
6949 options->DataDirectory = get_data_directory(options->DataDirectory_option);
6950 if (!options->DataDirectory)
6951 return -1;
6952 if (strlen(options->DataDirectory) > (512-128)) {
6953 log_warn(LD_CONFIG, "DataDirectory is too long.");
6954 return -1;
6957 tor_free(options->KeyDirectory);
6958 if (options->KeyDirectory_option) {
6959 options->KeyDirectory = get_data_directory(options->KeyDirectory_option);
6960 if (!options->KeyDirectory)
6961 return -1;
6962 } else {
6963 /* Default to the data directory's keys subdir */
6964 tor_asprintf(&options->KeyDirectory, "%s"PATH_SEPARATOR"keys",
6965 options->DataDirectory);
6968 tor_free(options->CacheDirectory);
6969 if (options->CacheDirectory_option) {
6970 options->CacheDirectory = get_data_directory(
6971 options->CacheDirectory_option);
6972 if (!options->CacheDirectory)
6973 return -1;
6974 } else {
6975 /* Default to the data directory. */
6976 options->CacheDirectory = tor_strdup(options->DataDirectory);
6979 return 0;
6982 /** This string must remain the same forevermore. It is how we
6983 * recognize that the torrc file doesn't need to be backed up. */
6984 #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
6985 "if you edit it, comments will not be preserved"
6986 /** This string can change; it tries to give the reader an idea
6987 * that editing this file by hand is not a good plan. */
6988 #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
6989 "to torrc.orig.1 or similar, and Tor will ignore it"
6991 /** Save a configuration file for the configuration in <b>options</b>
6992 * into the file <b>fname</b>. If the file already exists, and
6993 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
6994 * replace it. Return 0 on success, -1 on failure. */
6995 static int
6996 write_configuration_file(const char *fname, const or_options_t *options)
6998 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
6999 int rename_old = 0, r;
7001 if (!fname)
7002 return -1;
7004 switch (file_status(fname)) {
7005 /* create backups of old config files, even if they're empty */
7006 case FN_FILE:
7007 case FN_EMPTY:
7008 old_val = read_file_to_str(fname, 0, NULL);
7009 if (!old_val || strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
7010 rename_old = 1;
7012 tor_free(old_val);
7013 break;
7014 case FN_NOENT:
7015 break;
7016 case FN_ERROR:
7017 case FN_DIR:
7018 default:
7019 log_warn(LD_CONFIG,
7020 "Config file \"%s\" is not a file? Failing.", fname);
7021 return -1;
7024 if (!(new_conf = options_dump(options, OPTIONS_DUMP_MINIMAL))) {
7025 log_warn(LD_BUG, "Couldn't get configuration string");
7026 goto err;
7029 tor_asprintf(&new_val, "%s\n%s\n\n%s",
7030 GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
7032 if (rename_old) {
7033 int i = 1;
7034 char *fn_tmp = NULL;
7035 while (1) {
7036 tor_asprintf(&fn_tmp, "%s.orig.%d", fname, i);
7037 if (file_status(fn_tmp) == FN_NOENT)
7038 break;
7039 tor_free(fn_tmp);
7040 ++i;
7042 log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
7043 if (tor_rename(fname, fn_tmp) < 0) {//XXXX sandbox doesn't allow
7044 log_warn(LD_FS,
7045 "Couldn't rename configuration file \"%s\" to \"%s\": %s",
7046 fname, fn_tmp, strerror(errno));
7047 tor_free(fn_tmp);
7048 goto err;
7050 tor_free(fn_tmp);
7053 if (write_str_to_file(fname, new_val, 0) < 0)
7054 goto err;
7056 r = 0;
7057 goto done;
7058 err:
7059 r = -1;
7060 done:
7061 tor_free(new_val);
7062 tor_free(new_conf);
7063 return r;
7067 * Save the current configuration file value to disk. Return 0 on
7068 * success, -1 on failure.
7071 options_save_current(void)
7073 /* This fails if we can't write to our configuration file.
7075 * If we try falling back to datadirectory or something, we have a better
7076 * chance of saving the configuration, but a better chance of doing
7077 * something the user never expected. */
7078 return write_configuration_file(get_torrc_fname(0), get_options());
7081 /** Return the number of cpus configured in <b>options</b>. If we are
7082 * told to auto-detect the number of cpus, return the auto-detected number. */
7084 get_num_cpus(const or_options_t *options)
7086 if (options->NumCPUs == 0) {
7087 int n = compute_num_cpus();
7088 return (n >= 1) ? n : 1;
7089 } else {
7090 return options->NumCPUs;
7095 * Initialize the libevent library.
7097 static void
7098 init_libevent(const or_options_t *options)
7100 tor_libevent_cfg_t cfg;
7102 tor_assert(options);
7104 configure_libevent_logging();
7105 /* If the kernel complains that some method (say, epoll) doesn't
7106 * exist, we don't care about it, since libevent will cope.
7108 suppress_libevent_log_msg("Function not implemented");
7110 memset(&cfg, 0, sizeof(cfg));
7111 cfg.num_cpus = get_num_cpus(options);
7112 cfg.msec_per_tick = options->TokenBucketRefillInterval;
7114 tor_libevent_initialize(&cfg);
7116 suppress_libevent_log_msg(NULL);
7119 /** Return a newly allocated string holding a filename relative to the
7120 * directory in <b>options</b> specified by <b>roottype</b>.
7121 * If <b>sub1</b> is present, it is the first path component after
7122 * the data directory. If <b>sub2</b> is also present, it is the second path
7123 * component after the data directory. If <b>suffix</b> is present, it
7124 * is appended to the filename.
7126 * Note: Consider using macros in config.h that wrap this function;
7127 * you should probably never need to call it as-is.
7129 MOCK_IMPL(char *,
7130 options_get_dir_fname2_suffix,(const or_options_t *options,
7131 directory_root_t roottype,
7132 const char *sub1, const char *sub2,
7133 const char *suffix))
7135 tor_assert(options);
7137 const char *rootdir = NULL;
7138 switch (roottype) {
7139 case DIRROOT_DATADIR:
7140 rootdir = options->DataDirectory;
7141 break;
7142 case DIRROOT_CACHEDIR:
7143 rootdir = options->CacheDirectory;
7144 break;
7145 case DIRROOT_KEYDIR:
7146 rootdir = options->KeyDirectory;
7147 break;
7148 default:
7149 tor_assert_unreached();
7150 break;
7152 tor_assert(rootdir);
7154 if (!suffix)
7155 suffix = "";
7157 char *fname = NULL;
7159 if (sub1 == NULL) {
7160 tor_asprintf(&fname, "%s%s", rootdir, suffix);
7161 tor_assert(!sub2); /* If sub2 is present, sub1 must be present. */
7162 } else if (sub2 == NULL) {
7163 tor_asprintf(&fname, "%s"PATH_SEPARATOR"%s%s", rootdir, sub1, suffix);
7164 } else {
7165 tor_asprintf(&fname, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s%s",
7166 rootdir, sub1, sub2, suffix);
7169 return fname;
7172 /** Check wether the data directory has a private subdirectory
7173 * <b>subdir</b>. If not, try to create it. Return 0 on success,
7174 * -1 otherwise. */
7176 check_or_create_data_subdir(const char *subdir)
7178 char *statsdir = get_datadir_fname(subdir);
7179 int return_val = 0;
7181 if (check_private_dir(statsdir, CPD_CREATE, get_options()->User) < 0) {
7182 log_warn(LD_HIST, "Unable to create %s/ directory!", subdir);
7183 return_val = -1;
7185 tor_free(statsdir);
7186 return return_val;
7189 /** Create a file named <b>fname</b> with contents <b>str</b> in the
7190 * subdirectory <b>subdir</b> of the data directory. <b>descr</b>
7191 * should be a short description of the file's content and will be
7192 * used for the warning message, if it's present and the write process
7193 * fails. Return 0 on success, -1 otherwise.*/
7195 write_to_data_subdir(const char* subdir, const char* fname,
7196 const char* str, const char* descr)
7198 char *filename = get_datadir_fname2(subdir, fname);
7199 int return_val = 0;
7201 if (write_str_to_file(filename, str, 0) < 0) {
7202 log_warn(LD_HIST, "Unable to write %s to disk!", descr ? descr : fname);
7203 return_val = -1;
7205 tor_free(filename);
7206 return return_val;
7209 /** Helper to implement GETINFO functions about configuration variables (not
7210 * their values). Given a "config/names" question, set *<b>answer</b> to a
7211 * new string describing the supported configuration variables and their
7212 * types. */
7214 getinfo_helper_config(control_connection_t *conn,
7215 const char *question, char **answer,
7216 const char **errmsg)
7218 (void) conn;
7219 (void) errmsg;
7220 if (!strcmp(question, "config/names")) {
7221 smartlist_t *sl = smartlist_new();
7222 smartlist_t *vars = config_mgr_list_vars(get_options_mgr());
7223 SMARTLIST_FOREACH_BEGIN(vars, const config_var_t *, var) {
7224 /* don't tell controller about invisible options */
7225 if (! config_var_is_listable(var))
7226 continue;
7227 const char *type = struct_var_get_typename(&var->member);
7228 if (!type)
7229 continue;
7230 smartlist_add_asprintf(sl, "%s %s\n",var->member.name,type);
7231 } SMARTLIST_FOREACH_END(var);
7232 *answer = smartlist_join_strings(sl, "", 0, NULL);
7233 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
7234 smartlist_free(sl);
7235 smartlist_free(vars);
7236 } else if (!strcmp(question, "config/defaults")) {
7237 smartlist_t *sl = smartlist_new();
7238 int dirauth_lines_seen = 0, fallback_lines_seen = 0;
7239 /* Possibly this should check whether the variables are listable,
7240 * but currently it does not. See ticket 31654. */
7241 smartlist_t *vars = config_mgr_list_vars(get_options_mgr());
7242 SMARTLIST_FOREACH_BEGIN(vars, const config_var_t *, var) {
7243 if (var->initvalue != NULL) {
7244 if (strcmp(var->member.name, "DirAuthority") == 0) {
7246 * Count dirauth lines we have a default for; we'll use the
7247 * count later to decide whether to add the defaults manually
7249 ++dirauth_lines_seen;
7251 if (strcmp(var->member.name, "FallbackDir") == 0) {
7253 * Similarly count fallback lines, so that we can decide later
7254 * to add the defaults manually.
7256 ++fallback_lines_seen;
7258 char *val = esc_for_log(var->initvalue);
7259 smartlist_add_asprintf(sl, "%s %s\n",var->member.name,val);
7260 tor_free(val);
7262 } SMARTLIST_FOREACH_END(var);
7263 smartlist_free(vars);
7265 if (dirauth_lines_seen == 0) {
7267 * We didn't see any directory authorities with default values,
7268 * so add the list of default authorities manually.
7272 * default_authorities is defined earlier in this file and
7273 * is a const char ** NULL-terminated array of dirauth config
7274 * lines.
7276 for (const char **i = default_authorities; *i != NULL; ++i) {
7277 char *val = esc_for_log(*i);
7278 smartlist_add_asprintf(sl, "DirAuthority %s\n", val);
7279 tor_free(val);
7283 if (fallback_lines_seen == 0 &&
7284 get_options()->UseDefaultFallbackDirs == 1) {
7286 * We didn't see any explicitly configured fallback mirrors,
7287 * so add the defaults to the list manually.
7289 * default_fallbacks is included earlier in this file and
7290 * is a const char ** NULL-terminated array of fallback config lines.
7292 const char **i;
7294 for (i = default_fallbacks; *i != NULL; ++i) {
7295 char *val = esc_for_log(*i);
7296 smartlist_add_asprintf(sl, "FallbackDir %s\n", val);
7297 tor_free(val);
7301 *answer = smartlist_join_strings(sl, "", 0, NULL);
7302 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
7303 smartlist_free(sl);
7305 return 0;
7308 /* Check whether an address has already been set against the options
7309 * depending on address family and destination type. Any exsting
7310 * value will lead to a fail, even if it is the same value. If not
7311 * set and not only validating, copy it into this location too.
7312 * Returns 0 on success or -1 if this address is already set.
7314 static int
7315 verify_and_store_outbound_address(sa_family_t family, tor_addr_t *addr,
7316 outbound_addr_t type, or_options_t *options, int validate_only)
7318 if (type>=OUTBOUND_ADDR_MAX || (family!=AF_INET && family!=AF_INET6)) {
7319 return -1;
7321 int fam_index=0;
7322 if (family==AF_INET6) {
7323 fam_index=1;
7325 tor_addr_t *dest=&options->OutboundBindAddresses[type][fam_index];
7326 if (!tor_addr_is_null(dest)) {
7327 return -1;
7329 if (!validate_only) {
7330 tor_addr_copy(dest, addr);
7332 return 0;
7335 /* Parse a list of address lines for a specific destination type.
7336 * Will store them into the options if not validate_only. If a
7337 * problem occurs, a suitable error message is store in msg.
7338 * Returns 0 on success or -1 if any address is already set.
7340 static int
7341 parse_outbound_address_lines(const config_line_t *lines, outbound_addr_t type,
7342 or_options_t *options, int validate_only, char **msg)
7344 tor_addr_t addr;
7345 sa_family_t family;
7346 while (lines) {
7347 family = tor_addr_parse(&addr, lines->value);
7348 if (verify_and_store_outbound_address(family, &addr, type,
7349 options, validate_only)) {
7350 if (msg)
7351 tor_asprintf(msg, "Multiple%s%s outbound bind addresses "
7352 "configured: %s",
7353 family==AF_INET?" IPv4":(family==AF_INET6?" IPv6":""),
7354 type==OUTBOUND_ADDR_OR?" OR":
7355 (type==OUTBOUND_ADDR_EXIT?" exit":""), lines->value);
7356 return -1;
7358 lines = lines->next;
7360 return 0;
7363 /** Parse outbound bind address option lines. If <b>validate_only</b>
7364 * is not 0 update OutboundBindAddresses in <b>options</b>.
7365 * Only one address can be set for any of these values.
7366 * On failure, set <b>msg</b> (if provided) to a newly allocated string
7367 * containing a description of the problem and return -1.
7369 static int
7370 parse_outbound_addresses(or_options_t *options, int validate_only, char **msg)
7372 if (!validate_only) {
7373 memset(&options->OutboundBindAddresses, 0,
7374 sizeof(options->OutboundBindAddresses));
7377 if (parse_outbound_address_lines(options->OutboundBindAddress,
7378 OUTBOUND_ADDR_EXIT_AND_OR, options,
7379 validate_only, msg) < 0) {
7380 goto err;
7383 if (parse_outbound_address_lines(options->OutboundBindAddressOR,
7384 OUTBOUND_ADDR_OR, options, validate_only,
7385 msg) < 0) {
7386 goto err;
7389 if (parse_outbound_address_lines(options->OutboundBindAddressExit,
7390 OUTBOUND_ADDR_EXIT, options, validate_only,
7391 msg) < 0) {
7392 goto err;
7395 return 0;
7396 err:
7397 return -1;
7400 /** Load one of the geoip files, <a>family</a> determining which
7401 * one. <a>default_fname</a> is used if on Windows and
7402 * <a>fname</a> equals "<default>". */
7403 static void
7404 config_load_geoip_file_(sa_family_t family,
7405 const char *fname,
7406 const char *default_fname)
7408 const or_options_t *options = get_options();
7409 const char *msg = "";
7410 int severity = options_need_geoip_info(options, &msg) ? LOG_WARN : LOG_INFO;
7411 int r;
7413 #ifdef _WIN32
7414 char *free_fname = NULL; /* Used to hold any temporary-allocated value */
7415 /* XXXX Don't use this "<default>" junk; make our filename options
7416 * understand prefixes somehow. -NM */
7417 if (!strcmp(fname, "<default>")) {
7418 const char *conf_root = get_windows_conf_root();
7419 tor_asprintf(&free_fname, "%s\\%s", conf_root, default_fname);
7420 fname = free_fname;
7422 r = geoip_load_file(family, fname, severity);
7423 tor_free(free_fname);
7424 #else /* !defined(_WIN32) */
7425 (void)default_fname;
7426 r = geoip_load_file(family, fname, severity);
7427 #endif /* defined(_WIN32) */
7429 if (r < 0 && severity == LOG_WARN) {
7430 log_warn(LD_GENERAL, "%s", msg);
7434 /** Load geoip files for IPv4 and IPv6 if <a>options</a> and
7435 * <a>old_options</a> indicate we should. */
7436 static void
7437 config_maybe_load_geoip_files_(const or_options_t *options,
7438 const or_options_t *old_options)
7440 /* XXXX Reload GeoIPFile on SIGHUP. -NM */
7442 if (options->GeoIPFile &&
7443 ((!old_options || !opt_streq(old_options->GeoIPFile,
7444 options->GeoIPFile))
7445 || !geoip_is_loaded(AF_INET))) {
7446 config_load_geoip_file_(AF_INET, options->GeoIPFile, "geoip");
7447 /* Okay, now we need to maybe change our mind about what is in
7448 * which country. We do this for IPv4 only since that's what we
7449 * store in node->country. */
7450 refresh_all_country_info();
7452 if (options->GeoIPv6File &&
7453 ((!old_options || !opt_streq(old_options->GeoIPv6File,
7454 options->GeoIPv6File))
7455 || !geoip_is_loaded(AF_INET6))) {
7456 config_load_geoip_file_(AF_INET6, options->GeoIPv6File, "geoip6");
7460 /** Initialize cookie authentication (used so far by the ControlPort
7461 * and Extended ORPort).
7463 * Allocate memory and create a cookie (of length <b>cookie_len</b>)
7464 * in <b>cookie_out</b>.
7465 * Then write it down to <b>fname</b> and prepend it with <b>header</b>.
7467 * If <b>group_readable</b> is set, set <b>fname</b> to be readable
7468 * by the default GID.
7470 * If the whole procedure was successful, set
7471 * <b>cookie_is_set_out</b> to True. */
7473 init_cookie_authentication(const char *fname, const char *header,
7474 int cookie_len, int group_readable,
7475 uint8_t **cookie_out, int *cookie_is_set_out)
7477 char cookie_file_str_len = strlen(header) + cookie_len;
7478 char *cookie_file_str = tor_malloc(cookie_file_str_len);
7479 int retval = -1;
7481 /* We don't want to generate a new cookie every time we call
7482 * options_act(). One should be enough. */
7483 if (*cookie_is_set_out) {
7484 retval = 0; /* we are all set */
7485 goto done;
7488 /* If we've already set the cookie, free it before re-setting
7489 it. This can happen if we previously generated a cookie, but
7490 couldn't write it to a disk. */
7491 if (*cookie_out)
7492 tor_free(*cookie_out);
7494 /* Generate the cookie */
7495 *cookie_out = tor_malloc(cookie_len);
7496 crypto_rand((char *)*cookie_out, cookie_len);
7498 /* Create the string that should be written on the file. */
7499 memcpy(cookie_file_str, header, strlen(header));
7500 memcpy(cookie_file_str+strlen(header), *cookie_out, cookie_len);
7501 if (write_bytes_to_file(fname, cookie_file_str, cookie_file_str_len, 1)) {
7502 log_warn(LD_FS,"Error writing auth cookie to %s.", escaped(fname));
7503 goto done;
7506 #ifndef _WIN32
7507 if (group_readable) {
7508 if (chmod(fname, 0640)) {
7509 log_warn(LD_FS,"Unable to make %s group-readable.", escaped(fname));
7512 #else /* defined(_WIN32) */
7513 (void) group_readable;
7514 #endif /* !defined(_WIN32) */
7516 /* Success! */
7517 log_info(LD_GENERAL, "Generated auth cookie file in '%s'.", escaped(fname));
7518 *cookie_is_set_out = 1;
7519 retval = 0;
7521 done:
7522 memwipe(cookie_file_str, 0, cookie_file_str_len);
7523 tor_free(cookie_file_str);
7524 return retval;
7528 * Return true if any option is set in <b>options</b> to make us behave
7529 * as a client.
7532 options_any_client_port_set(const or_options_t *options)
7534 return (options->SocksPort_set ||
7535 options->TransPort_set ||
7536 options->NATDPort_set ||
7537 options->DNSPort_set ||
7538 options->HTTPTunnelPort_set);