Tor 0.4.9.13
Loading...
Searching...
No Matches
config.c
Go to the documentation of this file.
1/* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2021, The Tor Project, Inc. */
5/* See LICENSE for licensing information */
6
7/**
8 * \file config.c
9 * \brief Code to interpret the user's configuration of Tor.
10 *
11 * This module handles torrc configuration file, including parsing it,
12 * combining it with torrc.defaults and the command line, allowing
13 * user changes to it (via editing and SIGHUP or via the control port),
14 * writing it back to disk (because of SAVECONF from the control port),
15 * and -- most importantly, acting on it.
16 *
17 * The module additionally has some tools for manipulating and
18 * inspecting values that are calculated as a result of the
19 * configured options.
20 *
21 * <h3>How to add new options</h3>
22 *
23 * To add new items to the torrc, there are a minimum of three places to edit:
24 * <ul>
25 * <li>The or_options_t structure in or_options_st.h, where the options are
26 * stored.
27 * <li>The option_vars_ array below in this module, which configures
28 * the names of the torrc options, their types, their multiplicities,
29 * and their mappings to fields in or_options_t.
30 * <li>The manual in doc/man/tor.1.txt, to document what the new option
31 * is, and how it works.
32 * </ul>
33 *
34 * Additionally, you might need to edit these places too:
35 * <ul>
36 * <li>options_validate_cb() below, in case you want to reject some possible
37 * values of the new configuration option.
38 * <li>options_transition_allowed() below, in case you need to
39 * forbid some or all changes in the option while Tor is
40 * running.
41 * <li>options_transition_affects_workers(), in case changes in the option
42 * might require Tor to relaunch or reconfigure its worker threads.
43 * (This function is now in the relay module.)
44 * <li>options_transition_affects_descriptor(), in case changes in the
45 * option might require a Tor relay to build and publish a new server
46 * descriptor.
47 * (This function is now in the relay module.)
48 * <li>options_act() and/or options_act_reversible(), in case there's some
49 * action that needs to be taken immediately based on the option's
50 * value.
51 * </ul>
52 *
53 * <h3>Changing the value of an option</h3>
54 *
55 * Because of the SAVECONF command from the control port, it's a bad
56 * idea to change the value of any user-configured option in the
57 * or_options_t. If you want to sometimes do this anyway, we recommend
58 * that you create a secondary field in or_options_t; that you have the
59 * user option linked only to the secondary field; that you use the
60 * secondary field to initialize the one that Tor actually looks at; and that
61 * you use the one Tor looks as the one that you modify.
62 **/
63
64#define CONFIG_PRIVATE
65#include "core/or/or.h"
66#include "app/config/config.h"
67#include "lib/confmgt/confmgt.h"
69#include "app/main/main.h"
70#include "app/main/subsysmgr.h"
74#include "core/or/channel.h"
75#include "core/or/circuitlist.h"
76#include "core/or/circuitmux.h"
80#include "trunnel/conflux.h"
81#include "core/or/dos.h"
82#include "core/or/policies.h"
83#include "core/or/relay.h"
84#include "core/or/scheduler.h"
96#include "feature/hs/hs_pow.h"
104#include "feature/relay/dns.h"
109#include "lib/geoip/geoip.h"
117#include "lib/net/resolve.h"
118#include "lib/sandbox/sandbox.h"
120
121#ifdef ENABLE_NSS
123#else
125#endif
126
127#ifdef _WIN32
128#include <shlobj.h>
129#endif
130#ifdef HAVE_FCNTL_H
131#include <fcntl.h>
132#endif
133#ifdef HAVE_SYS_STAT_H
134#include <sys/stat.h>
135#endif
136#ifdef HAVE_SYS_PARAM_H
137#include <sys/param.h>
138#endif
139#ifdef HAVE_UNISTD_H
140#include <unistd.h>
141#endif
142
143#include "lib/meminfo/meminfo.h"
144#include "lib/osinfo/uname.h"
145#include "lib/osinfo/libc.h"
146#include "lib/process/daemon.h"
147#include "lib/process/pidfile.h"
148#include "lib/process/restrict.h"
149#include "lib/process/setuid.h"
150#include "lib/process/process.h"
151#include "lib/net/gethostname.h"
152#include "lib/thread/numcpus.h"
153
154#include "lib/encoding/keyval.h"
155#include "lib/fs/conffile.h"
156#include "lib/evloop/procmon.h"
157
160
162#include "core/or/port_cfg_st.h"
163
164#ifdef HAVE_SYSTEMD
165# if defined(__COVERITY__) && !defined(__INCLUDE_LEVEL__)
166/* Systemd's use of gcc's __INCLUDE_LEVEL__ extension macro appears to confuse
167 * Coverity. Here's a kludge to unconfuse it.
168 */
169# define __INCLUDE_LEVEL__ 2
170#endif /* defined(__COVERITY__) && !defined(__INCLUDE_LEVEL__) */
171#include <systemd/sd-daemon.h>
172#endif /* defined(HAVE_SYSTEMD) */
173
174/* Prefix used to indicate a Unix socket in a FooPort configuration. */
175static const char unix_socket_prefix[] = "unix:";
176/* Prefix used to indicate a Unix socket with spaces in it, in a FooPort
177 * configuration. */
178static const char unix_q_socket_prefix[] = "unix:\"";
179
180/* limits for TCP send and recv buffer size used for constrained sockets */
181#define MIN_CONSTRAINED_TCP_BUFFER 2048
182#define MAX_CONSTRAINED_TCP_BUFFER 262144 /* 256k */
183
184/** macro to help with the bulk rename of *DownloadSchedule to
185 * *DownloadInitialDelay . */
186#ifndef COCCI
187#define DOWNLOAD_SCHEDULE(name) \
188 { (#name "DownloadSchedule"), (#name "DownloadInitialDelay"), 0, 1 }
189#else
190#define DOWNLOAD_SCHEDULE(name) { NULL, NULL, 0, 1 }
191#endif /* !defined(COCCI) */
192
193/** A list of abbreviations and aliases to map command-line options, obsolete
194 * option names, or alternative option names, to their current values. */
196 PLURAL(AuthDirBadDirCC),
197 PLURAL(AuthDirBadExitCC),
198 PLURAL(AuthDirInvalidCC),
199 PLURAL(AuthDirMiddleOnlyCC),
200 PLURAL(AuthDirRejectCC),
201 PLURAL(EntryNode),
202 PLURAL(ExcludeNode),
203 PLURAL(FirewallPort),
204 PLURAL(LongLivedPort),
205 PLURAL(HiddenServiceNode),
206 PLURAL(HiddenServiceExcludeNode),
207 PLURAL(NumCPU),
208 PLURAL(RendNode),
209 PLURAL(RecommendedPackage),
210 PLURAL(RendExcludeNode),
211 PLURAL(StrictEntryNode),
212 PLURAL(StrictExitNode),
213 PLURAL(StrictNode),
214 { "l", "Log", 1, 0},
215 { "AllowUnverifiedNodes", "AllowInvalidNodes", 0, 0},
216 { "AutomapHostSuffixes", "AutomapHostsSuffixes", 0, 0},
217 { "AutomapHostOnResolve", "AutomapHostsOnResolve", 0, 0},
218 { "BandwidthRateBytes", "BandwidthRate", 0, 0},
219 { "BandwidthBurstBytes", "BandwidthBurst", 0, 0},
220 { "DirFetchPostPeriod", "StatusFetchPeriod", 0, 0},
221 { "DirServer", "DirAuthority", 0, 0}, /* XXXX later, make this warn? */
222 { "MaxConn", "ConnLimit", 0, 1},
223 { "MaxMemInCellQueues", "MaxMemInQueues", 0, 0},
224 { "ORBindAddress", "ORListenAddress", 0, 0},
225 { "DirBindAddress", "DirListenAddress", 0, 0},
226 { "SocksBindAddress", "SocksListenAddress", 0, 0},
227 { "UseHelperNodes", "UseEntryGuards", 0, 0},
228 { "NumHelperNodes", "NumEntryGuards", 0, 0},
229 { "UseEntryNodes", "UseEntryGuards", 0, 0},
230 { "NumEntryNodes", "NumEntryGuards", 0, 0},
231 { "ResolvConf", "ServerDNSResolvConfFile", 0, 1},
232 { "SearchDomains", "ServerDNSSearchDomains", 0, 1},
233 { "ServerDNSAllowBrokenResolvConf", "ServerDNSAllowBrokenConfig", 0, 0},
234 { "PreferTunnelledDirConns", "PreferTunneledDirConns", 0, 0},
235 { "BridgeAuthoritativeDirectory", "BridgeAuthoritativeDir", 0, 0},
236 { "HashedControlPassword", "__HashedControlSessionPassword", 1, 0},
237 { "VirtualAddrNetwork", "VirtualAddrNetworkIPv4", 0, 0},
238 { "SocksSocketsGroupWritable", "UnixSocksGroupWritable", 0, 1},
239 { "_HSLayer2Nodes", "HSLayer2Nodes", 0, 1 },
240 { "_HSLayer3Nodes", "HSLayer3Nodes", 0, 1 },
241
242 DOWNLOAD_SCHEDULE(ClientBootstrapConsensusAuthority),
243 DOWNLOAD_SCHEDULE(ClientBootstrapConsensusAuthorityOnly),
244 DOWNLOAD_SCHEDULE(ClientBootstrapConsensusFallback),
245 DOWNLOAD_SCHEDULE(TestingBridge),
246 DOWNLOAD_SCHEDULE(TestingBridgeBootstrap),
247 DOWNLOAD_SCHEDULE(TestingClient),
248 DOWNLOAD_SCHEDULE(TestingClientConsensus),
249 DOWNLOAD_SCHEDULE(TestingServer),
250 DOWNLOAD_SCHEDULE(TestingServerConsensus),
251
252 { NULL, NULL, 0, 0},
253};
254
255/** dummy instance of or_options_t, used for type-checking its
256 * members with CONF_CHECK_VAR_TYPE. */
257DUMMY_TYPECHECK_INSTANCE(or_options_t);
258
259/** An entry for config_vars: "The option <b>varname</b> has type
260 * CONFIG_TYPE_<b>conftype</b>, and corresponds to
261 * or_options_t.<b>member</b>"
262 */
263#define VAR(varname,conftype,member,initvalue) \
264 CONFIG_VAR_ETYPE(or_options_t, varname, conftype, member, 0, initvalue)
265
266/* As VAR, but uses a type definition in addition to a type enum. */
267#define VAR_D(varname,conftype,member,initvalue) \
268 CONFIG_VAR_DEFN(or_options_t, varname, conftype, member, 0, initvalue)
269
270#define VAR_NODUMP(varname,conftype,member,initvalue) \
271 CONFIG_VAR_ETYPE(or_options_t, varname, conftype, member, \
272 CFLG_NODUMP, initvalue)
273#define VAR_NODUMP_IMMUTABLE(varname,conftype,member,initvalue) \
274 CONFIG_VAR_ETYPE(or_options_t, varname, conftype, member, \
275 CFLG_NODUMP | CFLG_IMMUTABLE, initvalue)
276#define VAR_INVIS(varname,conftype,member,initvalue) \
277 CONFIG_VAR_ETYPE(or_options_t, varname, conftype, member, \
278 CFLG_NODUMP | CFLG_NOSET | CFLG_NOLIST, initvalue)
279
280#define V(member,conftype,initvalue) \
281 VAR(#member, conftype, member, initvalue)
282
283#define VAR_IMMUTABLE(varname, conftype, member, initvalue) \
284 CONFIG_VAR_ETYPE(or_options_t, varname, conftype, member, \
285 CFLG_IMMUTABLE, initvalue)
286
287#define V_IMMUTABLE(member,conftype,initvalue) \
288 VAR_IMMUTABLE(#member, conftype, member, initvalue)
289
290/** As V, but uses a type definition instead of a type enum */
291#define V_D(member,type,initvalue) \
292 VAR_D(#member, type, member, initvalue)
293
294/** An entry for config_vars: "The option <b>varname</b> is obsolete." */
295#define OBSOLETE(varname) CONFIG_VAR_OBSOLETE(varname)
296
297/**
298 * Macro to declare *Port options. Each one comes in three entries.
299 * For example, most users should use "SocksPort" to configure the
300 * socks port, but TorBrowser wants to use __SocksPort so that it
301 * isn't stored by SAVECONF. The SocksPortLines virtual option is
302 * used to query both options from the controller.
303 */
304#define VPORT(member) \
305 VAR(#member "Lines", LINELIST_V, member ## _lines, NULL), \
306 VAR(#member, LINELIST_S, member ## _lines, NULL), \
307 VAR_NODUMP("__" #member, LINELIST_S, member ## _lines, NULL)
308
309/** UINT64_MAX as a decimal string */
310#define UINT64_MAX_STRING "18446744073709551615"
311
312/** Array of configuration options. Until we disallow nonstandard
313 * abbreviations, order is significant, since the first matching option will
314 * be chosen first.
315 */
316static const config_var_t option_vars_[] = {
317 V(AccountingMax, MEMUNIT, "0 bytes"),
318 VAR("AccountingRule", STRING, AccountingRule_option, "max"),
319 V(AccountingStart, STRING, NULL),
320 V(Address, LINELIST, NULL),
321 V(AddressDisableIPv6, BOOL, "0"),
322 OBSOLETE("AllowDotExit"),
323 OBSOLETE("AllowInvalidNodes"),
324 V(AllowNonRFC953Hostnames, BOOL, "0"),
325 OBSOLETE("AllowSingleHopCircuits"),
326 OBSOLETE("AllowSingleHopExits"),
327 V(AlternateBridgeAuthority, LINELIST, NULL),
328 V(AlternateDirAuthority, LINELIST, NULL),
329 OBSOLETE("AlternateHSAuthority"),
330 V(AssumeReachable, BOOL, "0"),
331 V(AssumeReachableIPv6, AUTOBOOL, "auto"),
332 OBSOLETE("AuthDirBadDir"),
333 OBSOLETE("AuthDirBadDirCCs"),
334 V(AuthDirBadExit, LINELIST, NULL),
335 V(AuthDirBadExitCCs, CSV, ""),
336 V(AuthDirInvalid, LINELIST, NULL),
337 V(AuthDirInvalidCCs, CSV, ""),
338 V(AuthDirMiddleOnly, LINELIST, NULL),
339 V(AuthDirMiddleOnlyCCs, CSV, ""),
340 V(AuthDirReject, LINELIST, NULL),
341 V(AuthDirRejectCCs, CSV, ""),
342 OBSOLETE("AuthDirRejectUnlisted"),
343 OBSOLETE("AuthDirListBadDirs"),
344 OBSOLETE("AuthDirMaxServersPerAuthAddr"),
345 V(AuthDirSupport048Clients, BOOL, "0"),
346 VAR("AuthoritativeDirectory", BOOL, AuthoritativeDir, "0"),
347 V(AutomapHostsOnResolve, BOOL, "0"),
348 V(AutomapHostsSuffixes, CSV, ".onion,.exit"),
349 V(AvoidDiskWrites, BOOL, "0"),
350 V(BandwidthBurst, MEMUNIT, "1 GB"),
351 V(BandwidthRate, MEMUNIT, "1 GB"),
352 V(BridgeAuthoritativeDir, BOOL, "0"),
353 VAR("Bridge", LINELIST, Bridges, NULL),
354 V(BridgePassword, STRING, NULL),
355 V(BridgeRecordUsageByCountry, BOOL, "1"),
356 V(BridgeRelay, BOOL, "0"),
357 V(BridgeDistribution, STRING, NULL),
358 VAR_IMMUTABLE("CacheDirectory",FILENAME, CacheDirectory_option, NULL),
359 V(CacheDirectoryGroupReadable, AUTOBOOL, "auto"),
360 V(CellStatistics, BOOL, "0"),
361 V(PaddingStatistics, BOOL, "1"),
362 V(OverloadStatistics, BOOL, "1"),
363 V(LearnCircuitBuildTimeout, BOOL, "1"),
364 V(CircuitBuildTimeout, INTERVAL, "0"),
365 OBSOLETE("CircuitIdleTimeout"),
366 V(CircuitsAvailableTimeout, INTERVAL, "0"),
367 V(CircuitStreamTimeout, INTERVAL, "0"),
368 V(CircuitPriorityHalflife, DOUBLE, "-1.0"), /*negative:'Use default'*/
369 V(ClientDNSRejectInternalAddresses, BOOL,"1"),
370#if defined(HAVE_MODULE_RELAY) || defined(TOR_UNIT_TESTS)
371 /* The unit tests expect the ClientOnly default to be 0. */
372 V(ClientOnly, BOOL, "0"),
373#else
374 /* We must be a Client if the relay module is disabled. */
375 V(ClientOnly, BOOL, "1"),
376#endif /* defined(HAVE_MODULE_RELAY) || defined(TOR_UNIT_TESTS) */
377 V(ClientPreferIPv6ORPort, AUTOBOOL, "auto"),
378 V(ClientPreferIPv6DirPort, AUTOBOOL, "auto"),
379 OBSOLETE("ClientAutoIPv6ORPort"),
380 V(ClientRejectInternalAddresses, BOOL, "1"),
381 V(ClientTransportPlugin, LINELIST, NULL),
382 V(ClientUseIPv6, BOOL, "1"),
383 V(ClientUseIPv4, BOOL, "1"),
384 V(CompiledProofOfWorkHash, AUTOBOOL, "auto"),
385 V(ConfluxEnabled, AUTOBOOL, "auto"),
386 VAR("ConfluxClientUX", STRING, ConfluxClientUX_option,
387 "throughput"),
388 V(ConnLimit, POSINT, "1000"),
389 V(ConnDirectionStatistics, BOOL, "0"),
390 V(ConstrainedSockets, BOOL, "0"),
391 V(ConstrainedSockSize, MEMUNIT, "8192"),
392 V(ContactInfo, STRING, NULL),
393 OBSOLETE("ControlListenAddress"),
394 VPORT(ControlPort),
395 V(ControlPortFileGroupReadable,BOOL, "0"),
396 V(ControlPortWriteToFile, FILENAME, NULL),
397 V(ControlSocket, LINELIST, NULL),
398 V(ControlSocketsGroupWritable, BOOL, "0"),
399 V(UnixSocksGroupWritable, BOOL, "0"),
400 V(CookieAuthentication, BOOL, "0"),
401 V(CookieAuthFileGroupReadable, BOOL, "0"),
402 V(CookieAuthFile, FILENAME, NULL),
403 V(CountPrivateBandwidth, BOOL, "0"),
404 VAR_IMMUTABLE("DataDirectory", FILENAME, DataDirectory_option, NULL),
405 V(DataDirectoryGroupReadable, BOOL, "0"),
406 V(DisableOOSCheck, BOOL, "1"),
407 V(DisableNetwork, BOOL, "0"),
408 V(DirAllowPrivateAddresses, BOOL, "0"),
409 OBSOLETE("DirListenAddress"),
410 V(DirPolicy, LINELIST, NULL),
411 VPORT(DirPort),
412 V(DirPortFrontPage, FILENAME, NULL),
413 VAR("DirReqStatistics", BOOL, DirReqStatistics_option, "1"),
414 VAR("DirAuthority", LINELIST, DirAuthorities, NULL),
415#if defined(HAVE_MODULE_RELAY) || defined(TOR_UNIT_TESTS)
416 /* The unit tests expect the DirCache default to be 1. */
417 V(DirCache, BOOL, "1"),
418#else
419 /* We can't be a DirCache if the relay module is disabled. */
420 V(DirCache, BOOL, "0"),
421#endif /* defined(HAVE_MODULE_RELAY) || defined(TOR_UNIT_TESTS) */
422 /* A DirAuthorityFallbackRate of 0.1 means that 0.5% of clients try an
423 * authority when all fallbacks are up, and 2% try an authority when 25% of
424 * fallbacks are down. (We rebuild the list when 25% of fallbacks are down).
425 *
426 * We want to reduce load on authorities, but keep these two figures within
427 * an order of magnitude, so there isn't too much load shifting to
428 * authorities when fallbacks go down. */
429 V(DirAuthorityFallbackRate, DOUBLE, "0.1"),
430 V_IMMUTABLE(DisableAllSwap, BOOL, "0"),
431 V_IMMUTABLE(DisableDebuggerAttachment, BOOL, "1"),
432 OBSOLETE("DisableIOCP"),
433 OBSOLETE("DisableV2DirectoryInfo_"),
434 OBSOLETE("DynamicDHGroups"),
435 VPORT(DNSPort),
436 OBSOLETE("DNSListenAddress"),
437 V(DormantClientTimeout, INTERVAL, "24 hours"),
438 V(DormantTimeoutEnabled, BOOL, "1"),
439 V(DormantTimeoutDisabledByIdleStreams, BOOL, "1"),
440 V(DormantOnFirstStartup, BOOL, "0"),
441 V(DormantCanceledByStartup, BOOL, "0"),
442 V(DownloadExtraInfo, BOOL, "0"),
443 V(TestingEnableConnBwEvent, BOOL, "0"),
444 V(TestingEnableCellStatsEvent, BOOL, "0"),
445 OBSOLETE("TestingEnableTbEmptyEvent"),
446 V(EnforceDistinctSubnets, BOOL, "1"),
447 V_D(EntryNodes, ROUTERSET, NULL),
448 V(EntryStatistics, BOOL, "0"),
449 OBSOLETE("TestingEstimatedDescriptorPropagationTime"),
450 V_D(ExcludeNodes, ROUTERSET, NULL),
451 V_D(ExcludeExitNodes, ROUTERSET, NULL),
452 OBSOLETE("ExcludeSingleHopRelays"),
453 V_D(ExitNodes, ROUTERSET, NULL),
454 /* Researchers need a way to tell their clients to use specific
455 * middles that they also control, to allow safe live-network
456 * experimentation with new padding machines. */
457 V_D(MiddleNodes, ROUTERSET, NULL),
458 V(ExitPolicy, LINELIST, NULL),
459 V(ExitPolicyRejectPrivate, BOOL, "1"),
460 V(ExitPolicyRejectLocalInterfaces, BOOL, "0"),
461 V(ExitPortStatistics, BOOL, "0"),
462 V(ExtendAllowPrivateAddresses, BOOL, "0"),
463 V(ExitRelay, AUTOBOOL, "auto"),
464 VPORT(ExtORPort),
465 V(ExtORPortCookieAuthFile, FILENAME, NULL),
466 V(ExtORPortCookieAuthFileGroupReadable, BOOL, "0"),
467 V(ExtraInfoStatistics, BOOL, "1"),
468 V(ExtendByEd25519ID, AUTOBOOL, "auto"),
469 V(FallbackDir, LINELIST, NULL),
470
471 V(UseDefaultFallbackDirs, BOOL, "1"),
472
473 OBSOLETE("FallbackNetworkstatusFile"),
474 VAR("FamilyId", LINELIST, FamilyId_lines, NULL),
475 VAR_IMMUTABLE("FamilyKeyDirectory",
476 FILENAME, FamilyKeyDirectory_option, NULL),
477 V(FascistFirewall, BOOL, "0"),
478 V(FirewallPorts, CSV, ""),
479 OBSOLETE("FastFirstHopPK"),
480 V(FetchDirInfoEarly, BOOL, "0"),
481 V(FetchDirInfoExtraEarly, BOOL, "0"),
482 V(FetchServerDescriptors, BOOL, "1"),
483 V(FetchHidServDescriptors, BOOL, "1"),
484 V(FetchUselessDescriptors, BOOL, "0"),
485 OBSOLETE("FetchV2Networkstatus"),
486 V(GeoIPExcludeUnknown, AUTOBOOL, "auto"),
487#ifdef _WIN32
488 V(GeoIPFile, FILENAME, "<default>"),
489 V(GeoIPv6File, FILENAME, "<default>"),
490#elif defined(__ANDROID__)
491 /* Android apps use paths that are configured at runtime.
492 * /data/local/tmp is guaranteed to exist, but will only be
493 * usable by the 'shell' and 'root' users, so this fallback is
494 * for debugging only. */
495 V(GeoIPFile, FILENAME, "/data/local/tmp/geoip"),
496 V(GeoIPv6File, FILENAME, "/data/local/tmp/geoip6"),
497#else
498 V(GeoIPFile, FILENAME,
499 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip"),
500 V(GeoIPv6File, FILENAME,
501 SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip6"),
502#endif /* defined(_WIN32) */
503 OBSOLETE("Group"),
504 V(GuardLifetime, INTERVAL, "0 minutes"),
505 V(HeartbeatPeriod, INTERVAL, "6 hours"),
506 V(MainloopStats, BOOL, "0"),
507 V(HashedControlPassword, LINELIST, NULL),
508 OBSOLETE("HidServDirectoryV2"),
509 OBSOLETE("HiddenServiceAuthorizeClient"),
510 OBSOLETE("HidServAuth"),
511 VAR("HiddenServiceDir", LINELIST_S, RendConfigLines, NULL),
512 VAR("HiddenServiceDirGroupReadable", LINELIST_S, RendConfigLines, NULL),
513 VAR("HiddenServiceOptions",LINELIST_V, RendConfigLines, NULL),
514 VAR("HiddenServicePort", LINELIST_S, RendConfigLines, NULL),
515 VAR("HiddenServiceVersion",LINELIST_S, RendConfigLines, NULL),
516 VAR("HiddenServiceAllowUnknownPorts",LINELIST_S, RendConfigLines, NULL),
517 VAR("HiddenServiceMaxStreams",LINELIST_S, RendConfigLines, NULL),
518 VAR("HiddenServiceMaxStreamsCloseCircuit",LINELIST_S, RendConfigLines, NULL),
519 VAR("HiddenServiceNumIntroductionPoints", LINELIST_S, RendConfigLines, NULL),
520 VAR("HiddenServiceExportCircuitID", LINELIST_S, RendConfigLines, NULL),
521 VAR("HiddenServiceEnableIntroDoSDefense", LINELIST_S, RendConfigLines, NULL),
522 VAR("HiddenServiceEnableIntroDoSRatePerSec",
523 LINELIST_S, RendConfigLines, NULL),
524 VAR("HiddenServiceEnableIntroDoSBurstPerSec",
525 LINELIST_S, RendConfigLines, NULL),
526 VAR("HiddenServiceOnionBalanceInstance",
527 LINELIST_S, RendConfigLines, NULL),
528 VAR("HiddenServicePoWDefensesEnabled", LINELIST_S, RendConfigLines, NULL),
529 VAR("HiddenServicePoWQueueRate", LINELIST_S, RendConfigLines, NULL),
530 VAR("HiddenServicePoWQueueBurst", LINELIST_S, RendConfigLines, NULL),
531 VAR("HiddenServiceStatistics", BOOL, HiddenServiceStatistics_option, "1"),
532 V(ClientOnionAuthDir, FILENAME, NULL),
533 OBSOLETE("CloseHSClientCircuitsImmediatelyOnTimeout"),
534 OBSOLETE("CloseHSServiceRendCircuitsImmediatelyOnTimeout"),
535 V_IMMUTABLE(HiddenServiceSingleHopMode, BOOL, "0"),
536 V_IMMUTABLE(HiddenServiceNonAnonymousMode,BOOL, "0"),
537 V(HTTPProxy, STRING, NULL),
538 V(HTTPProxyAuthenticator, STRING, NULL),
539 V(HTTPSProxy, STRING, NULL),
540 V(HTTPSProxyAuthenticator, STRING, NULL),
541 VPORT(HTTPTunnelPort),
542 V(IPv6Exit, BOOL, "0"),
543 VAR("ServerTransportPlugin", LINELIST, ServerTransportPlugin, NULL),
544 V(ServerTransportListenAddr, LINELIST, NULL),
545 V(ServerTransportOptions, LINELIST, NULL),
546 V(SigningKeyLifetime, INTERVAL, "30 days"),
547 V(Socks4Proxy, STRING, NULL),
548 V(Socks5Proxy, STRING, NULL),
549 V(Socks5ProxyUsername, STRING, NULL),
550 V(Socks5ProxyPassword, STRING, NULL),
551 V(TCPProxy, STRING, NULL),
552 VAR_IMMUTABLE("KeyDirectory", FILENAME, KeyDirectory_option, NULL),
553 V(KeyDirectoryGroupReadable, AUTOBOOL, "auto"),
554 VAR_D("HSLayer2Nodes", ROUTERSET, HSLayer2Nodes, NULL),
555 VAR_D("HSLayer3Nodes", ROUTERSET, HSLayer3Nodes, NULL),
556 V(KeepalivePeriod, INTERVAL, "5 minutes"),
557 V_IMMUTABLE(KeepBindCapabilities, AUTOBOOL, "auto"),
558 VAR("Log", LINELIST, Logs, NULL),
559 V(LogMessageDomains, BOOL, "0"),
560 V(LogTimeGranularity, MSEC_INTERVAL, "1 second"),
561 V(TruncateLogFile, BOOL, "0"),
562 V_IMMUTABLE(SyslogIdentityTag, STRING, NULL),
563 OBSOLETE("AndroidIdentityTag"),
564 V(LongLivedPorts, CSV,
565 "21,22,706,1863,5050,5190,5222,5223,6523,6667,6697,8300"),
566 VAR("MapAddress", LINELIST, AddressMap, NULL),
567 V(MaxAdvertisedBandwidth, MEMUNIT, "1 GB"),
568 V(MaxCircuitDirtiness, INTERVAL, "10 minutes"),
569 V(MaxClientCircuitsPending, POSINT, "32"),
570 V(MaxConsensusAgeForDiffs, INTERVAL, "0 seconds"),
571 VAR("MaxMemInQueues", MEMUNIT, MaxMemInQueues_raw, "0"),
572 VAR("MaxHSDirCacheBytes", MEMUNIT, MaxHSDirCacheBytes, "0"),
573 OBSOLETE("MaxOnionsPending"),
574 V(MaxOnionQueueDelay, MSEC_INTERVAL, "0"),
575 V(MaxUnparseableDescSizeToLog, MEMUNIT, "10 MB"),
576 VPORT(MetricsPort),
577 V(MetricsPortPolicy, LINELIST, NULL),
578 V(TestingMinTimeToReportBandwidth, INTERVAL, "1 day"),
579 VAR("MyFamily", LINELIST, MyFamily_lines, NULL),
580 V(NewCircuitPeriod, INTERVAL, "30 seconds"),
581 OBSOLETE("NamingAuthoritativeDirectory"),
582 OBSOLETE("NATDListenAddress"),
583 VPORT(NATDPort),
584 V(Nickname, STRING, NULL),
585 OBSOLETE("PredictedPortsRelevanceTime"),
586 OBSOLETE("WarnUnsafeSocks"),
587 VAR("NodeFamily", LINELIST, NodeFamilies, NULL),
588 V_IMMUTABLE(NoExec, BOOL, "0"),
589 V(NumCPUs, POSINT, "0"),
590 V(NumDirectoryGuards, POSINT, "0"),
591 V(NumEntryGuards, POSINT, "0"),
592 V(NumPrimaryGuards, POSINT, "0"),
593 V(OfflineMasterKey, BOOL, "0"),
594 OBSOLETE("ORListenAddress"),
595 VPORT(ORPort),
596 V(OutboundBindAddress, LINELIST, NULL),
597 V(OutboundBindAddressOR, LINELIST, NULL),
598 V(OutboundBindAddressExit, LINELIST, NULL),
599 V(OutboundBindAddressPT, LINELIST, NULL),
600
601 OBSOLETE("PathBiasDisableRate"),
602 V(PathBiasCircThreshold, INT, "-1"),
603 V(PathBiasNoticeRate, DOUBLE, "-1"),
604 V(PathBiasWarnRate, DOUBLE, "-1"),
605 V(PathBiasExtremeRate, DOUBLE, "-1"),
606 V(PathBiasScaleThreshold, INT, "-1"),
607 OBSOLETE("PathBiasScaleFactor"),
608 OBSOLETE("PathBiasMultFactor"),
609 V(PathBiasDropGuards, AUTOBOOL, "0"),
610 OBSOLETE("PathBiasUseCloseCounts"),
611
612 V(PathBiasUseThreshold, INT, "-1"),
613 V(PathBiasNoticeUseRate, DOUBLE, "-1"),
614 V(PathBiasExtremeUseRate, DOUBLE, "-1"),
615 V(PathBiasScaleUseThreshold, INT, "-1"),
616
617 V(PathsNeededToBuildCircuits, DOUBLE, "-1"),
618 V(PerConnBWBurst, MEMUNIT, "0"),
619 V(PerConnBWRate, MEMUNIT, "0"),
620 V_IMMUTABLE(PidFile, FILENAME, NULL),
621 V_IMMUTABLE(TestingTorNetwork, BOOL, "0"),
622
623 V(TestingLinkCertLifetime, INTERVAL, "2 days"),
624 V(TestingAuthKeyLifetime, INTERVAL, "2 days"),
625 V(TestingLinkKeySlop, INTERVAL, "3 hours"),
626 V(TestingAuthKeySlop, INTERVAL, "3 hours"),
627 V(TestingSigningKeySlop, INTERVAL, "1 day"),
628
629 OBSOLETE("OptimisticData"),
630 OBSOLETE("PortForwarding"),
631 OBSOLETE("PortForwardingHelper"),
632 OBSOLETE("PreferTunneledDirConns"),
633 V(ProtocolWarnings, BOOL, "0"),
634 V(PublishServerDescriptor, CSV, "1"),
635 V(PublishHidServDescriptors, BOOL, "1"),
636 V(ReachableAddresses, LINELIST, NULL),
637 V(ReachableDirAddresses, LINELIST, NULL),
638 V(ReachableORAddresses, LINELIST, NULL),
639 OBSOLETE("RecommendedPackages"),
640 V(ReducedConnectionPadding, BOOL, "0"),
641 V(ConnectionPadding, AUTOBOOL, "auto"),
642 V(RefuseUnknownExits, AUTOBOOL, "auto"),
643 V(CircuitPadding, BOOL, "1"),
644 V(ReconfigDropsBridgeDescs, BOOL, "0"),
645 V(ReducedCircuitPadding, BOOL, "0"),
646 V(RejectPlaintextPorts, CSV, ""),
647 V(RelayBandwidthBurst, MEMUNIT, "0"),
648 V(RelayBandwidthRate, MEMUNIT, "0"),
649 V(RephistTrackTime, INTERVAL, "24 hours"),
650 V_IMMUTABLE(RunAsDaemon, BOOL, "0"),
651 V(ReducedExitPolicy, BOOL, "0"),
652 V(ReevaluateExitPolicy, BOOL, "0"),
653 OBSOLETE("RunTesting"), // currently unused
654 V_IMMUTABLE(Sandbox, BOOL, "0"),
655 V(SafeLogging, STRING, "1"),
656 V(SafeSocks, BOOL, "0"),
657 V(ServerDNSAllowBrokenConfig, BOOL, "1"),
658 V(ServerDNSAllowNonRFC953Hostnames, BOOL,"0"),
659 V(ServerDNSDetectHijacking, BOOL, "1"),
660 V(ServerDNSRandomizeCase, BOOL, "1"),
661 V(ServerDNSResolvConfFile, FILENAME, NULL),
662 V(ServerDNSSearchDomains, BOOL, "0"),
663 V(ServerDNSTestAddresses, CSV,
664 "www.google.com,www.mit.edu,www.yahoo.com,www.slashdot.org"),
665 OBSOLETE("SchedulerLowWaterMark__"),
666 OBSOLETE("SchedulerHighWaterMark__"),
667 OBSOLETE("SchedulerMaxFlushCells__"),
668 V(KISTSchedRunInterval, MSEC_INTERVAL, "0 msec"),
669 V(KISTSockBufSizeFactor, DOUBLE, "1.0"),
670 V(Schedulers, CSV, "KIST,KISTLite,Vanilla"),
671 V(ShutdownWaitLength, INTERVAL, "30 seconds"),
672 OBSOLETE("SocksListenAddress"),
673 V(SocksPolicy, LINELIST, NULL),
674 VPORT(SocksPort),
675 V(SocksTimeout, INTERVAL, "2 minutes"),
676 V(SSLKeyLifetime, INTERVAL, "0"),
677 OBSOLETE("StrictEntryNodes"),
678 OBSOLETE("StrictExitNodes"),
679 V(StrictNodes, BOOL, "0"),
680 OBSOLETE("Support022HiddenServices"),
681 V(TestSocks, BOOL, "0"),
682 V_IMMUTABLE(TokenBucketRefillInterval, MSEC_INTERVAL, "100 msec"),
683 OBSOLETE("Tor2webMode"),
684 OBSOLETE("Tor2webRendezvousPoints"),
685 OBSOLETE("TLSECGroup"),
686 V(TrackHostExits, CSV, NULL),
687 V(TrackHostExitsExpire, INTERVAL, "30 minutes"),
688 OBSOLETE("TransListenAddress"),
689 VPORT(TransPort),
690 V(TransProxyType, STRING, "default"),
691 OBSOLETE("TunnelDirConns"),
692 V(UpdateBridgesFromAuthority, BOOL, "0"),
693 V(UseBridges, BOOL, "0"),
694 VAR("UseEntryGuards", BOOL, UseEntryGuards_option, "1"),
695 OBSOLETE("UseEntryGuardsAsDirGuards"),
696 V(UseGuardFraction, AUTOBOOL, "auto"),
697 V(VanguardsLiteEnabled, AUTOBOOL, "auto"),
698 V(UseMicrodescriptors, AUTOBOOL, "auto"),
699 OBSOLETE("UseNTorHandshake"),
700 VAR("__AlwaysCongestionControl", BOOL, AlwaysCongestionControl, "0"),
701 VAR("__SbwsExit", BOOL, SbwsExit, "0"),
702 V_IMMUTABLE(User, STRING, NULL),
703 OBSOLETE("UserspaceIOCPBuffers"),
704 OBSOLETE("V1AuthoritativeDirectory"),
705 OBSOLETE("V2AuthoritativeDirectory"),
706 VAR("V3AuthoritativeDirectory",BOOL, V3AuthoritativeDir, "0"),
707 V(TestingV3AuthInitialVotingInterval, INTERVAL, "30 minutes"),
708 V(TestingV3AuthInitialVoteDelay, INTERVAL, "5 minutes"),
709 V(TestingV3AuthInitialDistDelay, INTERVAL, "5 minutes"),
710 V(TestingV3AuthVotingStartOffset, INTERVAL, "0"),
711 V(V3AuthVotingInterval, INTERVAL, "1 hour"),
712 V(V3AuthVoteDelay, INTERVAL, "5 minutes"),
713 V(V3AuthDistDelay, INTERVAL, "5 minutes"),
714 V(V3AuthNIntervalsValid, POSINT, "3"),
715 V(V3AuthUseLegacyKey, BOOL, "0"),
716 V(V3BandwidthsFile, FILENAME, NULL),
717 V(GuardfractionFile, FILENAME, NULL),
718 OBSOLETE("VoteOnHidServDirectoriesV2"),
719 V(VirtualAddrNetworkIPv4, STRING, "127.192.0.0/10"),
720 V(VirtualAddrNetworkIPv6, STRING, "[FE80::]/10"),
721 V(WarnPlaintextPorts, CSV, "23,109,110,143"),
722 OBSOLETE("UseFilteringSSLBufferevents"),
723 OBSOLETE("__UseFilteringSSLBufferevents"),
724 VAR_NODUMP("__ReloadTorrcOnSIGHUP", BOOL, ReloadTorrcOnSIGHUP, "1"),
725 VAR_NODUMP("__AllDirActionsPrivate", BOOL, AllDirActionsPrivate, "0"),
726 VAR_NODUMP("__DisablePredictedCircuits",BOOL,DisablePredictedCircuits, "0"),
727 VAR_NODUMP_IMMUTABLE("__DisableSignalHandlers", BOOL,
728 DisableSignalHandlers, "0"),
729 VAR_NODUMP("__LeaveStreamsUnattached",BOOL, LeaveStreamsUnattached, "0"),
730 VAR_NODUMP("__HashedControlSessionPassword", LINELIST,
731 HashedControlSessionPassword,
732 NULL),
733 VAR_NODUMP("__OwningControllerProcess",STRING,
734 OwningControllerProcess, NULL),
735 VAR_NODUMP_IMMUTABLE("__OwningControllerFD", UINT64, OwningControllerFD,
737 V(TestingServerDownloadInitialDelay, CSV_INTERVAL, "0"),
738 V(TestingClientDownloadInitialDelay, CSV_INTERVAL, "0"),
739 V(TestingServerConsensusDownloadInitialDelay, CSV_INTERVAL, "0"),
740 V(TestingClientConsensusDownloadInitialDelay, CSV_INTERVAL, "0"),
741 /* With the ClientBootstrapConsensus*Download* below:
742 * Clients with only authorities will try:
743 * - at least 3 authorities over 10 seconds, then exponentially backoff,
744 * with the next attempt 3-21 seconds later,
745 * Clients with authorities and fallbacks will try:
746 * - at least 2 authorities and 4 fallbacks over 21 seconds, then
747 * exponentially backoff, with the next attempts 4-33 seconds later,
748 * Clients will also retry when an application request arrives.
749 * After a number of failed requests, clients retry every 3 days + 1 hour.
750 *
751 * Clients used to try 2 authorities over 10 seconds, then wait for
752 * 60 minutes or an application request.
753 *
754 * When clients have authorities and fallbacks available, they use these
755 * schedules: (we stagger the times to avoid thundering herds) */
756 V(ClientBootstrapConsensusAuthorityDownloadInitialDelay, CSV_INTERVAL, "6"),
757 V(ClientBootstrapConsensusFallbackDownloadInitialDelay, CSV_INTERVAL, "0"),
758 /* When clients only have authorities available, they use this schedule: */
759 V(ClientBootstrapConsensusAuthorityOnlyDownloadInitialDelay, CSV_INTERVAL,
760 "0"),
761 /* We don't want to overwhelm slow networks (or mirrors whose replies are
762 * blocked), but we also don't want to fail if only some mirrors are
763 * blackholed. Clients will try 3 directories simultaneously.
764 * (Relays never use simultaneous connections.) */
765 V(ClientBootstrapConsensusMaxInProgressTries, POSINT, "3"),
766 /* When a client has any running bridges, check each bridge occasionally,
767 * whether or not that bridge is actually up. */
768 V(TestingBridgeDownloadInitialDelay, CSV_INTERVAL,"10800"),
769 /* When a client is just starting, or has no running bridges, check each
770 * bridge a few times quickly, and then try again later. These schedules
771 * are much longer than the other schedules, because we try each and every
772 * configured bridge with this schedule. */
773 V(TestingBridgeBootstrapDownloadInitialDelay, CSV_INTERVAL, "0"),
774 V(TestingClientMaxIntervalWithoutRequest, INTERVAL, "10 minutes"),
775 V(TestingDirConnectionMaxStall, INTERVAL, "5 minutes"),
776 OBSOLETE("TestingConsensusMaxDownloadTries"),
777 OBSOLETE("ClientBootstrapConsensusMaxDownloadTries"),
778 OBSOLETE("ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries"),
779 OBSOLETE("TestingDescriptorMaxDownloadTries"),
780 OBSOLETE("TestingMicrodescMaxDownloadTries"),
781 OBSOLETE("TestingCertMaxDownloadTries"),
782 VAR_INVIS("___UsingTestNetworkDefaults", BOOL, UsingTestNetworkDefaults_,
783 "0"),
784
786};
787
788/** List of default directory authorities */
789static const char *default_authorities[] = {
790#ifndef COCCI
791#include "auth_dirs.inc"
792#endif
793 NULL
794};
795
796/** List of fallback directory authorities. The list is generated by opt-in of
797 * relays that meet certain stability criteria.
798 */
799static const char *default_fallbacks[] = {
800#ifndef COCCI
801#include "fallback_dirs.inc"
802#endif
803 NULL
804};
805
806/** Override default values with these if the user sets the TestingTorNetwork
807 * option. */
808static const struct {
809 const char *k;
810 const char *v;
812#ifndef COCCI
813#include "testnet.inc"
814#endif
815 { NULL, NULL }
817
818#undef VAR
819#undef V
820#undef OBSOLETE
821
822static const config_deprecation_t option_deprecation_notes_[] = {
823 /* Deprecated since 0.3.2.0-alpha. */
824 { "HTTPProxy", "It only applies to direct unencrypted HTTP connections "
825 "to your directory server, which your Tor probably wasn't using." },
826 { "HTTPProxyAuthenticator", "HTTPProxy is deprecated in favor of HTTPSProxy "
827 "which should be used with HTTPSProxyAuthenticator." },
828 /* End of options deprecated since 0.3.2.1-alpha */
829
830 /* Options deprecated since 0.3.2.2-alpha */
831 { "ReachableDirAddresses", "It has no effect on relays, and has had no "
832 "effect on clients since 0.2.8." },
833 { "ClientPreferIPv6DirPort", "It has no effect on relays, and has had no "
834 "effect on clients since 0.2.8." },
835 /* End of options deprecated since 0.3.2.2-alpha. */
836
837 /* Options deprecated since 0.4.3.1-alpha. */
838 { "ClientAutoIPv6ORPort", "This option is unreliable if a connection isn't "
839 "reliably dual-stack."},
840 /* End of options deprecated since 0.4.3.1-alpha. */
841
842 { NULL, NULL }
843};
844
845#ifdef _WIN32
846static char *get_windows_conf_root(void);
847#endif
848
849static int options_check_transition_cb(const void *old,
850 const void *new,
851 char **msg);
852static int validate_data_directories(or_options_t *options);
853static int write_configuration_file(const char *fname,
854 const or_options_t *options);
855
856static void init_libevent(const or_options_t *options);
857static int opt_streq(const char *s1, const char *s2);
858static int parse_outbound_addresses(or_options_t *options, int validate_only,
859 char **msg);
860static void config_maybe_load_geoip_files_(const or_options_t *options,
861 const or_options_t *old_options);
862static int options_validate_cb(const void *old_options, void *options,
863 char **msg);
865static void set_protocol_warning_severity_level(int warning_severity);
866static void options_clear_cb(const config_mgr_t *mgr, void *opts);
867static setopt_err_t options_validate_and_set(const or_options_t *old_options,
868 or_options_t *new_options,
869 char **msg_out);
872 struct listener_transaction_t *xn);
873
874/** Magic value for or_options_t. */
875#define OR_OPTIONS_MAGIC 9090909
876
877/** Configuration format for or_options_t. */
879 .size = sizeof(or_options_t),
880 .magic = {
881 "or_options_t",
883 offsetof(or_options_t, magic_),
884 },
885 .abbrevs = option_abbrevs_,
886 .deprecations = option_deprecation_notes_,
887 .vars = option_vars_,
888 .legacy_validate_fn = options_validate_cb,
889 .check_transition_fn = options_check_transition_cb,
890 .clear_fn = options_clear_cb,
891 .has_config_suite = true,
892 .config_suite_offset = offsetof(or_options_t, subconfigs_),
893};
894
895/*
896 * Functions to read and write the global options pointer.
897 */
898
899/** Command-line and config-file options. */
901/** The fallback options_t object; this is where we look for options not
902 * in torrc before we fall back to Tor's defaults. */
904/** Name of most recently read torrc file. */
905static char *torrc_fname = NULL;
906/** Name of the most recently read torrc-defaults file.*/
907static char *torrc_defaults_fname = NULL;
908/** Result of parsing the command line. */
910/** List of port_cfg_t for all configured ports. */
912/** True iff we're currently validating options, and any calls to
913 * get_options() are likely to be bugs. */
914static int in_option_validation = 0;
915/** True iff we have run options_act_once_on_startup() */
916static bool have_set_startup_options = false;
917
918/* A global configuration manager to handle all configuration objects. */
919static config_mgr_t *options_mgr = NULL;
920
921/** Return the global configuration manager object for torrc options. */
922STATIC const config_mgr_t *
924{
925 if (PREDICT_UNLIKELY(options_mgr == NULL)) {
926 options_mgr = config_mgr_new(&options_format);
927 int rv = subsystems_register_options_formats(options_mgr);
928 tor_assert(rv == 0);
929 config_mgr_freeze(options_mgr);
930 }
931 return options_mgr;
932}
933
934#define CHECK_OPTIONS_MAGIC(opt) STMT_BEGIN \
935 config_check_toplevel_magic(get_options_mgr(), (opt)); \
936 STMT_END
937
938/** Returns the currently configured options. */
941{
943 tor_assert_nonfatal(! in_option_validation);
944 return global_options;
945}
946
947/** Returns the currently configured options */
948MOCK_IMPL(const or_options_t *,
950{
951 return get_options_mutable();
952}
953
954/**
955 * True iff we have noticed that this is a testing tor network, and we
956 * should use the corresponding defaults.
957 **/
958static bool testing_network_configured = false;
959
960/** Return a set of lines for any default options that we want to override
961 * from those set in our config_var_t values. */
962static config_line_t *
964{
965 int i;
966 config_line_t *result = NULL, **next = &result;
967
969 for (i = 0; testing_tor_network_defaults[i].k; ++i) {
973 next = &(*next)->next;
974 }
975 }
976
977 return result;
978}
979
980/** Change the current global options to contain <b>new_val</b> instead of
981 * their current value; take action based on the new value; free the old value
982 * as necessary. Returns 0 on success, -1 on failure.
983 */
984int
985set_options(or_options_t *new_val, char **msg)
986{
987 or_options_t *old_options = global_options;
988 global_options = new_val;
989 /* Note that we pass the *old* options below, for comparison. It
990 * pulls the new options directly out of global_options. */
991 if (options_act_reversible(old_options, msg)<0) {
992 tor_assert(*msg);
993 global_options = old_options;
994 return -1;
995 }
996 if (subsystems_set_options(get_options_mgr(), new_val) < 0 ||
997 options_act(old_options) < 0) { /* acting on the options failed. die. */
999 log_err(LD_BUG,
1000 "Acting on config options left us in a broken state. Dying.");
1002 }
1003 global_options = old_options;
1004 return -1;
1005 }
1006 /* Issues a CONF_CHANGED event to notify controller of the change. If Tor is
1007 * just starting up then the old_options will be undefined. */
1008 if (old_options && old_options != global_options) {
1009 config_line_t *changes =
1010 config_get_changes(get_options_mgr(), old_options, new_val);
1012 connection_reapply_exit_policy(changes);
1013 config_free_lines(changes);
1014 }
1015
1016 if (old_options != global_options) {
1017 or_options_free(old_options);
1018 /* If we are here it means we've successfully applied the new options and
1019 * that the global options have been changed to the new values. We'll
1020 * check if we need to remove or add periodic events. */
1021 periodic_events_on_new_options(global_options);
1022 }
1023
1024 return 0;
1025}
1026
1027/** Release additional memory allocated in options
1028 */
1029static void
1030options_clear_cb(const config_mgr_t *mgr, void *opts)
1031{
1032 (void)mgr;
1033 CHECK_OPTIONS_MAGIC(opts);
1034 or_options_t *options = opts;
1035
1036 routerset_free(options->ExcludeExitNodesUnion_);
1037 if (options->NodeFamilySets) {
1038 SMARTLIST_FOREACH(options->NodeFamilySets, routerset_t *,
1039 rs, routerset_free(rs));
1040 smartlist_free(options->NodeFamilySets);
1041 }
1042 if (options->SchedulerTypes_) {
1043 SMARTLIST_FOREACH(options->SchedulerTypes_, int *, i, tor_free(i));
1044 smartlist_free(options->SchedulerTypes_);
1045 }
1046 if (options->FilesOpenedByIncludes) {
1047 SMARTLIST_FOREACH(options->FilesOpenedByIncludes, char *, f, tor_free(f));
1048 smartlist_free(options->FilesOpenedByIncludes);
1049 }
1050 tor_free(options->DataDirectory);
1051 tor_free(options->CacheDirectory);
1052 tor_free(options->FamilyKeyDirectory);
1053 tor_free(options->KeyDirectory);
1055 tor_free(options->command_arg);
1056 tor_free(options->master_key_fname);
1057 config_free_lines(options->MyFamily);
1058 if (options->FamilyIds) {
1061 smartlist_free(options->FamilyIds);
1062 }
1063}
1064
1065/** Release all memory allocated in options
1066 */
1067STATIC void
1069{
1070 config_free(get_options_mgr(), options);
1071}
1072
1073/** Release all memory and resources held by global configuration structures.
1074 */
1075void
1077{
1078 or_options_free(global_options);
1079 global_options = NULL;
1080 or_options_free(global_default_options);
1082
1083 parsed_cmdline_free(global_cmdline);
1084
1085 if (configured_ports) {
1087 port_cfg_t *, p, port_cfg_free(p));
1088 smartlist_free(configured_ports);
1089 configured_ports = NULL;
1090 }
1091
1094
1096
1098
1099 config_mgr_free(options_mgr);
1100}
1101
1102/** Make <b>address</b> -- a piece of information related to our operation as
1103 * a client -- safe to log according to the settings in options->SafeLogging,
1104 * and return it.
1105 *
1106 * (We return "[scrubbed]" if SafeLogging is "1", and address otherwise.)
1107 */
1108const char *
1109safe_str_client_opts(const or_options_t *options, const char *address)
1110{
1111 if (!address)
1112 return "[null]";
1113 if (!options) {
1114 options = get_options();
1115 }
1116
1117 if (options->SafeLogging_ == SAFELOG_SCRUB_ALL)
1118 return "[scrubbed]";
1119 else
1120 return address;
1121}
1122
1123/** Make <b>address</b> -- a piece of information of unspecified sensitivity
1124 * -- safe to log according to the settings in options->SafeLogging, and
1125 * return it.
1126 *
1127 * (We return "[scrubbed]" if SafeLogging is anything besides "0", and address
1128 * otherwise.)
1129 */
1130const char *
1131safe_str_opts(const or_options_t *options, const char *address)
1132{
1133 if (!address)
1134 return "[null]";
1135 if (!options) {
1136 options = get_options();
1137 }
1138
1139 if (options->SafeLogging_ != SAFELOG_SCRUB_NONE)
1140 return "[scrubbed]";
1141 else
1142 return address;
1143}
1144
1145/** Equivalent to escaped(safe_str_client(address)). See reentrancy note on
1146 * escaped(): don't use this outside the main thread, or twice in the same
1147 * log statement. */
1148const char *
1149escaped_safe_str_client(const char *address)
1150{
1151 if (get_options()->SafeLogging_ == SAFELOG_SCRUB_ALL)
1152 return "[scrubbed]";
1153 else
1154 return escaped(address);
1155}
1156
1157/** Equivalent to escaped(safe_str(address)). See reentrancy note on
1158 * escaped(): don't use this outside the main thread, or twice in the same
1159 * log statement. */
1160const char *
1161escaped_safe_str(const char *address)
1162{
1163 if (get_options()->SafeLogging_ != SAFELOG_SCRUB_NONE)
1164 return "[scrubbed]";
1165 else
1166 return escaped(address);
1167}
1168
1169/**
1170 * The severity level that should be used for warnings of severity
1171 * LOG_PROTOCOL_WARN.
1172 *
1173 * We keep this outside the options, and we use an atomic_counter_t, in case
1174 * one thread needs to use LOG_PROTOCOL_WARN while an option transition is
1175 * happening in the main thread.
1176 */
1178
1179/** Return the severity level that should be used for warnings of severity
1180 * LOG_PROTOCOL_WARN. */
1181int
1186
1187/** Set the protocol warning severity level to <b>severity</b>. */
1188static void
1190{
1192 warning_severity);
1193}
1194
1195/**
1196 * Initialize the log warning severity level for protocol warnings. Call
1197 * only once at startup.
1198 */
1199void
1205
1206/**
1207 * Tear down protocol_warning_severity_level.
1208 */
1209static void
1211{
1212 /* Destroying a locked mutex is undefined behaviour. This mutex may be
1213 * locked, because multiple threads can access it. But we need to destroy
1214 * it, otherwise re-initialisation will trigger undefined behaviour.
1215 * See #31735 for details. */
1217}
1218
1219/** Add the default directory authorities directly into the trusted dir list,
1220 * but only add them insofar as they share bits with <b>type</b>.
1221 * Each authority's bits are restricted to the bits shared with <b>type</b>.
1222 * If <b>type</b> is ALL_DIRINFO or NO_DIRINFO (zero), add all authorities. */
1223STATIC void
1225{
1226 int i;
1227 for (i=0; default_authorities[i]; i++) {
1228 if (parse_dir_authority_line(default_authorities[i], type, 0)<0) {
1229 log_err(LD_BUG, "Couldn't parse internal DirAuthority line %s",
1231 }
1232 }
1233}
1234
1235/** Add the default fallback directory servers into the fallback directory
1236 * server list. */
1237MOCK_IMPL(void,
1239{
1240 int i;
1241 for (i=0; default_fallbacks[i]; i++) {
1243 log_err(LD_BUG, "Couldn't parse internal FallbackDir line %s",
1245 }
1246 }
1247}
1248
1249/** Look at all the config options for using alternate directory
1250 * authorities, and make sure none of them are broken. Also, warn the
1251 * user if we changed any dangerous ones.
1252 */
1253static int
1255 const or_options_t *old_options)
1256{
1257 config_line_t *cl;
1258
1259 if (options->DirAuthorities &&
1260 (options->AlternateDirAuthority || options->AlternateBridgeAuthority)) {
1261 log_warn(LD_CONFIG,
1262 "You cannot set both DirAuthority and Alternate*Authority.");
1263 return -1;
1264 }
1265
1266 /* do we want to complain to the user about being partitionable? */
1267 if ((options->DirAuthorities &&
1268 (!old_options ||
1270 old_options->DirAuthorities))) ||
1271 (options->AlternateDirAuthority &&
1272 (!old_options ||
1274 old_options->AlternateDirAuthority)))) {
1275 log_warn(LD_CONFIG,
1276 "You have used DirAuthority or AlternateDirAuthority to "
1277 "specify alternate directory authorities in "
1278 "your configuration. This is potentially dangerous: it can "
1279 "make you look different from all other Tor users, and hurt "
1280 "your anonymity. Even if you've specified the same "
1281 "authorities as Tor uses by default, the defaults could "
1282 "change in the future. Be sure you know what you're doing.");
1283 }
1284
1285 /* Now go through the four ways you can configure an alternate
1286 * set of directory authorities, and make sure none are broken. */
1287 for (cl = options->DirAuthorities; cl; cl = cl->next)
1288 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
1289 return -1;
1290 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
1291 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
1292 return -1;
1293 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
1294 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
1295 return -1;
1296 for (cl = options->FallbackDir; cl; cl = cl->next)
1297 if (parse_dir_fallback_line(cl->value, 1)<0)
1298 return -1;
1299 return 0;
1300}
1301
1302/** Look at all the config options and assign new dir authorities
1303 * as appropriate.
1304 */
1305int
1307 const or_options_t *old_options)
1308{
1309 config_line_t *cl;
1310 int need_to_update =
1311 !smartlist_len(router_get_trusted_dir_servers()) ||
1312 !smartlist_len(router_get_fallback_dir_servers()) || !old_options ||
1313 !config_lines_eq(options->DirAuthorities, old_options->DirAuthorities) ||
1314 !config_lines_eq(options->FallbackDir, old_options->FallbackDir) ||
1315 (options->UseDefaultFallbackDirs != old_options->UseDefaultFallbackDirs) ||
1317 old_options->AlternateBridgeAuthority) ||
1319 old_options->AlternateDirAuthority);
1320
1321 if (!need_to_update)
1322 return 0; /* all done */
1323
1324 /* "You cannot set both DirAuthority and Alternate*Authority."
1325 * Checking that this restriction holds allows us to simplify
1326 * the unit tests. */
1327 tor_assert(!(options->DirAuthorities &&
1328 (options->AlternateDirAuthority
1329 || options->AlternateBridgeAuthority)));
1330
1331 /* Start from a clean slate. */
1333
1334 if (!options->DirAuthorities) {
1335 /* then we may want some of the defaults */
1336 dirinfo_type_t type = NO_DIRINFO;
1337 if (!options->AlternateBridgeAuthority) {
1338 type |= BRIDGE_DIRINFO;
1339 }
1340 if (!options->AlternateDirAuthority) {
1342 /* Only add the default fallback directories when the DirAuthorities,
1343 * AlternateDirAuthority, and FallbackDir directory config options
1344 * are set to their defaults, and when UseDefaultFallbackDirs is 1. */
1345 if (!options->FallbackDir && options->UseDefaultFallbackDirs) {
1347 }
1348 }
1349 /* if type == NO_DIRINFO, we don't want to add any of the
1350 * default authorities, because we've replaced them all */
1351 if (type != NO_DIRINFO)
1353 }
1354
1355 for (cl = options->DirAuthorities; cl; cl = cl->next)
1356 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
1357 return -1;
1358 for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
1359 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
1360 return -1;
1361 for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
1362 if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
1363 return -1;
1364 for (cl = options->FallbackDir; cl; cl = cl->next)
1365 if (parse_dir_fallback_line(cl->value, 0)<0)
1366 return -1;
1367 return 0;
1368}
1369
1370/**
1371 * Make sure that <b>directory</b> exists, with appropriate ownership and
1372 * permissions (as modified by <b>group_readable</b>). If <b>create</b>,
1373 * create the directory if it is missing. Return 0 on success.
1374 * On failure, return -1 and set *<b>msg_out</b>.
1375 */
1376static int
1378 const char *directory,
1379 int group_readable,
1380 const char *owner,
1381 char **msg_out)
1382{
1383 cpd_check_t cpd_opts = create ? CPD_CREATE : CPD_CHECK;
1384 if (group_readable)
1385 cpd_opts |= CPD_GROUP_READ;
1386 if (check_private_dir(directory,
1387 cpd_opts,
1388 owner) < 0) {
1389 tor_asprintf(msg_out,
1390 "Couldn't %s private data directory \"%s\"",
1391 create ? "create" : "access",
1392 directory);
1393 return -1;
1394 }
1395
1396#ifndef _WIN32
1397 if (group_readable) {
1398 /* Only new dirs created get new opts, also enforce group read. */
1399 if (chmod(directory, 0750)) {
1400 log_warn(LD_FS,"Unable to make %s group-readable: %s",
1401 directory, strerror(errno));
1402 }
1403 }
1404#endif /* !defined(_WIN32) */
1405
1406 return 0;
1407}
1408
1409/**
1410 * Ensure that our keys directory exists, with appropriate permissions.
1411 * Return 0 on success, -1 on failure.
1412 */
1413int
1415{
1416 /* Make sure DataDirectory exists, and is private. */
1417 cpd_check_t cpd_opts = CPD_CREATE;
1418 if (options->DataDirectoryGroupReadable)
1419 cpd_opts |= CPD_GROUP_READ;
1420 if (check_private_dir(options->DataDirectory, cpd_opts, options->User)) {
1421 log_err(LD_OR, "Can't create/check datadirectory %s",
1422 options->DataDirectory);
1423 return -1;
1424 }
1425
1426 /* Check the key directory. */
1427 if (check_private_dir(options->KeyDirectory, CPD_CREATE, options->User)) {
1428 return -1;
1429 }
1430 return 0;
1431}
1432
1433/* Helps determine flags to pass to switch_id. */
1434static int have_low_ports = -1;
1435
1436/** Take case of initial startup tasks that must occur before any of the
1437 * transactional option-related changes are allowed. */
1438static int
1440{
1442 return 0;
1443
1444 const or_options_t *options = get_options();
1445 const bool running_tor = options->command == CMD_RUN_TOR;
1446
1447 if (!running_tor)
1448 return 0;
1449
1450 /* Daemonize _first_, since we only want to open most of this stuff in
1451 * the subprocess. Libevent bases can't be reliably inherited across
1452 * processes. */
1453 if (options->RunAsDaemon) {
1456 /* No need to roll back, since you can't change the value. */
1457 if (start_daemon())
1459 }
1460
1461#ifdef HAVE_SYSTEMD
1462 /* Our PID may have changed, inform supervisor */
1463 sd_notifyf(0, "MAINPID=%ld\n", (long int)getpid());
1464#endif
1465
1466 /* Set up libevent. (We need to do this before we can register the
1467 * listeners as listeners.) */
1468 init_libevent(options);
1469
1470 /* This has to come up after libevent is initialized. */
1471 control_initialize_event_queue();
1472
1473 /*
1474 * Initialize the scheduler - this has to come after
1475 * options_init_from_torrc() sets up libevent - why yes, that seems
1476 * completely sensible to hide the libevent setup in the option parsing
1477 * code! It also needs to happen before init_keys(), so it needs to
1478 * happen here too. How yucky. */
1479 scheduler_init();
1480
1481 /* Attempt to lock all current and future memory with mlockall() only once.
1482 * This must happen before setuid. */
1483 if (options->DisableAllSwap) {
1484 if (tor_mlockall() == -1) {
1485 *msg_out = tor_strdup("DisableAllSwap failure. Do you have proper "
1486 "permissions?");
1487 return -1;
1488 }
1489 }
1490
1492 return 0;
1493}
1494
1495/**
1496 * Change our user ID if we're configured to do so.
1497 **/
1498static int
1499options_switch_id(char **msg_out)
1500{
1501 const or_options_t *options = get_options();
1502
1503 /* Setuid/setgid as appropriate */
1504 if (options->User) {
1505 tor_assert(have_low_ports != -1);
1506 unsigned switch_id_flags = 0;
1507 if (options->KeepBindCapabilities == 1) {
1508 switch_id_flags |= SWITCH_ID_KEEP_BINDLOW;
1509 switch_id_flags |= SWITCH_ID_WARN_IF_NO_CAPS;
1510 }
1511 if (options->KeepBindCapabilities == -1 && have_low_ports) {
1512 switch_id_flags |= SWITCH_ID_KEEP_BINDLOW;
1513 }
1514 if (switch_id(options->User, switch_id_flags) != 0) {
1515 /* No need to roll back, since you can't change the value. */
1516 *msg_out = tor_strdup("Problem with User value. See logs for details.");
1517 return -1;
1518 }
1519 }
1520
1521 return 0;
1522}
1523
1524/**
1525 * Helper. Given a data directory (<b>datadir</b>) and another directory
1526 * (<b>subdir</b>) with respective group-writable permissions
1527 * <b>datadir_gr</b> and <b>subdir_gr</b>, compute whether the subdir should
1528 * be group-writeable.
1529 **/
1530static int
1532 const char *subdir,
1533 int datadir_gr,
1534 int subdir_gr)
1535{
1536 if (subdir_gr != -1) {
1537 /* The user specified a default for "subdir", so we always obey it. */
1538 return subdir_gr;
1539 }
1540
1541 /* The user left the subdir_gr option on "auto." */
1542 if (0 == strcmp(subdir, datadir)) {
1543 /* The directories are the same, so we use the group-readable flag from
1544 * the datadirectory */
1545 return datadir_gr;
1546 } else {
1547 /* The directories are different, so we default to "not group-readable" */
1548 return 0;
1549 }
1550}
1551
1552/**
1553 * Create our DataDirectory, CacheDirectory, and KeyDirectory, and
1554 * set their permissions correctly.
1555 */
1556STATIC int
1558{
1559 const or_options_t *options = get_options();
1560 const bool running_tor = options->command == CMD_RUN_TOR;
1561
1562 /* Ensure data directory is private; create if possible. */
1563 /* It's okay to do this in "options_act_reversible()" even though it isn't
1564 * actually reversible, since you can't change the DataDirectory while
1565 * Tor is running. */
1566 if (check_and_create_data_directory(running_tor /* create */,
1567 options->DataDirectory,
1569 options->User,
1570 msg_out) < 0) {
1571 return -1;
1572 }
1573
1574 /* We need to handle the group-readable flag for the cache directory and key
1575 * directory specially, since they may be the same as the data directory */
1576 const int key_dir_group_readable = compute_group_readable_flag(
1577 options->DataDirectory,
1578 options->KeyDirectory,
1580 options->KeyDirectoryGroupReadable);
1581
1582 if (check_and_create_data_directory(running_tor /* create */,
1583 options->KeyDirectory,
1584 key_dir_group_readable,
1585 options->User,
1586 msg_out) < 0) {
1587 return -1;
1588 }
1589
1590 const int cache_dir_group_readable = compute_group_readable_flag(
1591 options->DataDirectory,
1592 options->CacheDirectory,
1595
1596 if (check_and_create_data_directory(running_tor /* create */,
1597 options->CacheDirectory,
1598 cache_dir_group_readable,
1599 options->User,
1600 msg_out) < 0) {
1601 return -1;
1602 }
1603
1604 return 0;
1605}
1606
1607/** Structure to represent an incomplete configuration of a set of
1608 * listeners.
1609 *
1610 * This structure is generated by options_start_listener_transaction(), and is
1611 * either committed by options_commit_listener_transaction() or rolled back by
1612 * options_rollback_listener_transaction(). */
1614 bool set_conn_limit; /**< True if we've set the connection limit */
1615 unsigned old_conn_limit; /**< If nonzero, previous connlimit value. */
1616 smartlist_t *new_listeners; /**< List of new listeners that we opened. */
1618
1619/**
1620 * Start configuring our listeners based on the current value of
1621 * get_options().
1622 *
1623 * The value <b>old_options</b> holds either the previous options object,
1624 * or NULL if we're starting for the first time.
1625 *
1626 * On success, return a listener_transaction_t that we can either roll back or
1627 * commit.
1628 *
1629 * On failure return NULL and write a message into a newly allocated string in
1630 * *<b>msg_out</b>.
1631 **/
1634 char **msg_out)
1635{
1636 listener_transaction_t *xn = tor_malloc_zero(sizeof(listener_transaction_t));
1638 or_options_t *options = get_options_mutable();
1639 const bool running_tor = options->command == CMD_RUN_TOR;
1640
1641 if (! running_tor) {
1642 return xn;
1643 }
1644
1645 int n_ports=0;
1646 /* We need to set the connection limit before we can open the listeners. */
1647 if (! sandbox_is_active()) {
1648 if (set_max_file_descriptors((unsigned)options->ConnLimit,
1649 &options->ConnLimit_) < 0) {
1650 *msg_out = tor_strdup("Problem with ConnLimit value. "
1651 "See logs for details.");
1652 goto rollback;
1653 }
1654 xn->set_conn_limit = true;
1655 if (old_options)
1656 xn->old_conn_limit = (unsigned)old_options->ConnLimit;
1657 } else {
1658 tor_assert(old_options);
1659 options->ConnLimit_ = old_options->ConnLimit_;
1660 }
1661
1662 /* Adjust the port configuration so we can launch listeners. */
1663 /* 31851: some ports are relay-only */
1664 if (parse_ports(options, 0, msg_out, &n_ports, NULL)) {
1665 if (!*msg_out)
1666 *msg_out = tor_strdup("Unexpected problem parsing port config");
1667 goto rollback;
1668 }
1669
1670 /* Set the hibernation state appropriately.*/
1671 consider_hibernation(time(NULL));
1672
1673 /* Launch the listeners. (We do this before we setuid, so we can bind to
1674 * ports under 1024.) We don't want to rebind if we're hibernating or
1675 * shutting down. If networking is disabled, this will close all but the
1676 * control listeners, but disable those. */
1677 /* 31851: some listeners are relay-only */
1678 if (!we_are_hibernating()) {
1680 options->DisableNetwork) < 0) {
1681 *msg_out = tor_strdup("Failed to bind one of the listener ports.");
1682 goto rollback;
1683 }
1684 }
1685 if (options->DisableNetwork) {
1686 /* Aggressively close non-controller stuff, NOW */
1687 log_notice(LD_NET, "DisableNetwork is set. Tor will not make or accept "
1688 "non-control network connections. Shutting down all existing "
1689 "connections.");
1691 /* We can't complete circuits until the network is re-enabled. */
1693 }
1694
1695#if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
1696 /* Open /dev/pf before (possibly) dropping privileges. */
1697 if (options->TransPort_set &&
1698 options->TransProxyType_parsed == TPT_DEFAULT) {
1699 if (get_pf_socket() < 0) {
1700 *msg_out = tor_strdup("Unable to open /dev/pf for transparent proxy.");
1701 goto rollback;
1702 }
1703 }
1704#endif /* defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H) */
1705
1706 return xn;
1707
1708 rollback:
1710 return NULL;
1711}
1712
1713/**
1714 * Finish configuring the listeners that started to get configured with
1715 * <b>xn</b>. Frees <b>xn</b>.
1716 **/
1717static void
1719{
1720 tor_assert(xn);
1721 if (xn->set_conn_limit) {
1722 or_options_t *options = get_options_mutable();
1723 /*
1724 * If we adjusted the conn limit, recompute the OOS threshold too
1725 *
1726 * How many possible sockets to keep in reserve? If we have lots of
1727 * possible sockets, keep this below a limit and set ConnLimit_high_thresh
1728 * very close to ConnLimit_, but if ConnLimit_ is low, shrink it in
1729 * proportion.
1730 *
1731 * Somewhat arbitrarily, set socks_in_reserve to 5% of ConnLimit_, but
1732 * cap it at 64.
1733 */
1734 int socks_in_reserve = options->ConnLimit_ / 20;
1735 if (socks_in_reserve > 64) socks_in_reserve = 64;
1736
1737 options->ConnLimit_high_thresh = options->ConnLimit_ - socks_in_reserve;
1738 options->ConnLimit_low_thresh = (options->ConnLimit_ / 4) * 3;
1739 log_info(LD_GENERAL,
1740 "Recomputed OOS thresholds: ConnLimit %d, ConnLimit_ %d, "
1741 "ConnLimit_high_thresh %d, ConnLimit_low_thresh %d",
1742 options->ConnLimit, options->ConnLimit_,
1743 options->ConnLimit_high_thresh,
1744 options->ConnLimit_low_thresh);
1745
1746 /* Give the OOS handler a chance with the new thresholds */
1748 }
1749
1750 smartlist_free(xn->new_listeners);
1751 tor_free(xn);
1752}
1753
1754/**
1755 * Revert the listener configuration changes that that started to get
1756 * configured with <b>xn</b>. Frees <b>xn</b>.
1757 **/
1758static void
1760{
1761 if (! xn)
1762 return;
1763
1764 or_options_t *options = get_options_mutable();
1765
1766 if (xn->set_conn_limit && xn->old_conn_limit)
1768
1770 {
1771 log_notice(LD_NET, "Closing partially-constructed %s",
1772 connection_describe(conn));
1773 connection_close_immediate(conn);
1774 connection_mark_for_close(conn);
1775 });
1776
1777 smartlist_free(xn->new_listeners);
1778 tor_free(xn);
1779}
1780
1781/** Structure to represent an incomplete configuration of a set of logs.
1782 *
1783 * This structure is generated by options_start_log_transaction(), and is
1784 * either committed by options_commit_log_transaction() or rolled back by
1785 * options_rollback_log_transaction(). */
1786typedef struct log_transaction_t {
1787 /** Previous lowest severity of any configured log. */
1789 /** True if we have marked the previous logs to be closed */
1791 /** True if we initialized the new set of logs */
1793 /** True if our safelogging configuration is different from what it was
1794 * previously (or if we are starting for the first time). */
1797
1798/**
1799 * Start configuring our logs based on the current value of get_options().
1800 *
1801 * The value <b>old_options</b> holds either the previous options object,
1802 * or NULL if we're starting for the first time.
1803 *
1804 * On success, return a log_transaction_t that we can either roll back or
1805 * commit.
1806 *
1807 * On failure return NULL and write a message into a newly allocated string in
1808 * *<b>msg_out</b>.
1809 **/
1812 char **msg_out)
1813{
1814 const or_options_t *options = get_options();
1815 const bool running_tor = options->command == CMD_RUN_TOR;
1816
1817 log_transaction_t *xn = tor_malloc_zero(sizeof(log_transaction_t));
1819 xn->safelogging_changed = !old_options ||
1820 old_options->SafeLogging_ != options->SafeLogging_;
1821
1822 if (! running_tor)
1823 goto done;
1824
1825 mark_logs_temp(); /* Close current logs once new logs are open. */
1826 xn->logs_marked = true;
1827 /* Configure the tor_log(s) */
1828 if (options_init_logs(old_options, options, 0)<0) {
1829 *msg_out = tor_strdup("Failed to init Log options. See logs for details.");
1831 xn = NULL;
1832 goto done;
1833 }
1834
1835 xn->logs_initialized = true;
1836
1837 done:
1838 return xn;
1839}
1840
1841/**
1842 * Finish configuring the logs that started to get configured with <b>xn</b>.
1843 * Frees <b>xn</b>.
1844 **/
1845STATIC void
1847{
1848 const or_options_t *options = get_options();
1849 tor_assert(xn);
1850
1851 if (xn->logs_marked) {
1852 log_severity_list_t *severity =
1853 tor_malloc_zero(sizeof(log_severity_list_t));
1858 tor_free(severity);
1860 }
1861
1862 if (xn->logs_initialized) {
1864 }
1865
1866 {
1867 const char *badness = NULL;
1868 int bad_safelog = 0, bad_severity = 0, new_badness = 0;
1869 if (options->SafeLogging_ != SAFELOG_SCRUB_ALL) {
1870 bad_safelog = 1;
1871 if (xn->safelogging_changed)
1872 new_badness = 1;
1873 }
1874 if (get_min_log_level() >= LOG_INFO) {
1875 bad_severity = 1;
1877 new_badness = 1;
1878 }
1879 if (bad_safelog && bad_severity)
1880 badness = "you disabled SafeLogging, and "
1881 "you're logging more than \"notice\"";
1882 else if (bad_safelog)
1883 badness = "you disabled SafeLogging";
1884 else
1885 badness = "you're logging more than \"notice\"";
1886 if (new_badness)
1887 log_warn(LD_GENERAL, "Your log may contain sensitive information - %s. "
1888 "Don't log unless it serves an important reason. "
1889 "Overwrite the log afterwards.", badness);
1890 }
1891
1892 tor_free(xn);
1893}
1894
1895/**
1896 * Revert the log configuration changes that that started to get configured
1897 * with <b>xn</b>. Frees <b>xn</b>.
1898 **/
1899STATIC void
1901{
1902 if (!xn)
1903 return;
1904
1905 if (xn->logs_marked) {
1908 }
1909
1910 tor_free(xn);
1911}
1912
1913/**
1914 * Fetch the active option list, and take actions based on it. All of
1915 * the things we do in this function should survive being done
1916 * repeatedly, OR be done only once when starting Tor. If present,
1917 * <b>old_options</b> contains the previous value of the options.
1918 *
1919 * This function is only truly "reversible" _after_ the first time it
1920 * is run. The first time that it runs, it performs some irreversible
1921 * tasks in the correct sequence between the reversible option changes.
1922 *
1923 * Option changes should only be marked as "reversible" if they cannot
1924 * be validated before switching them, but they can be switched back if
1925 * some other validation fails.
1926 *
1927 * Return 0 if all goes well, return -1 if things went badly.
1928 */
1929MOCK_IMPL(STATIC int,
1930options_act_reversible,(const or_options_t *old_options, char **msg))
1931{
1932 const bool first_time = ! have_set_startup_options;
1933 log_transaction_t *log_transaction = NULL;
1934 listener_transaction_t *listener_transaction = NULL;
1935 int r = -1;
1936
1937 /* The ordering of actions in this function is not free, sadly.
1938 *
1939 * First of all, we _must_ daemonize before we take all kinds of
1940 * initialization actions, since they need to happen in the
1941 * subprocess.
1942 */
1943 if (options_act_once_on_startup(msg) < 0)
1944 goto rollback;
1945
1946 /* Once we've handled most of once-off initialization, we need to
1947 * open our listeners before we switch IDs. (If we open listeners first,
1948 * we might not be able to bind to low ports.)
1949 */
1950 listener_transaction = options_start_listener_transaction(old_options, msg);
1951 if (listener_transaction == NULL)
1952 goto rollback;
1953
1954 if (first_time) {
1955 if (options_switch_id(msg) < 0)
1956 goto rollback;
1957 }
1958
1959 /* On the other hand, we need to touch the file system _after_ we
1960 * switch IDs: otherwise, we'll be making directories and opening files
1961 * with the wrong permissions.
1962 */
1963 if (first_time) {
1964 if (options_create_directories(msg) < 0)
1965 goto rollback;
1966 }
1967
1968 /* Bail out at this point if we're not going to be a client or server:
1969 * we don't run Tor itself. */
1970 log_transaction = options_start_log_transaction(old_options, msg);
1971 if (log_transaction == NULL)
1972 goto rollback;
1973
1974 // Commit!
1975 r = 0;
1976
1977 options_commit_log_transaction(log_transaction);
1978
1979 options_commit_listener_transaction(listener_transaction);
1980
1981 goto done;
1982
1983 rollback:
1984 r = -1;
1985 tor_assert(*msg);
1986
1987 options_rollback_log_transaction(log_transaction);
1988 options_rollback_listener_transaction(listener_transaction);
1989
1990 done:
1991 return r;
1992}
1993
1994/** If we need to have a GEOIP ip-to-country map to run with our configured
1995 * options, return 1 and set *<b>reason_out</b> to a description of why. */
1996int
1997options_need_geoip_info(const or_options_t *options, const char **reason_out)
1998{
1999 int bridge_usage = should_record_bridge_info(options);
2000 int routerset_usage =
2002 routerset_needs_geoip(options->ExitNodes) ||
2008
2009 if (routerset_usage && reason_out) {
2010 *reason_out = "We've been configured to use (or avoid) nodes in certain "
2011 "countries, and we need GEOIP information to figure out which ones they "
2012 "are.";
2013 } else if (bridge_usage && reason_out) {
2014 *reason_out = "We've been configured to see which countries can access "
2015 "us as a bridge, and we need GEOIP information to tell which countries "
2016 "clients are in.";
2017 }
2018 return bridge_usage || routerset_usage;
2019}
2020
2021/* Used in the various options_transition_affects* functions. */
2022#define YES_IF_CHANGED_BOOL(opt) \
2023 if (!CFG_EQ_BOOL(old_options, new_options, opt)) return 1;
2024#define YES_IF_CHANGED_INT(opt) \
2025 if (!CFG_EQ_INT(old_options, new_options, opt)) return 1;
2026#define YES_IF_CHANGED_STRING(opt) \
2027 if (!CFG_EQ_STRING(old_options, new_options, opt)) return 1;
2028#define YES_IF_CHANGED_LINELIST(opt) \
2029 if (!CFG_EQ_LINELIST(old_options, new_options, opt)) return 1;
2030#define YES_IF_CHANGED_SMARTLIST(opt) \
2031 if (!CFG_EQ_SMARTLIST(old_options, new_options, opt)) return 1;
2032#define YES_IF_CHANGED_ROUTERSET(opt) \
2033 if (!CFG_EQ_ROUTERSET(old_options, new_options, opt)) return 1;
2034
2035/**
2036 * Return true if changing the configuration from <b>old</b> to <b>new</b>
2037 * affects the guard subsystem.
2038 */
2039static int
2041 const or_options_t *new_options)
2042{
2043 /* NOTE: Make sure this function stays in sync with
2044 * node_passes_guard_filter */
2045 tor_assert(old_options);
2046 tor_assert(new_options);
2047
2048 YES_IF_CHANGED_BOOL(UseEntryGuards);
2049 YES_IF_CHANGED_BOOL(UseBridges);
2050 YES_IF_CHANGED_BOOL(ClientUseIPv4);
2051 YES_IF_CHANGED_BOOL(ClientUseIPv6);
2052 YES_IF_CHANGED_BOOL(FascistFirewall);
2053 YES_IF_CHANGED_ROUTERSET(ExcludeNodes);
2054 YES_IF_CHANGED_ROUTERSET(EntryNodes);
2055 YES_IF_CHANGED_SMARTLIST(FirewallPorts);
2056 YES_IF_CHANGED_LINELIST(Bridges);
2057 YES_IF_CHANGED_LINELIST(ReachableORAddresses);
2058 YES_IF_CHANGED_LINELIST(ReachableDirAddresses);
2059
2060 return 0;
2061}
2062
2063/** Fetch the active option list, and take actions based on it. All of the
2064 * things we do should survive being done repeatedly. If present,
2065 * <b>old_options</b> contains the previous value of the options.
2066 *
2067 * Return 0 if all goes well, return -1 if it's time to die.
2068 *
2069 * Note: We haven't moved all the "act on new configuration" logic
2070 * the options_act* functions yet. Some is still in do_hup() and other
2071 * places.
2072 */
2073MOCK_IMPL(STATIC int,
2074options_act,(const or_options_t *old_options))
2075{
2076 config_line_t *cl;
2077 or_options_t *options = get_options_mutable();
2078 int running_tor = options->command == CMD_RUN_TOR;
2079 char *msg=NULL;
2080 const int transition_affects_guards =
2081 old_options && options_transition_affects_guards(old_options, options);
2082
2083 if (options->NoExec || options->Sandbox) {
2085 }
2086
2087 /* disable ptrace and later, other basic debugging techniques */
2088 {
2089 /* Remember if we already disabled debugger attachment */
2090 static int disabled_debugger_attach = 0;
2091 /* Remember if we already warned about being configured not to disable
2092 * debugger attachment */
2093 static int warned_debugger_attach = 0;
2094 /* Don't disable debugger attachment when we're running the unit tests. */
2095 if (options->DisableDebuggerAttachment && !disabled_debugger_attach &&
2096 running_tor) {
2097 int ok = tor_disable_debugger_attach();
2098 /* LCOV_EXCL_START the warned_debugger_attach is 0 can't reach inside. */
2099 if (warned_debugger_attach && ok == 1) {
2100 log_notice(LD_CONFIG, "Disabled attaching debuggers for unprivileged "
2101 "users.");
2102 }
2103 /* LCOV_EXCL_STOP */
2104 disabled_debugger_attach = (ok == 1);
2105 } else if (!options->DisableDebuggerAttachment &&
2106 !warned_debugger_attach) {
2107 log_notice(LD_CONFIG, "Not disabling debugger attaching for "
2108 "unprivileged users.");
2109 warned_debugger_attach = 1;
2110 }
2111 }
2112
2113 /* Write control ports to disk as appropriate */
2115
2116 if (running_tor && !have_lockfile()) {
2117 if (try_locking(options, 1) < 0)
2118 return -1;
2119 }
2120
2121 {
2122 int warning_severity = options->ProtocolWarnings ? LOG_WARN : LOG_INFO;
2123 set_protocol_warning_severity_level(warning_severity);
2124 }
2125
2126 if (consider_adding_dir_servers(options, old_options) < 0) {
2127 // XXXX This should get validated earlier, and committed here, to
2128 // XXXX lower opportunities for reaching an error case.
2129 return -1;
2130 }
2131
2132 if (hs_service_non_anonymous_mode_enabled(options)) {
2133 log_warn(LD_GENERAL, "This copy of Tor was compiled or configured to run "
2134 "in a non-anonymous mode. It will provide NO ANONYMITY.");
2135 }
2136
2137 /* 31851: OutboundBindAddressExit is relay-only */
2138 if (parse_outbound_addresses(options, 0, &msg) < 0) {
2139 // LCOV_EXCL_START
2140 log_warn(LD_BUG, "Failed parsing previously validated outbound "
2141 "bind addresses: %s", msg);
2142 tor_free(msg);
2143 return -1;
2144 // LCOV_EXCL_STOP
2145 }
2146
2147 if (options->Bridges) {
2149 for (cl = options->Bridges; cl; cl = cl->next) {
2150 bridge_line_t *bridge_line = parse_bridge_line(cl->value);
2151 if (!bridge_line) {
2152 // LCOV_EXCL_START
2153 log_warn(LD_BUG,
2154 "Previously validated Bridge line could not be added!");
2155 return -1;
2156 // LCOV_EXCL_STOP
2157 }
2158 bridge_add_from_config(bridge_line);
2159 }
2161 }
2162
2163 if (running_tor && hs_config_service_all(options, 0)<0) {
2164 // LCOV_EXCL_START
2165 log_warn(LD_BUG,
2166 "Previously validated hidden services line could not be added!");
2167 return -1;
2168 // LCOV_EXCL_STOP
2169 }
2170
2171 if (running_tor && hs_config_client_auth_all(options, 0) < 0) {
2172 // LCOV_EXCL_START
2173 log_warn(LD_BUG, "Previously validated client authorization for "
2174 "hidden services could not be added!");
2175 return -1;
2176 // LCOV_EXCL_STOP
2177 }
2178
2179 if (running_tor && !old_options &&
2180 options->OwningControllerFD != UINT64_MAX) {
2181 const unsigned ctrl_flags =
2182 CC_LOCAL_FD_IS_OWNER |
2183 CC_LOCAL_FD_IS_AUTHENTICATED;
2184 tor_socket_t ctrl_sock = (tor_socket_t)options->OwningControllerFD;
2185 if (control_connection_add_local_fd(ctrl_sock, ctrl_flags) < 0) {
2186 log_warn(LD_CONFIG, "Could not add local controller connection with "
2187 "given FD.");
2188 return -1;
2189 }
2190 }
2191
2192 /* Load state */
2193 if (! or_state_loaded() && running_tor) {
2194 if (or_state_load())
2195 return -1;
2196 if (options_act_dirauth_mtbf(options) < 0)
2197 return -1;
2198 }
2199
2200 /* 31851: some of the code in these functions is relay-only */
2203 if (!options->DisableNetwork) {
2204 if (options->ClientTransportPlugin) {
2205 for (cl = options->ClientTransportPlugin; cl; cl = cl->next) {
2206 if (pt_parse_transport_line(options, cl->value, 0, 0) < 0) {
2207 // LCOV_EXCL_START
2208 log_warn(LD_BUG,
2209 "Previously validated ClientTransportPlugin line "
2210 "could not be added!");
2211 return -1;
2212 // LCOV_EXCL_STOP
2213 }
2214 }
2215 }
2216 }
2217
2218 if (options_act_server_transport(old_options) < 0)
2219 return -1;
2220
2223
2224 /* Start the PT proxy configuration. By doing this configuration
2225 here, we also figure out which proxies need to be restarted and
2226 which not. */
2229
2230 /* Bail out at this point if we're not going to be a client or server:
2231 * we want to not fork, and to log stuff to stderr. */
2232 if (!running_tor)
2233 return 0;
2234
2235 /* Finish backgrounding the process */
2236 if (options->RunAsDaemon) {
2237 /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
2238 finish_daemon(options->DataDirectory);
2239 }
2240
2241 if (options_act_relay(old_options) < 0)
2242 return -1;
2243
2244 /* Write our PID to the PID file. If we do not have write permissions we
2245 * will log a warning and exit. */
2246 if (options->PidFile && !sandbox_is_active()) {
2247 if (write_pidfile(options->PidFile) < 0) {
2248 log_err(LD_CONFIG, "Unable to write PIDFile %s",
2249 escaped(options->PidFile));
2250 return -1;
2251 }
2252 }
2253
2254 /* Register addressmap directives */
2256 parse_virtual_addr_network(options->VirtualAddrNetworkIPv4, AF_INET,0,NULL);
2257 parse_virtual_addr_network(options->VirtualAddrNetworkIPv6, AF_INET6,0,NULL);
2258
2259 /* Update address policies. */
2260 if (policies_parse_from_options(options) < 0) {
2261 /* This should be impossible, but let's be sure. */
2262 log_warn(LD_BUG,"Error parsing already-validated policy options.");
2263 return -1;
2264 }
2265
2266 if (init_control_cookie_authentication(options->CookieAuthentication) < 0) {
2267 log_warn(LD_CONFIG,"Error creating control cookie authentication file.");
2268 return -1;
2269 }
2270
2272
2273 /* reload keys as needed for rendezvous services. */
2274 if (hs_service_load_all_keys() < 0) {
2275 log_warn(LD_GENERAL,"Error loading rendezvous service keys");
2276 return -1;
2277 }
2278
2279 /* Inform the scheduler subsystem that a configuration changed happened. It
2280 * might be a change of scheduler or parameter. */
2282
2283 if (options_act_relay_accounting(old_options) < 0)
2284 return -1;
2285
2286 /* Change the cell EWMA settings */
2288
2289 /* Update the BridgePassword's hashed version as needed. We store this as a
2290 * digest so that we can do side-channel-proof comparisons on it.
2291 */
2292 if (options->BridgePassword) {
2293 char *http_authenticator;
2294 http_authenticator = alloc_http_authenticator(options->BridgePassword);
2295 if (!http_authenticator) {
2296 // XXXX This should get validated in options_validate().
2297 log_warn(LD_BUG, "Unable to allocate HTTP authenticator. Not setting "
2298 "BridgePassword.");
2299 return -1;
2300 }
2301 options->BridgePassword_AuthDigest_ = tor_malloc(DIGEST256_LEN);
2303 http_authenticator, strlen(http_authenticator),
2304 DIGEST_SHA256);
2305 tor_free(http_authenticator);
2306 }
2307
2308 config_maybe_load_geoip_files_(options, old_options);
2309
2310 if (geoip_is_loaded(AF_INET) && options->GeoIPExcludeUnknown) {
2311 /* ExcludeUnknown is true or "auto" */
2312 const int is_auto = options->GeoIPExcludeUnknown == -1;
2313 int changed;
2314
2315 changed = routerset_add_unknown_ccs(&options->ExcludeNodes, is_auto);
2316 changed += routerset_add_unknown_ccs(&options->ExcludeExitNodes, is_auto);
2317
2318 if (changed)
2320 }
2321
2322 /* Check for transitions that need action. */
2323 if (old_options) {
2324 int revise_trackexithosts = 0;
2325 int revise_automap_entries = 0;
2326 int abandon_circuits = 0;
2327 if ((options->UseEntryGuards && !old_options->UseEntryGuards) ||
2328 options->UseBridges != old_options->UseBridges ||
2329 (options->UseBridges &&
2330 !config_lines_eq(options->Bridges, old_options->Bridges)) ||
2331 !routerset_equal(old_options->ExcludeNodes,options->ExcludeNodes) ||
2332 !routerset_equal(old_options->ExcludeExitNodes,
2333 options->ExcludeExitNodes) ||
2334 !routerset_equal(old_options->EntryNodes, options->EntryNodes) ||
2335 !routerset_equal(old_options->ExitNodes, options->ExitNodes) ||
2336 !routerset_equal(old_options->HSLayer2Nodes,
2337 options->HSLayer2Nodes) ||
2338 !routerset_equal(old_options->HSLayer3Nodes,
2339 options->HSLayer3Nodes) ||
2340 !routerset_equal(old_options->MiddleNodes, options->MiddleNodes) ||
2341 options->StrictNodes != old_options->StrictNodes) {
2342 log_info(LD_CIRC,
2343 "Changed to using entry guards or bridges, or changed "
2344 "preferred or excluded node lists. "
2345 "Abandoning previous circuits.");
2346 abandon_circuits = 1;
2347 }
2348
2349 if (transition_affects_guards) {
2350 if (options->ReconfigDropsBridgeDescs)
2351 routerlist_drop_bridge_descriptors();
2352 if (guards_update_all()) {
2353 abandon_circuits = 1;
2354 }
2355 }
2356
2357 if (abandon_circuits) {
2360 revise_trackexithosts = 1;
2361 }
2362
2363 if (!smartlist_strings_eq(old_options->TrackHostExits,
2364 options->TrackHostExits))
2365 revise_trackexithosts = 1;
2366
2367 if (revise_trackexithosts)
2369
2370 if (!options->AutomapHostsOnResolve &&
2371 old_options->AutomapHostsOnResolve) {
2372 revise_automap_entries = 1;
2373 } else {
2375 options->AutomapHostsSuffixes))
2376 revise_automap_entries = 1;
2377 else if (!opt_streq(old_options->VirtualAddrNetworkIPv4,
2378 options->VirtualAddrNetworkIPv4) ||
2379 !opt_streq(old_options->VirtualAddrNetworkIPv6,
2380 options->VirtualAddrNetworkIPv6))
2381 revise_automap_entries = 1;
2382 }
2383
2384 if (revise_automap_entries)
2386
2387 if (options_act_bridge_stats(old_options) < 0)
2388 return -1;
2389
2390 if (dns_reset())
2391 return -1;
2392
2393 if (options_act_relay_bandwidth(old_options) < 0)
2394 return -1;
2395
2396 if (options->BandwidthRate != old_options->BandwidthRate ||
2397 options->BandwidthBurst != old_options->BandwidthBurst)
2398 connection_bucket_adjust(options);
2399
2400 if (options->MainloopStats != old_options->MainloopStats) {
2402 }
2403 }
2404
2405 /* 31851: These options are relay-only, but we need to disable them if we
2406 * are in client mode. In 29211, we will disable all relay options in
2407 * client mode. */
2408 /* Only collect directory-request statistics on relays and bridges. */
2409 options->DirReqStatistics = options->DirReqStatistics_option &&
2410 server_mode(options);
2411 options->HiddenServiceStatistics =
2412 options->HiddenServiceStatistics_option && server_mode(options);
2413
2414 /* Only collect other relay-only statistics on relays. */
2415 if (!public_server_mode(options)) {
2416 options->CellStatistics = 0;
2417 options->EntryStatistics = 0;
2418 options->ConnDirectionStatistics = 0;
2419 options->ExitPortStatistics = 0;
2420 }
2421
2422 bool print_notice = 0;
2423 if (options_act_relay_stats(old_options, &print_notice) < 0)
2424 return -1;
2425 if (options_act_dirauth_stats(old_options, &print_notice) < 0)
2426 return -1;
2427 if (print_notice)
2428 options_act_relay_stats_msg();
2429
2430 if (options_act_relay_desc(old_options) < 0)
2431 return -1;
2432
2433 if (options_act_dirauth(old_options) < 0)
2434 return -1;
2435
2436 /* We may need to reschedule some directory stuff if our status changed. */
2437 if (old_options) {
2439 dirclient_fetches_dir_info_early(old_options)) ||
2441 dirclient_fetches_dir_info_later(old_options)) ||
2442 !config_lines_eq(old_options->Bridges, options->Bridges)) {
2443 /* Make sure update_router_have_minimum_dir_info() gets called. */
2445 /* We might need to download a new consensus status later or sooner than
2446 * we had expected. */
2448 }
2449 }
2450
2451 if (options_act_relay_dos(old_options) < 0)
2452 return -1;
2453 if (options_act_relay_dir(old_options) < 0)
2454 return -1;
2455
2456 return 0;
2457}
2458
2459/**
2460 * Enumeration to describe the syntax for a command-line option.
2461 **/
2462typedef enum {
2463 /** Describe an option that does not take an argument. */
2465 /** Describes an option that takes a single argument. */
2467 /** Describes an option that takes a single optional argument. */
2470
2471/** Table describing arguments that Tor accepts on the command line,
2472 * other than those that are the same as in torrc. */
2473static const struct {
2474 /** The string that the user has to provide. */
2475 const char *name;
2476 /** Optional short name. */
2477 const char *short_name;
2478 /** Does this option accept an argument? */
2480 /** If not CMD_RUN_TOR, what should Tor do when it starts? */
2482 /** If nonzero, set the quiet level to this. 1 is "hush", 2 is "quiet" */
2485 { .name="--torrc-file",
2486 .short_name="-f",
2487 .takes_argument=ARGUMENT_NECESSARY },
2488 { .name="--allow-missing-torrc" },
2489 { .name="--defaults-torrc",
2490 .takes_argument=ARGUMENT_NECESSARY },
2491 { .name="--hash-password",
2492 .takes_argument=ARGUMENT_NECESSARY,
2493 .command=CMD_HASH_PASSWORD,
2494 .quiet=QUIET_HUSH },
2495 { .name="--dump-config",
2496 .takes_argument=ARGUMENT_OPTIONAL,
2497 .command=CMD_DUMP_CONFIG,
2498 .quiet=QUIET_SILENT },
2499 { .name="--list-fingerprint",
2500 .takes_argument=ARGUMENT_OPTIONAL,
2501 .command=CMD_LIST_FINGERPRINT },
2502 { .name="--keygen",
2503 .command=CMD_KEYGEN },
2504 { .name="--keygen-family",
2505 .command=CMD_KEYGEN_FAMILY,
2506 .takes_argument=ARGUMENT_NECESSARY },
2507 { .name="--key-expiration",
2508 .takes_argument=ARGUMENT_OPTIONAL,
2509 .command=CMD_KEY_EXPIRATION },
2510 { .name="--format",
2511 .takes_argument=ARGUMENT_NECESSARY },
2512 { .name="--newpass" },
2513 { .name="--no-passphrase" },
2514 { .name="--passphrase-fd",
2515 .takes_argument=ARGUMENT_NECESSARY },
2516 { .name="--verify-config",
2517 .command=CMD_VERIFY_CONFIG },
2518 { .name="--ignore-missing-torrc" },
2519 { .name="--quiet",
2520 .quiet=QUIET_SILENT },
2521 { .name="--hush",
2522 .quiet=QUIET_HUSH },
2523 { .name="--version",
2524 .command=CMD_IMMEDIATE,
2525 .quiet=QUIET_HUSH },
2526 { .name="--list-modules",
2527 .command=CMD_IMMEDIATE,
2528 .quiet=QUIET_HUSH },
2529 { .name="--library-versions",
2530 .command=CMD_IMMEDIATE,
2531 .quiet=QUIET_HUSH },
2532 { .name="--help",
2533 .short_name="-h",
2534 .command=CMD_IMMEDIATE,
2535 .quiet=QUIET_HUSH },
2536 { .name="--list-torrc-options",
2537 .command=CMD_IMMEDIATE,
2538 .quiet=QUIET_HUSH },
2539 { .name="--list-deprecated-options",
2540 .command=CMD_IMMEDIATE },
2541 { .name="--nt-service" },
2542 { .name="-nt-service" },
2543 { .name="--dbg-dump-subsystem-list",
2544 .command=CMD_IMMEDIATE,
2545 .quiet=QUIET_HUSH },
2546 { .name=NULL },
2548
2549/** Helper: Read a list of configuration options from the command line. If
2550 * successful, return a newly allocated parsed_cmdline_t; otherwise return
2551 * NULL.
2552 *
2553 * If <b>ignore_errors</b> is set, try to recover from all recoverable
2554 * errors and return the best command line we can.
2555 */
2557config_parse_commandline(int argc, char **argv, int ignore_errors)
2558{
2559 parsed_cmdline_t *result = tor_malloc_zero(sizeof(parsed_cmdline_t));
2560 result->command = CMD_RUN_TOR;
2561 config_line_t *param = NULL;
2562
2563 config_line_t **new_cmdline = &result->cmdline_opts;
2564 config_line_t **new = &result->other_opts;
2565
2566 char *s, *arg;
2567 int i = 1;
2568
2569 while (i < argc) {
2570 unsigned command = CONFIG_LINE_NORMAL;
2572 int is_cmdline = 0;
2573 int j;
2574 bool is_a_command = false;
2575
2576 for (j = 0; CMDLINE_ONLY_OPTIONS[j].name != NULL; ++j) {
2577 if (!strcmp(argv[i], CMDLINE_ONLY_OPTIONS[j].name) ||
2579 !strcmp(argv[i], CMDLINE_ONLY_OPTIONS[j].short_name))) {
2580 is_cmdline = 1;
2581 want_arg = CMDLINE_ONLY_OPTIONS[j].takes_argument;
2583 is_a_command = true;
2584 result->command = CMDLINE_ONLY_OPTIONS[j].command;
2585 }
2587 if (quiet > result->quiet_level)
2588 result->quiet_level = quiet;
2589 break;
2590 }
2591 }
2592
2593 s = argv[i];
2594
2595 /* Each keyword may be prefixed with one or two dashes. */
2596 if (*s == '-')
2597 s++;
2598 if (*s == '-')
2599 s++;
2600 /* Figure out the command, if any. */
2601 if (*s == '+') {
2602 s++;
2604 } else if (*s == '/') {
2605 s++;
2606 command = CONFIG_LINE_CLEAR;
2607 /* A 'clear' command has no argument. */
2608 want_arg = 0;
2609 }
2610
2611 const int is_last = (i == argc-1);
2612
2613 if (want_arg == ARGUMENT_NECESSARY && is_last) {
2614 if (ignore_errors) {
2615 arg = tor_strdup("");
2616 } else {
2617 log_warn(LD_CONFIG,"Command-line option '%s' with no value. Failing.",
2618 argv[i]);
2619 parsed_cmdline_free(result);
2620 return NULL;
2621 }
2622 } else if (want_arg == ARGUMENT_OPTIONAL &&
2623 /* optional arguments may never start with '-'. */
2624 (is_last || argv[i+1][0] == '-')) {
2625 arg = tor_strdup("");
2626 want_arg = ARGUMENT_NONE; // prevent skipping the next flag.
2627 } else {
2628 arg = (want_arg != ARGUMENT_NONE) ? tor_strdup(argv[i+1]) :
2629 tor_strdup("");
2630 }
2631
2632 param = tor_malloc_zero(sizeof(config_line_t));
2633 param->key = is_cmdline ? tor_strdup(argv[i]) :
2634 tor_strdup(config_expand_abbrev(get_options_mgr(), s, 1, 1));
2635 param->value = arg;
2636 param->command = command;
2637 param->next = NULL;
2638 log_debug(LD_CONFIG, "command line: parsed keyword '%s', value '%s'",
2639 param->key, param->value);
2640
2641 if (is_a_command) {
2642 result->command_arg = param->value;
2643 }
2644
2645 if (is_cmdline) {
2646 *new_cmdline = param;
2647 new_cmdline = &((*new_cmdline)->next);
2648 } else {
2649 *new = param;
2650 new = &((*new)->next);
2651 }
2652
2653 i += want_arg ? 2 : 1;
2654 }
2655
2656 return result;
2657}
2658
2659/** Release all storage held by <b>cmdline</b>. */
2660void
2662{
2663 if (!cmdline)
2664 return;
2665 config_free_lines(cmdline->cmdline_opts);
2666 config_free_lines(cmdline->other_opts);
2667 tor_free(cmdline);
2668}
2669
2670/** Return true iff key is a valid configuration option. */
2671int
2672option_is_recognized(const char *key)
2673{
2674 return config_find_option_name(get_options_mgr(), key) != NULL;
2675}
2676
2677/** Return the canonical name of a configuration option, or NULL
2678 * if no such option exists. */
2679const char *
2681{
2683}
2684
2685/** Return a canonical list of the options assigned for key.
2686 */
2688option_get_assignment(const or_options_t *options, const char *key)
2689{
2690 return config_get_assigned_option(get_options_mgr(), options, key, 1);
2691}
2692
2693/** Try assigning <b>list</b> to the global options. You do this by duping
2694 * options, assigning list to the new one, then validating it. If it's
2695 * ok, then throw out the old one and stick with the new one. Else,
2696 * revert to old and return failure. Return SETOPT_OK on success, or
2697 * a setopt_err_t on failure.
2698 *
2699 * If not success, point *<b>msg</b> to a newly allocated string describing
2700 * what went wrong.
2701 */
2703options_trial_assign(config_line_t *list, unsigned flags, char **msg)
2704{
2705 int r;
2706 or_options_t *trial_options = config_dup(get_options_mgr(), get_options());
2707
2708 if ((r=config_assign(get_options_mgr(), trial_options,
2709 list, flags, msg)) < 0) {
2710 or_options_free(trial_options);
2711 return r;
2712 }
2713 const or_options_t *cur_options = get_options();
2714
2715 return options_validate_and_set(cur_options, trial_options, msg);
2716}
2717
2718/** Print a usage message for tor. */
2719static void
2721{
2722 printf(
2723"Copyright (c) 2001-2004, Roger Dingledine\n"
2724"Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
2725"Copyright (c) 2007-2021, The Tor Project, Inc.\n\n"
2726"tor -f <torrc> [args]\n"
2727"See man page for options, or https://www.torproject.org/ for "
2728"documentation.\n");
2729}
2730
2731/** Print all non-obsolete torrc options. */
2732static void
2734{
2736 SMARTLIST_FOREACH_BEGIN(vars, const config_var_t *, var) {
2737 /* Possibly this should check listable, rather than (or in addition to)
2738 * settable. See ticket 31654.
2739 */
2740 if (! config_var_is_settable(var)) {
2741 /* This variable cannot be set, or cannot be set by this name. */
2742 continue;
2743 }
2744 printf("%s\n", var->member.name);
2745 } SMARTLIST_FOREACH_END(var);
2746 smartlist_free(vars);
2747}
2748
2749/** Print all deprecated but non-obsolete torrc options. */
2750static void
2752{
2754 /* Possibly this should check whether the variables are listable,
2755 * but currently it does not. See ticket 31654. */
2756 SMARTLIST_FOREACH(deps, const char *, name,
2757 printf("%s\n", name));
2758 smartlist_free(deps);
2759}
2760
2761/** Print all compile-time modules and their enabled/disabled status. */
2762static void
2764{
2765 static const struct {
2766 const char *name;
2767 bool have;
2768 } list[] = {
2769 { "relay", have_module_relay() },
2770 { "dirauth", have_module_dirauth() },
2771 { "dircache", have_module_dircache() },
2772 { "pow", have_module_pow() }
2773 };
2774
2775 for (unsigned i = 0; i < sizeof list / sizeof list[0]; i++) {
2776 printf("%s: %s\n", list[i].name, list[i].have ? "yes" : "no");
2777 }
2778}
2779
2780/** Prints compile-time and runtime library versions. */
2781static void
2783{
2784 printf("Tor version %s. \n", get_version());
2785 printf("Library versions\tCompiled\t\tRuntime\n");
2786 printf("Libevent\t\t%-15s\t\t%s\n",
2789#ifdef ENABLE_OPENSSL
2790 printf("OpenSSL \t\t%-15s\t\t%s\n",
2791 crypto_openssl_get_header_version_str(),
2792 crypto_openssl_get_version_str());
2793#endif
2794#ifdef ENABLE_NSS
2795 printf("NSS \t\t%-15s\t\t%s\n",
2796 crypto_nss_get_header_version_str(),
2797 crypto_nss_get_version_str());
2798#endif
2799 if (tor_compress_supports_method(ZLIB_METHOD)) {
2800 printf("Zlib \t\t%-15s\t\t%s\n",
2801 tor_compress_version_str(ZLIB_METHOD),
2802 tor_compress_header_version_str(ZLIB_METHOD));
2803 }
2804 if (tor_compress_supports_method(LZMA_METHOD)) {
2805 printf("Liblzma \t\t%-15s\t\t%s\n",
2806 tor_compress_version_str(LZMA_METHOD),
2807 tor_compress_header_version_str(LZMA_METHOD));
2808 }
2809 if (tor_compress_supports_method(ZSTD_METHOD)) {
2810 printf("Libzstd \t\t%-15s\t\t%s\n",
2811 tor_compress_version_str(ZSTD_METHOD),
2812 tor_compress_header_version_str(ZSTD_METHOD));
2813 }
2814 if (tor_libc_get_name()) {
2815 printf("%-7s \t\t%-15s\t\t%s\n",
2819 }
2820 //TODO: Hex versions?
2821}
2822
2823/** Handles the --no-passphrase command line option. */
2824static int
2826{
2827 if (command == CMD_KEYGEN) {
2828 get_options_mutable()->keygen_force_passphrase = FORCE_PASSPHRASE_OFF;
2829 return 0;
2830 } else {
2831 log_err(LD_CONFIG, "--no-passphrase specified without --keygen!");
2832 return -1;
2833 }
2834}
2835
2836/** Handles the --format command line option. */
2837static int
2839{
2840 if (command == CMD_KEY_EXPIRATION) {
2841 // keep the same order as enum key_expiration_format
2842 const char *formats[] = { "iso8601", "timestamp" };
2843 int format = -1;
2844 for (unsigned i = 0; i < ARRAY_LENGTH(formats); i++) {
2845 if (!strcmp(value, formats[i])) {
2846 format = i;
2847 break;
2848 }
2849 }
2850
2851 if (format < 0) {
2852 log_err(LD_CONFIG, "Invalid --format value %s", escaped(value));
2853 return -1;
2854 } else {
2855 get_options_mutable()->key_expiration_format = format;
2856 }
2857 return 0;
2858 } else {
2859 log_err(LD_CONFIG, "--format specified without --key-expiration!");
2860 return -1;
2861 }
2862}
2863
2864/** Handles the --newpass command line option. */
2865static int
2867{
2868 if (command == CMD_KEYGEN) {
2869 get_options_mutable()->change_key_passphrase = 1;
2870 return 0;
2871 } else {
2872 log_err(LD_CONFIG, "--newpass specified without --keygen!");
2873 return -1;
2874 }
2875}
2876
2877/** Handles the --passphrase-fd command line option. */
2878static int
2880{
2881 if (get_options()->keygen_force_passphrase == FORCE_PASSPHRASE_OFF) {
2882 log_err(LD_CONFIG, "--no-passphrase specified with --passphrase-fd!");
2883 return -1;
2884 } else if (command != CMD_KEYGEN) {
2885 log_err(LD_CONFIG, "--passphrase-fd specified without --keygen!");
2886 return -1;
2887 } else {
2888 int ok = 1;
2889 long fd = tor_parse_long(value, 10, 0, INT_MAX, &ok, NULL);
2890 if (fd < 0 || ok == 0) {
2891 log_err(LD_CONFIG, "Invalid --passphrase-fd value %s", escaped(value));
2892 return -1;
2893 }
2894 get_options_mutable()->keygen_passphrase_fd = (int)fd;
2895 get_options_mutable()->use_keygen_passphrase_fd = 1;
2896 get_options_mutable()->keygen_force_passphrase = FORCE_PASSPHRASE_ON;
2897 return 0;
2898 }
2899}
2900
2901/** Handles the --master-key command line option. */
2902static int
2904{
2905 if (command != CMD_KEYGEN) {
2906 log_err(LD_CONFIG, "--master-key without --keygen!");
2907 return -1;
2908 } else {
2909 get_options_mutable()->master_key_fname = tor_strdup(value);
2910 return 0;
2911 }
2912}
2913
2914/* Return true if <b>options</b> is using the default authorities, and false
2915 * if any authority-related option has been overridden. */
2916int
2917using_default_dir_authorities(const or_options_t *options)
2918{
2919 return (!options->DirAuthorities && !options->AlternateDirAuthority);
2920}
2921
2922/** Return a new empty or_options_t. Used for testing. */
2925{
2927 options->command = CMD_RUN_TOR;
2928 return options;
2929}
2930
2931/** Set <b>options</b> to hold reasonable defaults for most options.
2932 * Each option defaults to zero. */
2933void
2935{
2936 config_init(get_options_mgr(), options);
2938 char *msg=NULL;
2939 if (config_assign(get_options_mgr(), options, dflts,
2940 CAL_WARN_DEPRECATIONS, &msg)<0) {
2941 log_err(LD_BUG, "Unable to set default options: %s", msg);
2942 tor_free(msg);
2943 tor_assert_unreached();
2944 }
2945 config_free_lines(dflts);
2946 tor_free(msg);
2947}
2948
2949/** Return a string containing a possible configuration file that would give
2950 * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
2951 * include options that are the same as Tor's defaults.
2952 */
2953char *
2954options_dump(const or_options_t *options, int how_to_dump)
2955{
2956 const or_options_t *use_defaults;
2957 int minimal;
2958 switch (how_to_dump) {
2959 case OPTIONS_DUMP_MINIMAL:
2960 use_defaults = global_default_options;
2961 minimal = 1;
2962 break;
2963 case OPTIONS_DUMP_ALL:
2964 use_defaults = NULL;
2965 minimal = 0;
2966 break;
2967 default:
2968 log_warn(LD_BUG, "Bogus value for how_to_dump==%d", how_to_dump);
2969 return NULL;
2970 }
2971
2972 return config_dump(get_options_mgr(), use_defaults, options, minimal, 0);
2973}
2974
2975/** Return 0 if every element of sl is a string holding a decimal
2976 * representation of a port number, or if sl is NULL.
2977 * Otherwise set *msg and return -1. */
2978static int
2979validate_ports_csv(smartlist_t *sl, const char *name, char **msg)
2980{
2981 int i;
2983
2984 if (!sl)
2985 return 0;
2986
2987 SMARTLIST_FOREACH(sl, const char *, cp,
2988 {
2989 i = atoi(cp);
2990 if (i < 1 || i > 65535) {
2991 tor_asprintf(msg, "Port '%s' out of range in %s", cp, name);
2992 return -1;
2993 }
2994 });
2995 return 0;
2996}
2997
2998/** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
2999 * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
3000 * Else return 0.
3001 */
3002int
3003config_ensure_bandwidth_cap(uint64_t *value, const char *desc, char **msg)
3004{
3005 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
3006 /* This handles an understandable special case where somebody says "2gb"
3007 * whereas our actual maximum is 2gb-1 (INT_MAX) */
3008 --*value;
3009 }
3010 if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
3011 tor_asprintf(msg, "%s (%"PRIu64") must be at most %d",
3012 desc, (*value),
3013 ROUTER_MAX_DECLARED_BANDWIDTH);
3014 return -1;
3015 }
3016 return 0;
3017}
3018
3019/** Highest allowable value for CircuitsAvailableTimeout.
3020 * If this is too large, client connections will stay open for too long,
3021 * incurring extra padding overhead. */
3022#define MAX_CIRCS_AVAILABLE_TIME (24*60*60)
3023
3024/** Lowest allowable value for MaxCircuitDirtiness; if this is too low, Tor
3025 * will generate too many circuits and potentially overload the network. */
3026#define MIN_MAX_CIRCUIT_DIRTINESS 10
3027
3028/** Highest allowable value for MaxCircuitDirtiness: prevents time_t
3029 * overflows. */
3030#define MAX_MAX_CIRCUIT_DIRTINESS (30*24*60*60)
3031
3032/** Lowest allowable value for CircuitStreamTimeout; if this is too low, Tor
3033 * will generate too many circuits and potentially overload the network. */
3034#define MIN_CIRCUIT_STREAM_TIMEOUT 10
3035
3036/** Lowest recommended value for CircuitBuildTimeout; if it is set too low
3037 * and LearnCircuitBuildTimeout is off, the failure rate for circuit
3038 * construction may be very high. In that case, if it is set below this
3039 * threshold emit a warning.
3040 * */
3041#define RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT (10)
3042
3043/**
3044 * Validate <b>new_options</b>. If it is valid, and it is a reasonable
3045 * replacement for <b>old_options</b>, replace the previous value of the
3046 * global options, and return return SETOPT_OK.
3047 *
3048 * If it is not valid, then free <b>new_options</b>, set *<b>msg_out</b> to a
3049 * newly allocated error message, and return an error code.
3050 */
3051static setopt_err_t
3053 or_options_t *new_options,
3054 char **msg_out)
3055{
3056 setopt_err_t rv;
3058
3060 vs = config_validate(get_options_mgr(), old_options, new_options, msg_out);
3061
3062 if (vs == VSTAT_TRANSITION_ERR) {
3063 rv = SETOPT_ERR_TRANSITION;
3064 goto err;
3065 } else if (vs < 0) {
3066 rv = SETOPT_ERR_PARSE;
3067 goto err;
3068 }
3070
3071 if (set_options(new_options, msg_out)) {
3072 rv = SETOPT_ERR_SETTING;
3073 goto err;
3074 }
3075
3076 rv = SETOPT_OK;
3077 new_options = NULL; /* prevent free */
3078 err:
3080 tor_assert(new_options == NULL || rv != SETOPT_OK);
3081 or_options_free(new_options);
3082 return rv;
3083}
3084
3085#ifdef TOR_UNIT_TESTS
3086/**
3087 * Return 0 if every setting in <b>options</b> is reasonable, is a
3088 * permissible transition from <b>old_options</b>, and none of the
3089 * testing-only settings differ from <b>default_options</b> unless in
3090 * testing mode. Else return -1. Should have no side effects, except for
3091 * normalizing the contents of <b>options</b>.
3092 *
3093 * On error, tor_strdup an error explanation into *<b>msg</b>.
3094 */
3095int
3096options_validate(const or_options_t *old_options, or_options_t *options,
3097 char **msg)
3098{
3100 vs = config_validate(get_options_mgr(), old_options, options, msg);
3101 return vs < 0 ? -1 : 0;
3102}
3103#endif /* defined(TOR_UNIT_TESTS) */
3104
3105#define REJECT(arg) \
3106 STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
3107#if defined(__GNUC__) && __GNUC__ <= 3
3108#define COMPLAIN(args...) \
3109 STMT_BEGIN log_warn(LD_CONFIG, args); STMT_END
3110#else
3111#define COMPLAIN(args, ...) \
3112 STMT_BEGIN log_warn(LD_CONFIG, args, ##__VA_ARGS__); STMT_END
3113#endif /* defined(__GNUC__) && __GNUC__ <= 3 */
3114
3115/** Log a warning message iff <b>filepath</b> is not absolute.
3116 * Warning message must contain option name <b>option</b> and
3117 * an absolute path that <b>filepath</b> will resolve to.
3118 *
3119 * In case <b>filepath</b> is absolute, do nothing.
3120 *
3121 * Return 1 if there were relative paths; 0 otherwise.
3122 */
3123static int
3125 const char *filepath)
3126{
3127 if (filepath && path_is_relative(filepath)) {
3128 char *abs_path = make_path_absolute(filepath);
3129 COMPLAIN("Path for %s (%s) is relative and will resolve to %s."
3130 " Is this what you wanted?", option, filepath, abs_path);
3131 tor_free(abs_path);
3132 return 1;
3133 }
3134 return 0;
3135}
3136
3137/** Scan <b>options</b> for occurrences of relative file/directory
3138 * paths and log a warning whenever one is found.
3139 *
3140 * Return 1 if there were relative paths; 0 otherwise.
3141 */
3142static int
3144{
3145 tor_assert(options);
3146 int n = 0;
3147 const config_mgr_t *mgr = get_options_mgr();
3148
3149 smartlist_t *vars = config_mgr_list_vars(mgr);
3150 SMARTLIST_FOREACH_BEGIN(vars, const config_var_t *, cv) {
3151 config_line_t *line;
3152 if (cv->member.type != CONFIG_TYPE_FILENAME)
3153 continue;
3154 const char *name = cv->member.name;
3155 line = config_get_assigned_option(mgr, options, name, 0);
3156 if (line)
3157 n += warn_if_option_path_is_relative(name, line->value);
3158 config_free_lines(line);
3159 } SMARTLIST_FOREACH_END(cv);
3160 smartlist_free(vars);
3161
3162 for (config_line_t *hs_line = options->RendConfigLines; hs_line;
3163 hs_line = hs_line->next) {
3164 if (!strcasecmp(hs_line->key, "HiddenServiceDir"))
3165 n += warn_if_option_path_is_relative("HiddenServiceDir",hs_line->value);
3166 }
3167 return n != 0;
3168}
3169
3170/* Validate options related to the scheduler. From the Schedulers list, the
3171 * SchedulerTypes_ list is created with int values so once we select the
3172 * scheduler, which can happen anytime at runtime, we don't have to parse
3173 * strings and thus be quick.
3174 *
3175 * Return 0 on success else -1 and msg is set with an error message. */
3176static int
3177options_validate_scheduler(or_options_t *options, char **msg)
3178{
3179 tor_assert(options);
3180 tor_assert(msg);
3181
3182 if (!options->Schedulers || smartlist_len(options->Schedulers) == 0) {
3183 REJECT("Empty Schedulers list. Either remove the option so the defaults "
3184 "can be used or set at least one value.");
3185 }
3186 /* Ok, we do have scheduler types, validate them. */
3187 if (options->SchedulerTypes_) {
3188 SMARTLIST_FOREACH(options->SchedulerTypes_, int *, iptr, tor_free(iptr));
3189 smartlist_free(options->SchedulerTypes_);
3190 }
3191 options->SchedulerTypes_ = smartlist_new();
3192 SMARTLIST_FOREACH_BEGIN(options->Schedulers, const char *, type) {
3193 int *sched_type;
3194 if (!strcasecmp("KISTLite", type)) {
3195 sched_type = tor_malloc_zero(sizeof(int));
3196 *sched_type = SCHEDULER_KIST_LITE;
3197 smartlist_add(options->SchedulerTypes_, sched_type);
3198 } else if (!strcasecmp("KIST", type)) {
3199 sched_type = tor_malloc_zero(sizeof(int));
3200 *sched_type = SCHEDULER_KIST;
3201 smartlist_add(options->SchedulerTypes_, sched_type);
3202 } else if (!strcasecmp("Vanilla", type)) {
3203 sched_type = tor_malloc_zero(sizeof(int));
3204 *sched_type = SCHEDULER_VANILLA;
3205 smartlist_add(options->SchedulerTypes_, sched_type);
3206 } else {
3207 tor_asprintf(msg, "Unknown type %s in option Schedulers. "
3208 "Possible values are KIST, KISTLite and Vanilla.",
3209 escaped(type));
3210 return -1;
3211 }
3212 } SMARTLIST_FOREACH_END(type);
3213
3214 if (options->KISTSockBufSizeFactor < 0) {
3215 REJECT("KISTSockBufSizeFactor must be at least 0");
3216 }
3217
3218 /* Don't need to validate that the Interval is less than anything because
3219 * zero is valid and all negative values are valid. */
3220 if (options->KISTSchedRunInterval > KIST_SCHED_RUN_INTERVAL_MAX) {
3221 tor_asprintf(msg, "KISTSchedRunInterval must not be more than %d (ms)",
3222 KIST_SCHED_RUN_INTERVAL_MAX);
3223 return -1;
3224 }
3225
3226 return 0;
3227}
3228
3229/* Validate options related to single onion services.
3230 * Modifies some options that are incompatible with single onion services.
3231 * On failure returns -1, and sets *msg to an error string.
3232 * Returns 0 on success. */
3233STATIC int
3234options_validate_single_onion(or_options_t *options, char **msg)
3235{
3236 /* The two single onion service options must have matching values. */
3237 if (options->HiddenServiceSingleHopMode &&
3238 !options->HiddenServiceNonAnonymousMode) {
3239 REJECT("HiddenServiceSingleHopMode does not provide any server anonymity. "
3240 "It must be used with HiddenServiceNonAnonymousMode set to 1.");
3241 }
3242 if (options->HiddenServiceNonAnonymousMode &&
3243 !options->HiddenServiceSingleHopMode) {
3244 REJECT("HiddenServiceNonAnonymousMode does not provide any server "
3245 "anonymity. It must be used with HiddenServiceSingleHopMode set to "
3246 "1.");
3247 }
3248
3249 /* Now that we've checked that the two options are consistent, we can safely
3250 * call the hs_service_* functions that abstract these options. */
3251
3252 /* If you run an anonymous client with an active Single Onion service, the
3253 * client loses anonymity. */
3254 const int client_port_set = (options->SocksPort_set ||
3255 options->TransPort_set ||
3256 options->NATDPort_set ||
3257 options->DNSPort_set ||
3258 options->HTTPTunnelPort_set);
3259 if (hs_service_non_anonymous_mode_enabled(options) && client_port_set) {
3260 REJECT("HiddenServiceNonAnonymousMode is incompatible with using Tor as "
3261 "an anonymous client. Please set Socks/Trans/NATD/DNSPort to 0, or "
3262 "revert HiddenServiceNonAnonymousMode to 0.");
3263 }
3264
3265 if (hs_service_allow_non_anonymous_connection(options)
3266 && options->UseEntryGuards) {
3267 /* Single Onion services only use entry guards when uploading descriptors;
3268 * all other connections are one-hop. Further, Single Onions causes the
3269 * hidden service code to do things which break the path bias
3270 * detector, and it's far easier to turn off entry guards (and
3271 * thus the path bias detector with it) than to figure out how to
3272 * make path bias compatible with single onions.
3273 */
3274 log_notice(LD_CONFIG,
3275 "HiddenServiceSingleHopMode is enabled; disabling "
3276 "UseEntryGuards.");
3277 options->UseEntryGuards = 0;
3278 }
3279
3280 return 0;
3281}
3282
3283/**
3284 * Legacy validation/normalization callback for or_options_t. See
3285 * legacy_validate_fn_t for more information.
3286 */
3287static int
3288options_validate_cb(const void *old_options_, void *options_, char **msg)
3289{
3290 if (old_options_)
3291 CHECK_OPTIONS_MAGIC(old_options_);
3292 CHECK_OPTIONS_MAGIC(options_);
3293 const or_options_t *old_options = old_options_;
3294 or_options_t *options = options_;
3295
3296 config_line_t *cl;
3297 int n_ports=0;
3298 int world_writable_control_socket=0;
3299
3300 tor_assert(msg);
3301 *msg = NULL;
3302
3303 if (parse_ports(options, 1, msg, &n_ports,
3304 &world_writable_control_socket) < 0)
3305 return -1;
3306
3307#ifndef HAVE_SYS_UN_H
3308 if (options->ControlSocket || options->ControlSocketsGroupWritable) {
3309 *msg = tor_strdup("Unix domain sockets (ControlSocket) not supported "
3310 "on this OS/with this build.");
3311 return -1;
3312 }
3313#else /* defined(HAVE_SYS_UN_H) */
3314 if (options->ControlSocketsGroupWritable && !options->ControlSocket) {
3315 *msg = tor_strdup("Setting ControlSocketsGroupWritable without setting "
3316 "a ControlSocket makes no sense.");
3317 return -1;
3318 }
3319#endif /* !defined(HAVE_SYS_UN_H) */
3320
3321 /* Set UseEntryGuards from the configured value, before we check it below.
3322 * We change UseEntryGuards when it's incompatible with other options,
3323 * but leave UseEntryGuards_option with the original value.
3324 * Always use the value of UseEntryGuards, not UseEntryGuards_option. */
3325 options->UseEntryGuards = options->UseEntryGuards_option;
3326
3327 if (options_validate_relay_os(old_options, options, msg) < 0)
3328 return -1;
3329
3330 /* 31851: OutboundBindAddressExit is unused in client mode */
3331 if (parse_outbound_addresses(options, 1, msg) < 0)
3332 return -1;
3333
3334 if (validate_data_directories(options)<0)
3335 REJECT("Invalid DataDirectory");
3336
3337 /* need to check for relative paths after we populate
3338 * options->DataDirectory (just above). */
3339 if (warn_about_relative_paths(options) && options->RunAsDaemon) {
3340 REJECT("You have specified at least one relative path (see above) "
3341 "with the RunAsDaemon option. RunAsDaemon is not compatible "
3342 "with relative paths.");
3343 }
3344
3345 if (options_validate_relay_info(old_options, options, msg) < 0)
3346 return -1;
3347
3348 /* 31851: this function is currently a no-op in client mode */
3349 check_network_configuration(server_mode(options));
3350
3351 /* Validate the tor_log(s) */
3352 if (options_init_logs(old_options, options, 1)<0)
3353 REJECT("Failed to validate Log options. See logs for details.");
3354
3355 /* XXXX require that the only port not be DirPort? */
3356 /* XXXX require that at least one port be listened-upon. */
3357 if (n_ports == 0 && !options->RendConfigLines)
3358 log_warn(LD_CONFIG,
3359 "SocksPort, TransPort, NATDPort, DNSPort, and ORPort are all "
3360 "undefined, and there aren't any hidden services configured. "
3361 "Tor will still run, but probably won't do anything.");
3362
3363 options->TransProxyType_parsed = TPT_DEFAULT;
3364#ifdef USE_TRANSPARENT
3365 if (options->TransProxyType) {
3366 if (!strcasecmp(options->TransProxyType, "default")) {
3367 options->TransProxyType_parsed = TPT_DEFAULT;
3368 } else if (!strcasecmp(options->TransProxyType, "pf-divert")) {
3369#if !defined(OpenBSD) && !defined(DARWIN)
3370 /* Later versions of OS X have pf */
3371 REJECT("pf-divert is a OpenBSD-specific "
3372 "and OS X/Darwin-specific feature.");
3373#else
3374 options->TransProxyType_parsed = TPT_PF_DIVERT;
3375#endif /* !defined(OpenBSD) && !defined(DARWIN) */
3376 } else if (!strcasecmp(options->TransProxyType, "tproxy")) {
3377#if !defined(__linux__)
3378 REJECT("TPROXY is a Linux-specific feature.");
3379#else
3380 options->TransProxyType_parsed = TPT_TPROXY;
3381#endif
3382 } else if (!strcasecmp(options->TransProxyType, "ipfw")) {
3383#ifndef KERNEL_MAY_SUPPORT_IPFW
3384 /* Earlier versions of OS X have ipfw */
3385 REJECT("ipfw is a FreeBSD-specific "
3386 "and OS X/Darwin-specific feature.");
3387#else
3388 options->TransProxyType_parsed = TPT_IPFW;
3389#endif /* !defined(KERNEL_MAY_SUPPORT_IPFW) */
3390 } else {
3391 REJECT("Unrecognized value for TransProxyType");
3392 }
3393
3394 if (strcasecmp(options->TransProxyType, "default") &&
3395 !options->TransPort_set) {
3396 REJECT("Cannot use TransProxyType without any valid TransPort.");
3397 }
3398 }
3399#else /* !defined(USE_TRANSPARENT) */
3400 if (options->TransPort_set)
3401 REJECT("TransPort is disabled in this build.");
3402#endif /* defined(USE_TRANSPARENT) */
3403
3404 if (options->TokenBucketRefillInterval <= 0
3405 || options->TokenBucketRefillInterval > 1000) {
3406 REJECT("TokenBucketRefillInterval must be between 1 and 1000 inclusive.");
3407 }
3408
3409 if (options->AssumeReachable && options->AssumeReachableIPv6 == 0) {
3410 REJECT("Cannot set AssumeReachable 1 and AssumeReachableIPv6 0.");
3411 }
3412
3413 if (options->ExcludeExitNodes || options->ExcludeNodes) {
3417 }
3418
3419 if (options->NodeFamilies) {
3420 options->NodeFamilySets = smartlist_new();
3421 for (cl = options->NodeFamilies; cl; cl = cl->next) {
3422 routerset_t *rs = routerset_new();
3423 if (routerset_parse(rs, cl->value, cl->key) == 0) {
3424 smartlist_add(options->NodeFamilySets, rs);
3425 } else {
3426 routerset_free(rs);
3427 }
3428 }
3429 }
3430
3431 if (options->ExcludeNodes && options->StrictNodes) {
3432 COMPLAIN("You have asked to exclude certain relays from all positions "
3433 "in your circuits. Expect hidden services and other Tor "
3434 "features to be broken in unpredictable ways.");
3435 }
3436
3437 if (options_validate_dirauth_mode(old_options, options, msg) < 0)
3438 return -1;
3439
3440 if (options->FetchDirInfoExtraEarly && !options->FetchDirInfoEarly)
3441 REJECT("FetchDirInfoExtraEarly requires that you also set "
3442 "FetchDirInfoEarly");
3443
3444 if (options->ConnLimit <= 0) {
3445 tor_asprintf(msg,
3446 "ConnLimit must be greater than 0, but was set to %d",
3447 options->ConnLimit);
3448 return -1;
3449 }
3450
3451 if (options->PathsNeededToBuildCircuits >= 0.0) {
3452 if (options->PathsNeededToBuildCircuits < 0.25) {
3453 log_warn(LD_CONFIG, "PathsNeededToBuildCircuits is too low. Increasing "
3454 "to 0.25");
3455 options->PathsNeededToBuildCircuits = 0.25;
3456 } else if (options->PathsNeededToBuildCircuits > 0.95) {
3457 log_warn(LD_CONFIG, "PathsNeededToBuildCircuits is too high. Decreasing "
3458 "to 0.95");
3459 options->PathsNeededToBuildCircuits = 0.95;
3460 }
3461 }
3462
3463 if (options->MaxClientCircuitsPending <= 0 ||
3464 options->MaxClientCircuitsPending > MAX_MAX_CLIENT_CIRCUITS_PENDING) {
3465 tor_asprintf(msg,
3466 "MaxClientCircuitsPending must be between 1 and %d, but "
3467 "was set to %d", MAX_MAX_CLIENT_CIRCUITS_PENDING,
3468 options->MaxClientCircuitsPending);
3469 return -1;
3470 }
3471
3472 if (validate_ports_csv(options->FirewallPorts, "FirewallPorts", msg) < 0)
3473 return -1;
3474
3475 if (validate_ports_csv(options->LongLivedPorts, "LongLivedPorts", msg) < 0)
3476 return -1;
3477
3479 "RejectPlaintextPorts", msg) < 0)
3480 return -1;
3481
3483 "WarnPlaintextPorts", msg) < 0)
3484 return -1;
3485
3486 if (options->FascistFirewall && !options->ReachableAddresses) {
3487 if (options->FirewallPorts && smartlist_len(options->FirewallPorts)) {
3488 /* We already have firewall ports set, so migrate them to
3489 * ReachableAddresses, which will set ReachableORAddresses and
3490 * ReachableDirAddresses if they aren't set explicitly. */
3491 smartlist_t *instead = smartlist_new();
3492 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3493 new_line->key = tor_strdup("ReachableAddresses");
3494 /* If we're configured with the old format, we need to prepend some
3495 * open ports. */
3496 SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
3497 {
3498 int p = atoi(portno);
3499 if (p<0) continue;
3500 smartlist_add_asprintf(instead, "*:%d", p);
3501 });
3502 new_line->value = smartlist_join_strings(instead,",",0,NULL);
3503 /* These have been deprecated since 0.1.1.5-alpha-cvs */
3504 log_notice(LD_CONFIG,
3505 "Converting FascistFirewall and FirewallPorts "
3506 "config options to new format: \"ReachableAddresses %s\"",
3507 new_line->value);
3508 options->ReachableAddresses = new_line;
3509 SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
3510 smartlist_free(instead);
3511 } else {
3512 /* We do not have FirewallPorts set, so add 80 to
3513 * ReachableDirAddresses, and 443 to ReachableORAddresses. */
3514 if (!options->ReachableDirAddresses) {
3515 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3516 new_line->key = tor_strdup("ReachableDirAddresses");
3517 new_line->value = tor_strdup("*:80");
3518 options->ReachableDirAddresses = new_line;
3519 log_notice(LD_CONFIG, "Converting FascistFirewall config option "
3520 "to new format: \"ReachableDirAddresses *:80\"");
3521 }
3522 if (!options->ReachableORAddresses) {
3523 config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3524 new_line->key = tor_strdup("ReachableORAddresses");
3525 new_line->value = tor_strdup("*:443");
3526 options->ReachableORAddresses = new_line;
3527 log_notice(LD_CONFIG, "Converting FascistFirewall config option "
3528 "to new format: \"ReachableORAddresses *:443\"");
3529 }
3530 }
3531 }
3532
3533 if ((options->ReachableAddresses ||
3534 options->ReachableORAddresses ||
3535 options->ReachableDirAddresses ||
3536 options->ClientUseIPv4 == 0) &&
3537 server_mode(options))
3538 REJECT("Servers must be able to freely connect to the rest "
3539 "of the Internet, so they must not set Reachable*Addresses "
3540 "or FascistFirewall or FirewallPorts or ClientUseIPv4 0.");
3541
3542 if (options->UseBridges &&
3543 server_mode(options))
3544 REJECT("Servers must be able to freely connect to the rest "
3545 "of the Internet, so they must not set UseBridges.");
3546
3547 /* If both of these are set, we'll end up with funny behavior where we
3548 * demand enough entrynodes be up and running else we won't build
3549 * circuits, yet we never actually use them. */
3550 if (options->UseBridges && options->EntryNodes)
3551 REJECT("You cannot set both UseBridges and EntryNodes.");
3552
3553 /* If we have UseBridges as 1 and UseEntryGuards as 0, we end up bypassing
3554 * the use of bridges */
3555 if (options->UseBridges && !options->UseEntryGuards)
3556 REJECT("Setting UseBridges requires also setting UseEntryGuards.");
3557
3558 options->MaxMemInQueues =
3559 compute_real_max_mem_in_queues(options->MaxMemInQueues_raw,
3560 server_mode(options));
3561 options->MaxMemInQueues_low_threshold = (options->MaxMemInQueues / 4) * 3;
3562
3563 if (!options->SafeLogging ||
3564 !strcasecmp(options->SafeLogging, "0")) {
3565 options->SafeLogging_ = SAFELOG_SCRUB_NONE;
3566 } else if (!strcasecmp(options->SafeLogging, "relay")) {
3567 options->SafeLogging_ = SAFELOG_SCRUB_RELAY;
3568 } else if (!strcasecmp(options->SafeLogging, "1")) {
3569 options->SafeLogging_ = SAFELOG_SCRUB_ALL;
3570 } else {
3571 tor_asprintf(msg,
3572 "Unrecognized value '%s' in SafeLogging",
3573 escaped(options->SafeLogging));
3574 return -1;
3575 }
3576
3577 options->ConfluxClientUX = CONFLUX_UX_HIGH_THROUGHPUT;
3578 if (options->ConfluxClientUX_option) {
3579 if (!strcmp(options->ConfluxClientUX_option, "latency"))
3580 options->ConfluxClientUX = CONFLUX_UX_MIN_LATENCY;
3581 else if (!strcmp(options->ConfluxClientUX_option, "throughput"))
3582 options->ConfluxClientUX = CONFLUX_UX_HIGH_THROUGHPUT;
3583 else if (!strcmp(options->ConfluxClientUX_option, "latency_lowmem"))
3584 options->ConfluxClientUX = CONFLUX_UX_LOW_MEM_LATENCY;
3585 else if (!strcmp(options->ConfluxClientUX_option, "throughput_lowmem"))
3586 options->ConfluxClientUX = CONFLUX_UX_LOW_MEM_THROUGHPUT;
3587 else
3588 REJECT("ConfluxClientUX must be 'latency', 'throughput, "
3589 "'latency_lowmem', or 'throughput_lowmem'");
3590 }
3591
3592 if (options_validate_publish_server(old_options, options, msg) < 0)
3593 return -1;
3594
3595 if (options_validate_relay_padding(old_options, options, msg) < 0)
3596 return -1;
3597
3598 /* Check the Single Onion Service options */
3599 if (options_validate_single_onion(options, msg) < 0)
3600 return -1;
3601
3603 // options_t is immutable for new code (the above code is older),
3604 // so just make the user fix the value themselves rather than
3605 // silently keep a shadow value lower than what they asked for.
3606 REJECT("CircuitsAvailableTimeout is too large. Max is 24 hours.");
3607 }
3608
3609 if (options->EntryNodes && !options->UseEntryGuards) {
3610 REJECT("If EntryNodes is set, UseEntryGuards must be enabled.");
3611 }
3612
3613 if (!(options->UseEntryGuards) &&
3614 (options->RendConfigLines != NULL) &&
3615 !hs_service_allow_non_anonymous_connection(options)) {
3616 log_warn(LD_CONFIG,
3617 "UseEntryGuards is disabled, but you have configured one or more "
3618 "hidden services on this Tor instance. Your hidden services "
3619 "will be very easy to locate using a well-known attack -- see "
3620 "https://freehaven.net/anonbib/#hs-attack06 for details.");
3621 }
3622
3623 if (options->NumPrimaryGuards && options->NumEntryGuards &&
3624 options->NumEntryGuards > options->NumPrimaryGuards) {
3625 REJECT("NumEntryGuards must not be greater than NumPrimaryGuards.");
3626 }
3627
3628 if (options->EntryNodes &&
3629 routerset_is_list(options->EntryNodes) &&
3630 (routerset_len(options->EntryNodes) == 1) &&
3631 (options->RendConfigLines != NULL)) {
3632 tor_asprintf(msg,
3633 "You have one single EntryNodes and at least one hidden service "
3634 "configured. This is bad because it's very easy to locate your "
3635 "entry guard which can then lead to the deanonymization of your "
3636 "hidden service -- for more details, see "
3637 "https://bugs.torproject.org/tpo/core/tor/14917. "
3638 "For this reason, the use of one EntryNodes with an hidden "
3639 "service is prohibited until a better solution is found.");
3640 return -1;
3641 }
3642
3643 /* Inform the hidden service operator that pinning EntryNodes can possibly
3644 * be harmful for the service anonymity. */
3645 if (options->EntryNodes &&
3646 routerset_is_list(options->EntryNodes) &&
3647 (options->RendConfigLines != NULL)) {
3648 log_warn(LD_CONFIG,
3649 "EntryNodes is set with multiple entries and at least one "
3650 "hidden service is configured. Pinning entry nodes can possibly "
3651 "be harmful to the service anonymity. Because of this, we "
3652 "recommend you either don't do that or make sure you know what "
3653 "you are doing. For more details, please look at "
3654 "https://bugs.torproject.org/tpo/core/tor/21155.");
3655 }
3656
3657 /* Single Onion Services: non-anonymous hidden services */
3658 if (hs_service_non_anonymous_mode_enabled(options)) {
3659 log_warn(LD_CONFIG,
3660 "HiddenServiceNonAnonymousMode is set. Every hidden service on "
3661 "this tor instance is NON-ANONYMOUS. If "
3662 "the HiddenServiceNonAnonymousMode option is changed, Tor will "
3663 "refuse to launch hidden services from the same directories, to "
3664 "protect your anonymity against config errors. This setting is "
3665 "for experimental use only.");
3666 }
3667
3668 if (!options->LearnCircuitBuildTimeout && options->CircuitBuildTimeout &&
3670 log_warn(LD_CONFIG,
3671 "CircuitBuildTimeout is shorter (%d seconds) than the recommended "
3672 "minimum (%d seconds), and LearnCircuitBuildTimeout is disabled. "
3673 "If tor isn't working, raise this value or enable "
3674 "LearnCircuitBuildTimeout.",
3675 options->CircuitBuildTimeout,
3677 } else if (!options->LearnCircuitBuildTimeout &&
3678 !options->CircuitBuildTimeout) {
3679 int severity = LOG_NOTICE;
3680 /* Be a little quieter if we've deliberately disabled
3681 * LearnCircuitBuildTimeout. */
3682 if (circuit_build_times_disabled_(options, 1)) {
3683 severity = LOG_INFO;
3684 }
3685 log_fn(severity, LD_CONFIG, "You disabled LearnCircuitBuildTimeout, but "
3686 "didn't specify a CircuitBuildTimeout. I'll pick a plausible "
3687 "default.");
3688 }
3689
3690 if (options->DormantClientTimeout < 10*60 && !options->TestingTorNetwork) {
3691 REJECT("DormantClientTimeout is too low. It must be at least 10 minutes.");
3692 }
3693
3694 if (options->PathBiasNoticeRate > 1.0) {
3695 tor_asprintf(msg,
3696 "PathBiasNoticeRate is too high. "
3697 "It must be between 0 and 1.0");
3698 return -1;
3699 }
3700 if (options->PathBiasWarnRate > 1.0) {
3701 tor_asprintf(msg,
3702 "PathBiasWarnRate is too high. "
3703 "It must be between 0 and 1.0");
3704 return -1;
3705 }
3706 if (options->PathBiasExtremeRate > 1.0) {
3707 tor_asprintf(msg,
3708 "PathBiasExtremeRate is too high. "
3709 "It must be between 0 and 1.0");
3710 return -1;
3711 }
3712 if (options->PathBiasNoticeUseRate > 1.0) {
3713 tor_asprintf(msg,
3714 "PathBiasNoticeUseRate is too high. "
3715 "It must be between 0 and 1.0");
3716 return -1;
3717 }
3718 if (options->PathBiasExtremeUseRate > 1.0) {
3719 tor_asprintf(msg,
3720 "PathBiasExtremeUseRate is too high. "
3721 "It must be between 0 and 1.0");
3722 return -1;
3723 }
3724
3726 log_warn(LD_CONFIG, "MaxCircuitDirtiness option is too short; "
3727 "raising to %d seconds.", MIN_MAX_CIRCUIT_DIRTINESS);
3729 }
3730
3732 log_warn(LD_CONFIG, "MaxCircuitDirtiness option is too high; "
3733 "setting to %d days.", MAX_MAX_CIRCUIT_DIRTINESS/86400);
3735 }
3736
3737 if (options->CircuitStreamTimeout &&
3739 log_warn(LD_CONFIG, "CircuitStreamTimeout option is too short; "
3740 "raising to %d seconds.", MIN_CIRCUIT_STREAM_TIMEOUT);
3742 }
3743
3744 if (options->HeartbeatPeriod &&
3746 !options->TestingTorNetwork) {
3747 log_warn(LD_CONFIG, "HeartbeatPeriod option is too short; "
3748 "raising to %d seconds.", MIN_HEARTBEAT_PERIOD);
3750 }
3751
3752 if (options->KeepalivePeriod < 1)
3753 REJECT("KeepalivePeriod option must be positive.");
3754
3756 "BandwidthRate", msg) < 0)
3757 return -1;
3759 "BandwidthBurst", msg) < 0)
3760 return -1;
3761
3762 if (options_validate_relay_bandwidth(old_options, options, msg) < 0)
3763 return -1;
3764
3765 if (options->BandwidthRate > options->BandwidthBurst)
3766 REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
3767
3768 if (options_validate_relay_accounting(old_options, options, msg) < 0)
3769 return -1;
3770
3771 if (options_validate_relay_mode(old_options, options, msg) < 0)
3772 return -1;
3773
3774 if (options->HTTPProxy) { /* parse it now */
3775 if (tor_addr_port_lookup(options->HTTPProxy,
3776 &options->HTTPProxyAddr, &options->HTTPProxyPort) < 0)
3777 REJECT("HTTPProxy failed to parse or resolve. Please fix.");
3778 if (options->HTTPProxyPort == 0) { /* give it a default */
3779 options->HTTPProxyPort = 80;
3780 }
3781 }
3782
3783 if (options->HTTPProxyAuthenticator) {
3784 if (strlen(options->HTTPProxyAuthenticator) >= 512)
3785 REJECT("HTTPProxyAuthenticator is too long (>= 512 chars).");
3786 }
3787
3788 if (options->HTTPSProxy) { /* parse it now */
3789 if (tor_addr_port_lookup(options->HTTPSProxy,
3790 &options->HTTPSProxyAddr, &options->HTTPSProxyPort) <0)
3791 REJECT("HTTPSProxy failed to parse or resolve. Please fix.");
3792 if (options->HTTPSProxyPort == 0) { /* give it a default */
3793 options->HTTPSProxyPort = 443;
3794 }
3795 }
3796
3797 if (options->HTTPSProxyAuthenticator) {
3798 if (strlen(options->HTTPSProxyAuthenticator) >= 512)
3799 REJECT("HTTPSProxyAuthenticator is too long (>= 512 chars).");
3800 }
3801
3802 if (options->Socks4Proxy) { /* parse it now */
3803 if (tor_addr_port_lookup(options->Socks4Proxy,
3804 &options->Socks4ProxyAddr,
3805 &options->Socks4ProxyPort) <0)
3806 REJECT("Socks4Proxy failed to parse or resolve. Please fix.");
3807 if (options->Socks4ProxyPort == 0) { /* give it a default */
3808 options->Socks4ProxyPort = 1080;
3809 }
3810 }
3811
3812 if (options->Socks5Proxy) { /* parse it now */
3813 if (tor_addr_port_lookup(options->Socks5Proxy,
3814 &options->Socks5ProxyAddr,
3815 &options->Socks5ProxyPort) <0)
3816 REJECT("Socks5Proxy failed to parse or resolve. Please fix.");
3817 if (options->Socks5ProxyPort == 0) { /* give it a default */
3818 options->Socks5ProxyPort = 1080;
3819 }
3820 }
3821
3822 if (options->TCPProxy) {
3823 int res = parse_tcp_proxy_line(options->TCPProxy, options, msg);
3824 if (res < 0) {
3825 return res;
3826 }
3827 }
3828
3829 /* Check if more than one exclusive proxy type has been enabled. */
3830 if (!!options->Socks4Proxy + !!options->Socks5Proxy +
3831 !!options->HTTPSProxy + !!options->TCPProxy > 1)
3832 REJECT("You have configured more than one proxy type. "
3833 "(Socks4Proxy|Socks5Proxy|HTTPSProxy|TCPProxy)");
3834
3835 /* Check if the proxies will give surprising behavior. */
3836 if (options->HTTPProxy && !(options->Socks4Proxy ||
3837 options->Socks5Proxy ||
3838 options->HTTPSProxy ||
3839 options->TCPProxy)) {
3840 log_warn(LD_CONFIG, "HTTPProxy configured, but no SOCKS proxy, "
3841 "HTTPS proxy, or any other TCP proxy configured. Watch out: "
3842 "this configuration will proxy unencrypted directory "
3843 "connections only.");
3844 }
3845
3846 if (options->Socks5ProxyUsername) {
3847 size_t len;
3848
3849 len = strlen(options->Socks5ProxyUsername);
3850 if (len < 1 || len > MAX_SOCKS5_AUTH_FIELD_SIZE)
3851 REJECT("Socks5ProxyUsername must be between 1 and 255 characters.");
3852
3853 if (!options->Socks5ProxyPassword)
3854 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
3855
3856 len = strlen(options->Socks5ProxyPassword);
3857 if (len < 1 || len > MAX_SOCKS5_AUTH_FIELD_SIZE)
3858 REJECT("Socks5ProxyPassword must be between 1 and 255 characters.");
3859 } else if (options->Socks5ProxyPassword)
3860 REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
3861
3862 if (options->HashedControlPassword) {
3864 if (!sl) {
3865 REJECT("Bad HashedControlPassword: wrong length or bad encoding");
3866 } else {
3867 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3868 smartlist_free(sl);
3869 }
3870 }
3871
3872 if (options->HashedControlSessionPassword) {
3875 if (!sl) {
3876 REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
3877 } else {
3878 SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
3879 smartlist_free(sl);
3880 }
3881 }
3882
3883 if (options->OwningControllerProcess) {
3884 const char *validate_pspec_msg = NULL;
3886 &validate_pspec_msg)) {
3887 tor_asprintf(msg, "Bad OwningControllerProcess: %s",
3888 validate_pspec_msg);
3889 return -1;
3890 }
3891 }
3892
3893 if ((options->ControlPort_set || world_writable_control_socket) &&
3894 !options->HashedControlPassword &&
3895 !options->HashedControlSessionPassword &&
3896 !options->CookieAuthentication) {
3897 log_warn(LD_CONFIG, "Control%s is %s, but no authentication method "
3898 "has been configured. This means that any program on your "
3899 "computer can reconfigure your Tor. That's bad! You should "
3900 "upgrade your Tor controller as soon as possible.",
3901 options->ControlPort_set ? "Port" : "Socket",
3902 options->ControlPort_set ? "open" : "world writable");
3903 }
3904
3905 if (options->CookieAuthFileGroupReadable && !options->CookieAuthFile) {
3906 log_warn(LD_CONFIG, "CookieAuthFileGroupReadable is set, but will have "
3907 "no effect: you must specify an explicit CookieAuthFile to "
3908 "have it group-readable.");
3909 }
3910
3911 for (cl = options->NodeFamilies; cl; cl = cl->next) {
3912 routerset_t *rs = routerset_new();
3913 if (routerset_parse(rs, cl->value, cl->key)) {
3914 routerset_free(rs);
3915 return -1;
3916 }
3917 routerset_free(rs);
3918 }
3919
3920 if (validate_addr_policies(options, msg) < 0)
3921 return -1;
3922
3923 /* If FallbackDir is set, we don't UseDefaultFallbackDirs */
3924 if (options->UseDefaultFallbackDirs && options->FallbackDir) {
3925 log_info(LD_CONFIG, "You have set UseDefaultFallbackDirs 1 and "
3926 "FallbackDir(s). Ignoring UseDefaultFallbackDirs, and "
3927 "using the FallbackDir(s) you have set.");
3928 }
3929
3930 if (validate_dir_servers(options, old_options) < 0)
3931 REJECT("Directory authority/fallback line did not parse. See logs "
3932 "for details.");
3933
3934 if (options->UseBridges && !options->Bridges)
3935 REJECT("If you set UseBridges, you must specify at least one bridge.");
3936
3937 for (cl = options->Bridges; cl; cl = cl->next) {
3938 bridge_line_t *bridge_line = parse_bridge_line(cl->value);
3939 if (!bridge_line)
3940 REJECT("Bridge line did not parse. See logs for details.");
3941 bridge_line_free(bridge_line);
3942 }
3943
3944 for (cl = options->ClientTransportPlugin; cl; cl = cl->next) {
3945 if (pt_parse_transport_line(options, cl->value, 1, 0) < 0)
3946 REJECT("Invalid client transport line. See logs for details.");
3947 }
3948
3949 if (options_validate_server_transport(old_options, options, msg) < 0)
3950 return -1;
3951
3952 if (options->ConstrainedSockets) {
3953 /* If the user wants to constrain socket buffer use, make sure the desired
3954 * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
3955 if (options->ConstrainedSockSize < MIN_CONSTRAINED_TCP_BUFFER ||
3956 options->ConstrainedSockSize > MAX_CONSTRAINED_TCP_BUFFER ||
3957 options->ConstrainedSockSize % 1024) {
3958 tor_asprintf(msg,
3959 "ConstrainedSockSize is invalid. Must be a value between %d and %d "
3960 "in 1024 byte increments.",
3961 MIN_CONSTRAINED_TCP_BUFFER, MAX_CONSTRAINED_TCP_BUFFER);
3962 return -1;
3963 }
3964 }
3965
3966 if (options_validate_dirauth_schedule(old_options, options, msg) < 0)
3967 return -1;
3968
3969 if (hs_config_service_all(options, 1) < 0)
3970 REJECT("Failed to configure rendezvous options. See logs for details.");
3971
3972 /* Parse client-side authorization for hidden services. */
3973 if (hs_config_client_auth_all(options, 1) < 0)
3974 REJECT("Failed to configure client authorization for hidden services. "
3975 "See logs for details.");
3976
3978 AF_INET, 1, msg)<0)
3979 return -1;
3981 AF_INET6, 1, msg)<0)
3982 return -1;
3983
3984 if (options->TestingTorNetwork &&
3985 !(options->DirAuthorities ||
3986 (options->AlternateDirAuthority &&
3987 options->AlternateBridgeAuthority))) {
3988 REJECT("TestingTorNetwork may only be configured in combination with "
3989 "a non-default set of DirAuthority or both of "
3990 "AlternateDirAuthority and AlternateBridgeAuthority configured.");
3991 }
3992
3993#define CHECK_DEFAULT(arg) \
3994 STMT_BEGIN \
3995 if (!config_is_same(get_options_mgr(),options, \
3996 dflt_options,#arg)) { \
3997 or_options_free(dflt_options); \
3998 REJECT(#arg " may only be changed in testing Tor " \
3999 "networks!"); \
4000 } \
4001 STMT_END
4002
4003 /* Check for options that can only be changed from the defaults in testing
4004 networks. */
4005 if (! options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
4006 or_options_t *dflt_options = options_new();
4007 options_init(dflt_options);
4008 /* 31851: some of these options are dirauth or relay only */
4009 CHECK_DEFAULT(TestingV3AuthInitialVotingInterval);
4010 CHECK_DEFAULT(TestingV3AuthInitialVoteDelay);
4011 CHECK_DEFAULT(TestingV3AuthInitialDistDelay);
4012 CHECK_DEFAULT(TestingV3AuthVotingStartOffset);
4013 CHECK_DEFAULT(TestingAuthDirTimeToLearnReachability);
4014 CHECK_DEFAULT(TestingServerDownloadInitialDelay);
4015 CHECK_DEFAULT(TestingClientDownloadInitialDelay);
4016 CHECK_DEFAULT(TestingServerConsensusDownloadInitialDelay);
4017 CHECK_DEFAULT(TestingClientConsensusDownloadInitialDelay);
4018 CHECK_DEFAULT(TestingBridgeDownloadInitialDelay);
4019 CHECK_DEFAULT(TestingBridgeBootstrapDownloadInitialDelay);
4020 CHECK_DEFAULT(TestingClientMaxIntervalWithoutRequest);
4021 CHECK_DEFAULT(TestingDirConnectionMaxStall);
4022 CHECK_DEFAULT(TestingAuthKeyLifetime);
4023 CHECK_DEFAULT(TestingLinkCertLifetime);
4024 CHECK_DEFAULT(TestingSigningKeySlop);
4025 CHECK_DEFAULT(TestingAuthKeySlop);
4026 CHECK_DEFAULT(TestingLinkKeySlop);
4027 CHECK_DEFAULT(TestingMinTimeToReportBandwidth);
4028 or_options_free(dflt_options);
4029 }
4030#undef CHECK_DEFAULT
4031
4032 if (!options->ClientDNSRejectInternalAddresses &&
4033 !(options->DirAuthorities ||
4034 (options->AlternateDirAuthority && options->AlternateBridgeAuthority)))
4035 REJECT("ClientDNSRejectInternalAddresses used for default network.");
4036
4037 if (options_validate_relay_testing(old_options, options, msg) < 0)
4038 return -1;
4039 if (options_validate_dirauth_testing(old_options, options, msg) < 0)
4040 return -1;
4041
4042 if (options->TestingClientMaxIntervalWithoutRequest < 1) {
4043 REJECT("TestingClientMaxIntervalWithoutRequest is way too low.");
4044 } else if (options->TestingClientMaxIntervalWithoutRequest > 3600) {
4045 COMPLAIN("TestingClientMaxIntervalWithoutRequest is insanely high.");
4046 }
4047
4048 if (options->TestingDirConnectionMaxStall < 5) {
4049 REJECT("TestingDirConnectionMaxStall is way too low.");
4050 } else if (options->TestingDirConnectionMaxStall > 3600) {
4051 COMPLAIN("TestingDirConnectionMaxStall is insanely high.");
4052 }
4053
4055 REJECT("ClientBootstrapConsensusMaxInProgressTries must be greater "
4056 "than 0.");
4058 > 100) {
4059 COMPLAIN("ClientBootstrapConsensusMaxInProgressTries is insanely "
4060 "high.");
4061 }
4062
4063 if (options->TestingEnableConnBwEvent &&
4064 !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
4065 REJECT("TestingEnableConnBwEvent may only be changed in testing "
4066 "Tor networks!");
4067 }
4068
4069 if (options->TestingEnableCellStatsEvent &&
4070 !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
4071 REJECT("TestingEnableCellStatsEvent may only be changed in testing "
4072 "Tor networks!");
4073 }
4074
4075 if (options->TestingTorNetwork) {
4076 log_warn(LD_CONFIG, "TestingTorNetwork is set. This will make your node "
4077 "almost unusable in the public Tor network, and is "
4078 "therefore only advised if you are building a "
4079 "testing Tor network!");
4080 }
4081
4082 if (options_validate_scheduler(options, msg) < 0) {
4083 return -1;
4084 }
4085
4086 return 0;
4087}
4088
4089#undef REJECT
4090#undef COMPLAIN
4091
4092/* Given the value that the user has set for MaxMemInQueues, compute the
4093 * actual maximum value. We clip this value if it's too low, and autodetect
4094 * it if it's set to 0. */
4095STATIC uint64_t
4096compute_real_max_mem_in_queues(const uint64_t val, bool is_server)
4097{
4098#define MIN_SERVER_MB 64
4099#define MIN_UNWARNED_SERVER_MB 256
4100#define MIN_UNWARNED_CLIENT_MB 64
4101 uint64_t result;
4102
4103 if (val == 0) {
4104#define ONE_GIGABYTE (UINT64_C(1) << 30)
4105#define ONE_MEGABYTE (UINT64_C(1) << 20)
4106 /* The user didn't pick a memory limit. Choose a very large one
4107 * that is still smaller than the system memory */
4108 static int notice_sent = 0;
4109 size_t ram = 0;
4110 if (get_total_system_memory(&ram) < 0) {
4111 /* We couldn't determine our total system memory! */
4112#if SIZEOF_VOID_P >= 8
4113 /* 64-bit system. Let's hope for 8 GB. */
4114 result = 8 * ONE_GIGABYTE;
4115#else
4116 /* (presumably) 32-bit system. Let's hope for 1 GB. */
4117 result = ONE_GIGABYTE;
4118#endif /* SIZEOF_VOID_P >= 8 */
4119 } else {
4120 /* We detected the amount of memory available. */
4121 uint64_t avail = 0;
4122
4123#if SIZEOF_SIZE_T > 4
4124/* On a 64-bit platform, we consider 8GB "very large". */
4125#define RAM_IS_VERY_LARGE(x) ((x) >= (8 * ONE_GIGABYTE))
4126#else
4127/* On a 32-bit platform, we can't have 8GB of ram. */
4128#define RAM_IS_VERY_LARGE(x) (0)
4129#endif /* SIZEOF_SIZE_T > 4 */
4130
4131 if (RAM_IS_VERY_LARGE(ram)) {
4132 /* If we have 8 GB, or more, RAM available, we set the MaxMemInQueues
4133 * to 0.4 * RAM. The idea behind this value is that the amount of RAM
4134 * is more than enough for a single relay and should allow the relay
4135 * operator to run two relays if they have additional bandwidth
4136 * available.
4137 */
4138 avail = (ram / 5) * 2;
4139 } else {
4140 /* If we have less than 8 GB of RAM available, we use the "old" default
4141 * for MaxMemInQueues of 0.75 * RAM.
4142 */
4143 avail = (ram / 4) * 3;
4144 }
4145
4146 /* Make sure it's in range from 0.25 GB to 8 GB for 64-bit and 0.25 to 2
4147 * GB for 32-bit. */
4148 if (avail > MAX_DEFAULT_MEMORY_QUEUE_SIZE) {
4149 /* If you want to use more than this much RAM, you need to configure
4150 it yourself */
4152 } else if (avail < ONE_GIGABYTE / 4) {
4153 result = ONE_GIGABYTE / 4;
4154 } else {
4155 result = avail;
4156 }
4157 }
4158 if (is_server && ! notice_sent) {
4159 log_notice(LD_CONFIG, "%sMaxMemInQueues is set to %"PRIu64" MB. "
4160 "You can override this by setting MaxMemInQueues by hand.",
4161 ram ? "Based on detected system memory, " : "",
4162 (result / ONE_MEGABYTE));
4163 notice_sent = 1;
4164 }
4165 return result;
4166 } else if (is_server && val < ONE_MEGABYTE * MIN_SERVER_MB) {
4167 /* We can't configure less than this much on a server. */
4168 log_warn(LD_CONFIG, "MaxMemInQueues must be at least %d MB on servers "
4169 "for now. Ideally, have it as large as you can afford.",
4170 MIN_SERVER_MB);
4171 return MIN_SERVER_MB * ONE_MEGABYTE;
4172 } else if (is_server && val < ONE_MEGABYTE * MIN_UNWARNED_SERVER_MB) {
4173 /* On a server, if it's less than this much, we warn that things
4174 * may go badly. */
4175 log_warn(LD_CONFIG, "MaxMemInQueues is set to a low value; if your "
4176 "relay doesn't work, this may be the reason why.");
4177 return val;
4178 } else if (! is_server && val < ONE_MEGABYTE * MIN_UNWARNED_CLIENT_MB) {
4179 /* On a client, if it's less than this much, we warn that things
4180 * may go badly. */
4181 log_warn(LD_CONFIG, "MaxMemInQueues is set to a low value; if your "
4182 "client doesn't work, this may be the reason why.");
4183 return val;
4184 } else {
4185 /* The value was fine all along */
4186 return val;
4187 }
4188}
4189
4190/** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
4191 * equal strings. */
4192static int
4193opt_streq(const char *s1, const char *s2)
4194{
4195 return 0 == strcmp_opt(s1, s2);
4196}
4197
4198/** Check if any config options have changed but aren't allowed to. */
4199static int
4201 const void *new_val_,
4202 char **msg)
4203{
4204 CHECK_OPTIONS_MAGIC(old_);
4205 CHECK_OPTIONS_MAGIC(new_val_);
4206
4207 const or_options_t *old = old_;
4208 const or_options_t *new_val = new_val_;
4209
4210 if (BUG(!old))
4211 return 0;
4212
4213#define BAD_CHANGE_TO(opt, how) do { \
4214 *msg = tor_strdup("While Tor is running"how", changing " #opt \
4215 " is not allowed"); \
4216 return -1; \
4217 } while (0)
4218
4219 if (sandbox_is_active()) {
4220#define SB_NOCHANGE_STR(opt) \
4221 if (! CFG_EQ_STRING(old, new_val, opt)) \
4222 BAD_CHANGE_TO(opt," with Sandbox active")
4223#define SB_NOCHANGE_LINELIST(opt) \
4224 if (! CFG_EQ_LINELIST(old, new_val, opt)) \
4225 BAD_CHANGE_TO(opt," with Sandbox active")
4226#define SB_NOCHANGE_INT(opt) \
4227 if (! CFG_EQ_INT(old, new_val, opt)) \
4228 BAD_CHANGE_TO(opt," with Sandbox active")
4229
4230 SB_NOCHANGE_LINELIST(Address);
4231 SB_NOCHANGE_STR(ServerDNSResolvConfFile);
4232 SB_NOCHANGE_STR(DirPortFrontPage);
4233 SB_NOCHANGE_STR(CookieAuthFile);
4234 SB_NOCHANGE_STR(ExtORPortCookieAuthFile);
4235 SB_NOCHANGE_LINELIST(Logs);
4236 SB_NOCHANGE_INT(ConnLimit);
4237
4238 if (server_mode(old) != server_mode(new_val)) {
4239 *msg = tor_strdup("Can't start/stop being a server while "
4240 "Sandbox is active");
4241 return -1;
4242 }
4243 }
4244
4245#undef SB_NOCHANGE_LINELIST
4246#undef SB_NOCHANGE_STR
4247#undef SB_NOCHANGE_INT
4248#undef BAD_CHANGE_TO
4249#undef NO_CHANGE_BOOL
4250#undef NO_CHANGE_INT
4251#undef NO_CHANGE_STRING
4252 return 0;
4253}
4254
4255#ifdef _WIN32
4256/** Return the directory on windows where we expect to find our application
4257 * data. */
4258static char *
4259get_windows_conf_root(void)
4260{
4261 static int is_set = 0;
4262 static char path[MAX_PATH*2+1];
4263 TCHAR tpath[MAX_PATH] = {0};
4264
4265 LPITEMIDLIST idl;
4266 IMalloc *m;
4267 HRESULT result;
4268
4269 if (is_set)
4270 return path;
4271
4272 /* Find X:\documents and settings\username\application data\ .
4273 * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
4274 */
4275#ifdef ENABLE_LOCAL_APPDATA
4276#define APPDATA_PATH CSIDL_LOCAL_APPDATA
4277#else
4278#define APPDATA_PATH CSIDL_APPDATA
4279#endif
4280 if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, APPDATA_PATH, &idl))) {
4281 getcwd(path,MAX_PATH);
4282 is_set = 1;
4283 log_warn(LD_CONFIG,
4284 "I couldn't find your application data folder: are you "
4285 "running an ancient version of Windows 95? Defaulting to \"%s\"",
4286 path);
4287 return path;
4288 }
4289 /* Convert the path from an "ID List" (whatever that is!) to a path. */
4290 result = SHGetPathFromIDList(idl, tpath);
4291#ifdef UNICODE
4292 wcstombs(path,tpath,sizeof(path));
4293 path[sizeof(path)-1] = '\0';
4294#else
4295 strlcpy(path,tpath,sizeof(path));
4296#endif /* defined(UNICODE) */
4297
4298 /* Now we need to free the memory that the path-idl was stored in. In
4299 * typical Windows fashion, we can't just call 'free()' on it. */
4300 SHGetMalloc(&m);
4301 if (m) {
4302 m->lpVtbl->Free(m, idl);
4303 m->lpVtbl->Release(m);
4304 }
4305 if (!SUCCEEDED(result)) {
4306 return NULL;
4307 }
4308 strlcat(path,"\\tor",MAX_PATH);
4309 is_set = 1;
4310 return path;
4311}
4312#endif /* defined(_WIN32) */
4313
4314/** Return the default location for our torrc file (if <b>defaults_file</b> is
4315 * false), or for the torrc-defaults file (if <b>defaults_file</b> is true). */
4316static const char *
4317get_default_conf_file(int defaults_file)
4318{
4319#ifdef DISABLE_SYSTEM_TORRC
4320 (void) defaults_file;
4321 return NULL;
4322#elif defined(_WIN32)
4323 if (defaults_file) {
4324 static char defaults_path[MAX_PATH+1];
4325 tor_snprintf(defaults_path, MAX_PATH, "%s\\torrc-defaults",
4326 get_windows_conf_root());
4327 return defaults_path;
4328 } else {
4329 static char path[MAX_PATH+1];
4330 tor_snprintf(path, MAX_PATH, "%s\\torrc",
4331 get_windows_conf_root());
4332 return path;
4333 }
4334#else
4335 return defaults_file ? CONFDIR "/torrc-defaults" : CONFDIR "/torrc";
4336#endif /* defined(DISABLE_SYSTEM_TORRC) || ... */
4337}
4338
4339/** Learn config file name from command line arguments, or use the default.
4340 *
4341 * If <b>defaults_file</b> is true, we're looking for torrc-defaults;
4342 * otherwise, we're looking for the regular torrc_file.
4343 *
4344 * Set *<b>using_default_fname</b> to true if we're using the default
4345 * configuration file name; or false if we've set it from the command line.
4346 *
4347 * Set *<b>ignore_missing_torrc</b> to true if we should ignore the resulting
4348 * filename if it doesn't exist.
4349 */
4350static char *
4352 int defaults_file,
4353 int *using_default_fname, int *ignore_missing_torrc)
4354{
4355 char *fname=NULL;
4356 const config_line_t *p_index;
4357 const char *fname_opt = defaults_file ? "--defaults-torrc" : "-f";
4358 const char *fname_long_opt = defaults_file ? "--defaults-torrc" :
4359 "--torrc-file";
4360 const char *ignore_opt = defaults_file ? NULL : "--ignore-missing-torrc";
4361 const char *keygen_opt = "--keygen";
4362
4363 if (defaults_file)
4364 *ignore_missing_torrc = 1;
4365
4366 for (p_index = cmd_arg; p_index; p_index = p_index->next) {
4367 // options_init_from_torrc ensures only the short or long name is present
4368 if (!strcmp(p_index->key, fname_opt) ||
4369 !strcmp(p_index->key, fname_long_opt)) {
4370 if (fname) {
4371 log_warn(LD_CONFIG, "Duplicate %s options on command line.",
4372 p_index->key);
4373 tor_free(fname);
4374 }
4375 fname = expand_filename(p_index->value);
4376
4377 {
4378 char *absfname;
4379 absfname = make_path_absolute(fname);
4380 tor_free(fname);
4381 fname = absfname;
4382 }
4383
4384 *using_default_fname = 0;
4385 } else if ((ignore_opt && !strcmp(p_index->key, ignore_opt)) ||
4386 (keygen_opt && !strcmp(p_index->key, keygen_opt))) {
4387 *ignore_missing_torrc = 1;
4388 }
4389 }
4390
4391 if (*using_default_fname) {
4392 /* didn't find one, try CONFDIR */
4393 const char *dflt = get_default_conf_file(defaults_file);
4394 file_status_t st = file_status(dflt);
4395 if (dflt && (st == FN_FILE || st == FN_EMPTY)) {
4396 fname = tor_strdup(dflt);
4397 } else {
4398#ifndef _WIN32
4399 char *fn = NULL;
4400 if (!defaults_file) {
4401 fn = expand_filename("~/.torrc");
4402 }
4403 if (fn) {
4404 file_status_t hmst = file_status(fn);
4405 if (hmst == FN_FILE || hmst == FN_EMPTY || dflt == NULL) {
4406 fname = fn;
4407 } else {
4408 tor_free(fn);
4409 fname = tor_strdup(dflt);
4410 }
4411 } else {
4412 fname = dflt ? tor_strdup(dflt) : NULL;
4413 }
4414#else /* defined(_WIN32) */
4415 fname = dflt ? tor_strdup(dflt) : NULL;
4416#endif /* !defined(_WIN32) */
4417 }
4418 }
4419 return fname;
4420}
4421
4422/** Read the torrc from standard input and return it as a string.
4423 * Upon failure, return NULL.
4424 */
4425static char *
4427{
4428 size_t sz_out;
4429
4430 return read_file_to_str_until_eof(STDIN_FILENO,SIZE_MAX,&sz_out);
4431}
4432
4433/** Load a configuration file from disk, setting torrc_fname or
4434 * torrc_defaults_fname if successful.
4435 *
4436 * If <b>defaults_file</b> is true, load torrc-defaults; otherwise load torrc.
4437 *
4438 * Return the contents of the file on success, and NULL on failure.
4439 */
4440static char *
4441load_torrc_from_disk(const config_line_t *cmd_arg, int defaults_file)
4442{
4443 char *fname=NULL;
4444 char *cf = NULL;
4445 int using_default_torrc = 1;
4446 int ignore_missing_torrc = 0;
4447 char **fname_var = defaults_file ? &torrc_defaults_fname : &torrc_fname;
4448
4449 if (*fname_var == NULL) {
4450 fname = find_torrc_filename(cmd_arg, defaults_file,
4451 &using_default_torrc, &ignore_missing_torrc);
4452 tor_free(*fname_var);
4453 *fname_var = fname;
4454 } else {
4455 fname = *fname_var;
4456 }
4457 log_debug(LD_CONFIG, "Opening config file \"%s\"", fname?fname:"<NULL>");
4458
4459 /* Open config file */
4460 file_status_t st = fname ? file_status(fname) : FN_EMPTY;
4461 if (fname == NULL ||
4462 !(st == FN_FILE || st == FN_EMPTY) ||
4463 !(cf = read_file_to_str(fname,0,NULL))) {
4464 if (using_default_torrc == 1 || ignore_missing_torrc) {
4465 if (!defaults_file)
4466 log_notice(LD_CONFIG, "Configuration file \"%s\" not present, "
4467 "using reasonable defaults.", fname);
4468 tor_free(fname); /* sets fname to NULL */
4469 *fname_var = NULL;
4470 cf = tor_strdup("");
4471 } else {
4472 log_warn(LD_CONFIG,
4473 "Unable to open configuration file \"%s\".", fname);
4474 goto err;
4475 }
4476 } else {
4477 log_notice(LD_CONFIG, "Read configuration file \"%s\".", fname);
4478 }
4479
4480 return cf;
4481 err:
4482 tor_free(fname);
4483 *fname_var = NULL;
4484 return NULL;
4485}
4486
4487/** Read a configuration file into <b>options</b>, finding the configuration
4488 * file location based on the command line. After loading the file
4489 * call options_init_from_string() to load the config.
4490 * Return 0 if success, -1 if failure, and 1 if we succeeded but should exit
4491 * anyway. */
4492int
4493options_init_from_torrc(int argc, char **argv)
4494{
4495 char *cf=NULL, *cf_defaults=NULL;
4496 int retval = -1;
4497 char *errmsg=NULL;
4498 const config_line_t *cmdline_only_options;
4499
4500 /* Go through command-line variables */
4501 if (global_cmdline == NULL) {
4502 /* Or we could redo the list every time we pass this place.
4503 * It does not really matter */
4505 if (global_cmdline == NULL) {
4506 goto err;
4507 }
4508 }
4509 cmdline_only_options = global_cmdline->cmdline_opts;
4510
4511 if (config_line_find(cmdline_only_options, "-h") ||
4512 config_line_find(cmdline_only_options, "--help")) {
4513 print_usage();
4514 return 1;
4515 }
4516 if (config_line_find(cmdline_only_options, "--list-torrc-options")) {
4517 /* For validating whether we've documented everything. */
4519 return 1;
4520 }
4521 if (config_line_find(cmdline_only_options, "--list-deprecated-options")) {
4522 /* For validating whether what we have deprecated really exists. */
4524 return 1;
4525 }
4526 if (config_line_find(cmdline_only_options, "--dbg-dump-subsystem-list")) {
4528 return 1;
4529 }
4530
4531 if (config_line_find(cmdline_only_options, "--version")) {
4532 printf("Tor version %s.\n",get_version());
4533#ifdef ENABLE_GPL
4534 printf("This build of Tor is covered by the GNU General Public License "
4535 "(https://www.gnu.org/licenses/gpl-3.0.en.html)\n");
4536#endif
4537 printf("Tor is running on %s with Libevent %s, "
4538 "%s %s, Zlib %s, Liblzma %s, Libzstd %s and %s %s as libc.\n",
4539 get_uname(),
4543 tor_compress_supports_method(ZLIB_METHOD) ?
4544 tor_compress_version_str(ZLIB_METHOD) : "N/A",
4545 tor_compress_supports_method(LZMA_METHOD) ?
4546 tor_compress_version_str(LZMA_METHOD) : "N/A",
4547 tor_compress_supports_method(ZSTD_METHOD) ?
4548 tor_compress_version_str(ZSTD_METHOD) : "N/A",
4550 tor_libc_get_name() : "Unknown",
4552 printf("Tor compiled with %s version %s\n",
4553 strcmp(COMPILER_VENDOR, "gnu") == 0?
4554 COMPILER:COMPILER_VENDOR, COMPILER_VERSION);
4555
4556 return 1;
4557 }
4558
4559 if (config_line_find(cmdline_only_options, "--list-modules")) {
4561 return 1;
4562 }
4563
4564 if (config_line_find(cmdline_only_options, "--library-versions")) {
4566 return 1;
4567 }
4568
4570 const char *command_arg = global_cmdline->command_arg;
4571 /* "immediate" has already been handled by this point. */
4573
4574 if (command == CMD_HASH_PASSWORD) {
4575 cf_defaults = tor_strdup("");
4576 cf = tor_strdup("");
4577 } else {
4578 cf_defaults = load_torrc_from_disk(cmdline_only_options, 1);
4579 const config_line_t *f_line = config_line_find(cmdline_only_options, "-f");
4580 const config_line_t *f_line_long = config_line_find(cmdline_only_options,
4581 "--torrc-file");
4582 if (f_line && f_line_long) {
4583 log_err(LD_CONFIG, "-f and --torrc-file cannot be used together.");
4584 retval = -1;
4585 goto err;
4586 } else if (f_line_long) {
4587 f_line = f_line_long;
4588 }
4589
4590 const int read_torrc_from_stdin =
4591 (f_line != NULL && strcmp(f_line->value, "-") == 0);
4592
4593 if (read_torrc_from_stdin) {
4594 cf = load_torrc_from_stdin();
4595 } else {
4596 cf = load_torrc_from_disk(cmdline_only_options, 0);
4597 }
4598
4599 if (!cf) {
4600 if (config_line_find(cmdline_only_options, "--allow-missing-torrc")) {
4601 cf = tor_strdup("");
4602 } else {
4603 goto err;
4604 }
4605 }
4606 }
4607
4608 retval = options_init_from_string(cf_defaults, cf, command, command_arg,
4609 &errmsg);
4610 if (retval < 0)
4611 goto err;
4612
4613 if (config_line_find(cmdline_only_options, "--no-passphrase")) {
4615 retval = -1;
4616 goto err;
4617 }
4618 }
4619
4620 const config_line_t *format_line = config_line_find(cmdline_only_options,
4621 "--format");
4622 if (format_line) {
4623 if (handle_cmdline_format(command, format_line->value) < 0) {
4624 retval = -1;
4625 goto err;
4626 }
4627 } else {
4628 get_options_mutable()->key_expiration_format =
4629 KEY_EXPIRATION_FORMAT_ISO8601;
4630 }
4631
4632 if (config_line_find(cmdline_only_options, "--newpass")) {
4634 retval = -1;
4635 goto err;
4636 }
4637 }
4638
4639 const config_line_t *fd_line = config_line_find(cmdline_only_options,
4640 "--passphrase-fd");
4641 if (fd_line) {
4642 if (handle_cmdline_passphrase_fd(command, fd_line->value) < 0) {
4643 retval = -1;
4644 goto err;
4645 }
4646 }
4647
4648 const config_line_t *key_line = config_line_find(cmdline_only_options,
4649 "--master-key");
4650 if (key_line) {
4651 if (handle_cmdline_master_key(command, key_line->value) < 0) {
4652 retval = -1;
4653 goto err;
4654 }
4655 }
4656
4657 err:
4658 tor_free(cf);
4659 tor_free(cf_defaults);
4660 if (errmsg) {
4661 log_warn(LD_CONFIG,"%s", errmsg);
4662 tor_free(errmsg);
4663 }
4664 return retval < 0 ? -1 : 0;
4665}
4666
4667/** Load the options from the configuration in <b>cf</b>, validate
4668 * them for consistency and take actions based on them.
4669 *
4670 * Return 0 if success, negative on error:
4671 * * -1 for general errors.
4672 * * -2 for failure to parse/validate,
4673 * * -3 for transition not allowed
4674 * * -4 for error while setting the new options
4675 */
4677options_init_from_string(const char *cf_defaults, const char *cf,
4678 int command, const char *command_arg,
4679 char **msg)
4680{
4681 bool retry = false;
4682 or_options_t *oldoptions, *newoptions, *newdefaultoptions=NULL;
4683 config_line_t *cl;
4684 int retval;
4685 setopt_err_t err = SETOPT_ERR_MISC;
4686 int cf_has_include = 0;
4687 tor_assert(msg);
4688
4689 oldoptions = global_options; /* get_options unfortunately asserts if
4690 this is the first time we run*/
4691
4692 newoptions = options_new();
4693 options_init(newoptions);
4694 newoptions->command = command;
4695 newoptions->command_arg = command_arg ? tor_strdup(command_arg) : NULL;
4696
4697 smartlist_t *opened_files = smartlist_new();
4698 for (int i = 0; i < 2; ++i) {
4699 const char *body = i==0 ? cf_defaults : cf;
4700 if (!body)
4701 continue;
4702
4703 /* get config lines, assign them */
4704 retval = config_get_lines_include(body, &cl, 1,
4705 body == cf ? &cf_has_include : NULL,
4706 opened_files);
4707 if (retval < 0) {
4708 err = SETOPT_ERR_PARSE;
4709 goto err;
4710 }
4711 retval = config_assign(get_options_mgr(), newoptions, cl,
4713 config_free_lines(cl);
4714 if (retval < 0) {
4715 err = SETOPT_ERR_PARSE;
4716 goto err;
4717 }
4718 if (i==0)
4719 newdefaultoptions = config_dup(get_options_mgr(), newoptions);
4720 }
4721
4722 if (newdefaultoptions == NULL) {
4723 newdefaultoptions = config_dup(get_options_mgr(), global_default_options);
4724 }
4725
4726 /* Go through command-line variables too */
4727 {
4728 config_line_t *other_opts = NULL;
4729 if (global_cmdline) {
4730 other_opts = global_cmdline->other_opts;
4731 }
4732 retval = config_assign(get_options_mgr(), newoptions,
4733 other_opts,
4735 }
4736 if (retval < 0) {
4737 err = SETOPT_ERR_PARSE;
4738 goto err;
4739 }
4740
4741 newoptions->IncludeUsed = cf_has_include;
4742 newoptions->FilesOpenedByIncludes = opened_files;
4743 opened_files = NULL; // prevent double-free.
4744
4745 /* If this is a testing network configuration, change defaults
4746 * for a list of dependent config options, and try this function again. */
4747 if (newoptions->TestingTorNetwork && ! testing_network_configured) {
4748 // retry with the testing defaults.
4750 retry = true;
4751 goto err;
4752 }
4753
4754 err = options_validate_and_set(oldoptions, newoptions, msg);
4755 if (err < 0) {
4756 newoptions = NULL; // This was already freed in options_validate_and_set.
4757 goto err;
4758 }
4759
4760 or_options_free(global_default_options);
4761 global_default_options = newdefaultoptions;
4762
4763 return SETOPT_OK;
4764
4765 err:
4767 if (opened_files) {
4768 SMARTLIST_FOREACH(opened_files, char *, f, tor_free(f));
4769 smartlist_free(opened_files);
4770 }
4771 or_options_free(newdefaultoptions);
4772 or_options_free(newoptions);
4773 if (*msg) {
4774 char *old_msg = *msg;
4775 tor_asprintf(msg, "Failed to parse/validate config: %s", old_msg);
4776 tor_free(old_msg);
4777 }
4778 if (retry)
4779 return options_init_from_string(cf_defaults, cf, command, command_arg,
4780 msg);
4781 return err;
4782}
4783
4784/** Return the location for our configuration file. May return NULL.
4785 */
4786const char *
4787get_torrc_fname(int defaults_fname)
4788{
4789 const char *fname = defaults_fname ? torrc_defaults_fname : torrc_fname;
4790
4791 if (fname)
4792 return fname;
4793 else
4794 return get_default_conf_file(defaults_fname);
4795}
4796
4797/** Adjust the address map based on the MapAddress elements in the
4798 * configuration <b>options</b>
4799 */
4800void
4802{
4803 smartlist_t *elts;
4804 config_line_t *opt;
4805 const char *from, *to, *msg;
4806
4808 elts = smartlist_new();
4809 for (opt = options->AddressMap; opt; opt = opt->next) {
4810 smartlist_split_string(elts, opt->value, NULL,
4811 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
4812 if (smartlist_len(elts) < 2) {
4813 log_warn(LD_CONFIG,"MapAddress '%s' has too few arguments. Ignoring.",
4814 opt->value);
4815 goto cleanup;
4816 }
4817
4818 from = smartlist_get(elts,0);
4819 to = smartlist_get(elts,1);
4820
4821 if (to[0] == '.' || from[0] == '.') {
4822 log_warn(LD_CONFIG,"MapAddress '%s' is ambiguous - address starts with a"
4823 "'.'. Ignoring.",opt->value);
4824 goto cleanup;
4825 }
4826
4827 if (addressmap_register_auto(from, to, 0, ADDRMAPSRC_TORRC, &msg) < 0) {
4828 log_warn(LD_CONFIG,"MapAddress '%s' failed: %s. Ignoring.", opt->value,
4829 msg);
4830 goto cleanup;
4831 }
4832
4833 if (smartlist_len(elts) > 2)
4834 log_warn(LD_CONFIG,"Ignoring extra arguments to MapAddress.");
4835
4836 cleanup:
4837 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
4838 smartlist_clear(elts);
4839 }
4840 smartlist_free(elts);
4841}
4842
4843/** As addressmap_register(), but detect the wildcarded status of "from" and
4844 * "to", and do not steal a reference to <b>to</b>. */
4845/* XXXX move to connection_edge.c */
4846int
4847addressmap_register_auto(const char *from, const char *to,
4848 time_t expires,
4849 addressmap_entry_source_t addrmap_source,
4850 const char **msg)
4851{
4852 int from_wildcard = 0, to_wildcard = 0;
4853
4854 *msg = "whoops, forgot the error message";
4855
4856 if (!strcmp(to, "*") || !strcmp(from, "*")) {
4857 *msg = "can't remap from or to *";
4858 return -1;
4859 }
4860 /* Detect asterisks in expressions of type: '*.example.com' */
4861 if (!strncmp(from,"*.",2)) {
4862 from += 2;
4863 from_wildcard = 1;
4864 }
4865 if (!strncmp(to,"*.",2)) {
4866 to += 2;
4867 to_wildcard = 1;
4868 }
4869
4870 if (to_wildcard && !from_wildcard) {
4871 *msg = "can only use wildcard (i.e. '*.') if 'from' address "
4872 "uses wildcard also";
4873 return -1;
4874 }
4875
4876 if (address_is_invalid_destination(to, 1)) {
4877 *msg = "destination is invalid";
4878 return -1;
4879 }
4880
4881 addressmap_register(from, tor_strdup(to), expires, addrmap_source,
4882 from_wildcard, to_wildcard, 0);
4883
4884 return 0;
4885}
4886
4887/**
4888 * As add_file_log, but open the file as appropriate.
4889 */
4890STATIC int
4892 const char *filename, int truncate_log)
4893{
4894 int open_flags = O_WRONLY|O_CREAT;
4895 open_flags |= truncate_log ? O_TRUNC : O_APPEND;
4896
4897 int fd = tor_open_cloexec(filename, open_flags, 0640);
4898 if (fd < 0)
4899 return -1;
4900
4901 return add_file_log(severity, filename, fd);
4902}
4903
4904/**
4905 * Try to set our global log granularity from `options->LogGranularity`,
4906 * adjusting it as needed so that we are an even divisor of a second, or an
4907 * even multiple of seconds. Return 0 on success, -1 on failure.
4908 **/
4909static int
4911 int validate_only)
4912{
4913 if (options->LogTimeGranularity <= 0) {
4914 log_warn(LD_CONFIG, "Log time granularity '%d' has to be positive.",
4915 options->LogTimeGranularity);
4916 return -1;
4917 } else if (1000 % options->LogTimeGranularity != 0 &&
4918 options->LogTimeGranularity % 1000 != 0) {
4919 int granularity = options->LogTimeGranularity;
4920 if (granularity < 40) {
4921 do granularity++;
4922 while (1000 % granularity != 0);
4923 } else if (granularity < 1000) {
4924 granularity = 1000 / granularity;
4925 while (1000 % granularity != 0)
4926 granularity--;
4927 granularity = 1000 / granularity;
4928 } else {
4929 granularity = 1000 * ((granularity / 1000) + 1);
4930 }
4931 log_warn(LD_CONFIG, "Log time granularity '%d' has to be either a "
4932 "divisor or a multiple of 1 second. Changing to "
4933 "'%d'.",
4934 options->LogTimeGranularity, granularity);
4935 if (!validate_only)
4936 set_log_time_granularity(granularity);
4937 } else {
4938 if (!validate_only)
4940 }
4941
4942 return 0;
4943}
4944
4945/**
4946 * Initialize the logs based on the configuration file.
4947 */
4948STATIC int
4949options_init_logs(const or_options_t *old_options, const or_options_t *options,
4950 int validate_only)
4951{
4952 config_line_t *opt;
4953 int ok;
4954 smartlist_t *elts;
4955 int run_as_daemon =
4956#ifdef _WIN32
4957 0;
4958#else
4959 options->RunAsDaemon;
4960#endif
4961
4962 if (options_init_log_granularity(options, validate_only) < 0)
4963 return -1;
4964
4965 ok = 1;
4966 elts = smartlist_new();
4967
4968 if (options->Logs == NULL && !run_as_daemon && !validate_only) {
4969 /* When no logs are given, the default behavior is to log nothing (if
4970 RunAsDaemon is set) or to log based on the quiet level otherwise. */
4972 }
4973
4974 for (opt = options->Logs; opt; opt = opt->next) {
4975 log_severity_list_t *severity;
4976 const char *cfg = opt->value;
4977 severity = tor_malloc_zero(sizeof(log_severity_list_t));
4978 if (parse_log_severity_config(&cfg, severity) < 0) {
4979 log_warn(LD_CONFIG, "Couldn't parse log levels in Log option 'Log %s'",
4980 opt->value);
4981 ok = 0; goto cleanup;
4982 }
4983
4984 smartlist_split_string(elts, cfg, NULL,
4985 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
4986
4987 if (smartlist_len(elts) == 0)
4988 smartlist_add_strdup(elts, "stdout");
4989
4990 if (smartlist_len(elts) == 1 &&
4991 (!strcasecmp(smartlist_get(elts,0), "stdout") ||
4992 !strcasecmp(smartlist_get(elts,0), "stderr"))) {
4993 int err = smartlist_len(elts) &&
4994 !strcasecmp(smartlist_get(elts,0), "stderr");
4995 if (!validate_only) {
4996 if (run_as_daemon) {
4997 log_warn(LD_CONFIG,
4998 "Can't log to %s with RunAsDaemon set; skipping stdout",
4999 err?"stderr":"stdout");
5000 } else {
5001 add_stream_log(severity, err?"<stderr>":"<stdout>",
5002 fileno(err?stderr:stdout));
5003 }
5004 }
5005 goto cleanup;
5006 }
5007 if (smartlist_len(elts) == 1) {
5008 if (!strcasecmp(smartlist_get(elts,0), "syslog")) {
5009#ifdef HAVE_SYSLOG_H
5010 if (!validate_only) {
5011 add_syslog_log(severity, options->SyslogIdentityTag);
5012 }
5013#else
5014 log_warn(LD_CONFIG, "Syslog is not supported on this system. Sorry.");
5015#endif /* defined(HAVE_SYSLOG_H) */
5016 goto cleanup;
5017 }
5018
5019 /* We added this workaround in 0.4.5.x; we can remove it in 0.4.6 or
5020 * later */
5021 if (!strcasecmp(smartlist_get(elts, 0), "android")) {
5022#ifdef HAVE_SYSLOG_H
5023 log_warn(LD_CONFIG, "The android logging API is no longer supported;"
5024 " adding a syslog instead. The 'android' logging "
5025 " type will no longer work in the future.");
5026 if (!validate_only) {
5027 add_syslog_log(severity, options->SyslogIdentityTag);
5028 }
5029#else /* !defined(HAVE_SYSLOG_H) */
5030 log_warn(LD_CONFIG, "The android logging API is no longer supported.");
5031#endif /* defined(HAVE_SYSLOG_H) */
5032 goto cleanup;
5033 }
5034 }
5035
5036 if (smartlist_len(elts) == 2 &&
5037 !strcasecmp(smartlist_get(elts,0), "file")) {
5038 if (!validate_only) {
5039 char *fname = expand_filename(smartlist_get(elts, 1));
5040 /* Truncate if TruncateLogFile is set and we haven't seen this option
5041 line before. */
5042 int truncate_log = 0;
5043 if (options->TruncateLogFile) {
5044 truncate_log = 1;
5045 if (old_options) {
5046 config_line_t *opt2;
5047 for (opt2 = old_options->Logs; opt2; opt2 = opt2->next)
5048 if (!strcmp(opt->value, opt2->value)) {
5049 truncate_log = 0;
5050 break;
5051 }
5052 }
5053 }
5054 if (open_and_add_file_log(severity, fname, truncate_log) < 0) {
5055 log_warn(LD_CONFIG, "Couldn't open file for 'Log %s': %s",
5056 opt->value, strerror(errno));
5057 ok = 0;
5058 }
5059 tor_free(fname);
5060 }
5061 goto cleanup;
5062 }
5063
5064 log_warn(LD_CONFIG, "Bad syntax on file Log option 'Log %s'",
5065 opt->value);
5066 ok = 0; goto cleanup;
5067
5068 cleanup:
5069 SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
5070 smartlist_clear(elts);
5071 tor_free(severity);
5072 }
5073 smartlist_free(elts);
5074
5075 if (ok && !validate_only)
5077
5078 return ok?0:-1;
5079}
5080
5081/** Given a smartlist of SOCKS arguments to be passed to a transport
5082 * proxy in <b>args</b>, validate them and return -1 if they are
5083 * corrupted. Return 0 if they seem OK. */
5084static int
5086{
5087 char *socks_string = NULL;
5088 size_t socks_string_len;
5089
5090 tor_assert(args);
5091 tor_assert(smartlist_len(args) > 0);
5092
5093 SMARTLIST_FOREACH_BEGIN(args, const char *, s) {
5094 if (!string_is_key_value(LOG_WARN, s)) { /* items should be k=v items */
5095 log_warn(LD_CONFIG, "'%s' is not a k=v item.", s);
5096 return -1;
5097 }
5098 } SMARTLIST_FOREACH_END(s);
5099
5100 socks_string = pt_stringify_socks_args(args);
5101 if (!socks_string)
5102 return -1;
5103
5104 socks_string_len = strlen(socks_string);
5105 tor_free(socks_string);
5106
5107 if (socks_string_len > MAX_SOCKS5_AUTH_SIZE_TOTAL) {
5108 log_warn(LD_CONFIG, "SOCKS arguments can't be more than %u bytes (%lu).",
5110 (unsigned long) socks_string_len);
5111 return -1;
5112 }
5113
5114 return 0;
5115}
5116
5117/** Deallocate a bridge_line_t structure. */
5118/* private */ void
5120{
5121 if (!bridge_line)
5122 return;
5123
5124 if (bridge_line->socks_args) {
5125 SMARTLIST_FOREACH(bridge_line->socks_args, char*, s, tor_free(s));
5126 smartlist_free(bridge_line->socks_args);
5127 }
5128 tor_free(bridge_line->transport_name);
5129 tor_free(bridge_line);
5130}
5131
5132/** Parse the contents of a string, <b>line</b>, containing a Bridge line,
5133 * into a bridge_line_t.
5134 *
5135 * Validates that the IP:PORT, fingerprint, and SOCKS arguments (given to the
5136 * Pluggable Transport, if a one was specified) are well-formed.
5137 *
5138 * Returns NULL If the Bridge line could not be validated, and returns a
5139 * bridge_line_t containing the parsed information otherwise.
5140 *
5141 * Bridge line format:
5142 * Bridge [transport] IP:PORT [id-fingerprint] [k=v] [k=v] ...
5143 */
5144/* private */ bridge_line_t *
5145parse_bridge_line(const char *line)
5146{
5147 smartlist_t *items = NULL;
5148 char *addrport=NULL, *fingerprint=NULL;
5149 char *field=NULL;
5150 bridge_line_t *bridge_line = tor_malloc_zero(sizeof(bridge_line_t));
5151
5152 items = smartlist_new();
5153 smartlist_split_string(items, line, NULL,
5154 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5155 if (smartlist_len(items) < 1) {
5156 log_warn(LD_CONFIG, "Too few arguments to Bridge line.");
5157 goto err;
5158 }
5159
5160 /* first field is either a transport name or addrport */
5161 field = smartlist_get(items, 0);
5162 smartlist_del_keeporder(items, 0);
5163
5164 if (string_is_C_identifier(field)) {
5165 /* It's a transport name. */
5166 bridge_line->transport_name = field;
5167 if (smartlist_len(items) < 1) {
5168 log_warn(LD_CONFIG, "Too few items to Bridge line.");
5169 goto err;
5170 }
5171 addrport = smartlist_get(items, 0); /* Next field is addrport then. */
5172 smartlist_del_keeporder(items, 0);
5173 } else {
5174 addrport = field;
5175 }
5176
5177 if (tor_addr_port_parse(LOG_INFO, addrport,
5178 &bridge_line->addr, &bridge_line->port, 443)<0) {
5179 log_warn(LD_CONFIG, "Error parsing Bridge address '%s'", addrport);
5180 goto err;
5181 }
5182
5183 /* If transports are enabled, next field could be a fingerprint or a
5184 socks argument. If transports are disabled, next field must be
5185 a fingerprint. */
5186 if (smartlist_len(items)) {
5187 if (bridge_line->transport_name) { /* transports enabled: */
5188 field = smartlist_get(items, 0);
5189 smartlist_del_keeporder(items, 0);
5190
5191 /* If it's a key=value pair, then it's a SOCKS argument for the
5192 transport proxy... */
5193 if (string_is_key_value(LOG_DEBUG, field)) {
5194 bridge_line->socks_args = smartlist_new();
5195 smartlist_add(bridge_line->socks_args, field);
5196 } else { /* ...otherwise, it's the bridge fingerprint. */
5197 fingerprint = field;
5198 }
5199
5200 } else { /* transports disabled: */
5201 fingerprint = smartlist_join_strings(items, "", 0, NULL);
5202 }
5203 }
5204
5205 /* Handle fingerprint, if it was provided. */
5206 if (fingerprint) {
5207 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
5208 log_warn(LD_CONFIG, "Key digest for Bridge is wrong length.");
5209 goto err;
5210 }
5211 if (base16_decode(bridge_line->digest, DIGEST_LEN,
5212 fingerprint, HEX_DIGEST_LEN) != DIGEST_LEN) {
5213 log_warn(LD_CONFIG, "Unable to decode Bridge key digest.");
5214 goto err;
5215 }
5216 }
5217
5218 /* If we are using transports, any remaining items in the smartlist
5219 should be k=v values. */
5220 if (bridge_line->transport_name && smartlist_len(items)) {
5221 if (!bridge_line->socks_args)
5222 bridge_line->socks_args = smartlist_new();
5223
5224 /* append remaining items of 'items' to 'socks_args' */
5225 smartlist_add_all(bridge_line->socks_args, items);
5226 smartlist_clear(items);
5227
5228 tor_assert(smartlist_len(bridge_line->socks_args) > 0);
5229 }
5230
5231 if (bridge_line->socks_args) {
5232 if (validate_transport_socks_arguments(bridge_line->socks_args) < 0)
5233 goto err;
5234 }
5235
5236 goto done;
5237
5238 err:
5239 bridge_line_free(bridge_line);
5240 bridge_line = NULL;
5241
5242 done:
5243 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5244 smartlist_free(items);
5245 tor_free(addrport);
5246 tor_free(fingerprint);
5247
5248 return bridge_line;
5249}
5250
5251/** Parse the contents of a TCPProxy line from <b>line</b> and put it
5252 * in <b>options</b>. Return 0 if the line is well-formed, and -1 if it
5253 * isn't.
5254 *
5255 * This will mutate only options->TCPProxyProtocol, options->TCPProxyAddr,
5256 * and options->TCPProxyPort.
5257 *
5258 * On error, tor_strdup an error explanation into *<b>msg</b>.
5259 */
5260STATIC int
5261parse_tcp_proxy_line(const char *line, or_options_t *options, char **msg)
5262{
5263 int ret = 0;
5264 tor_assert(line);
5265 tor_assert(options);
5266 tor_assert(msg);
5267
5268 smartlist_t *sl = smartlist_new();
5269 /* Split between the protocol and the address/port. */
5270 smartlist_split_string(sl, line, " ",
5271 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
5272
5273 /* The address/port is not specified. */
5274 if (smartlist_len(sl) < 2) {
5275 *msg = tor_strdup("TCPProxy has no address/port. Please fix.");
5276 goto err;
5277 }
5278
5279 char *protocol_string = smartlist_get(sl, 0);
5280 char *addrport_string = smartlist_get(sl, 1);
5281
5282 /* The only currently supported protocol is 'haproxy'. */
5283 if (strcasecmp(protocol_string, "haproxy")) {
5284 *msg = tor_strdup("TCPProxy protocol is not supported. Currently "
5285 "the only supported protocol is 'haproxy'. "
5286 "Please fix.");
5287 goto err;
5288 } else {
5289 /* Otherwise, set the correct protocol. */
5291 }
5292
5293 /* Parse the address/port. */
5294 if (tor_addr_port_lookup(addrport_string, &options->TCPProxyAddr,
5295 &options->TCPProxyPort) < 0) {
5296 *msg = tor_strdup("TCPProxy address/port failed to parse or resolve. "
5297 "Please fix.");
5298 goto err;
5299 }
5300
5301 /* Success. */
5302 ret = 0;
5303 goto end;
5304
5305 err:
5306 ret = -1;
5307 end:
5308 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
5309 smartlist_free(sl);
5310 return ret;
5311}
5312
5313/** Read the contents of a ClientTransportPlugin or ServerTransportPlugin
5314 * line from <b>line</b>, depending on the value of <b>server</b>. Return 0
5315 * if the line is well-formed, and -1 if it isn't.
5316 *
5317 * If <b>validate_only</b> is 0, the line is well-formed, and the transport is
5318 * needed by some bridge:
5319 * - If it's an external proxy line, add the transport described in the line to
5320 * our internal transport list.
5321 * - If it's a managed proxy line, launch the managed proxy.
5322 */
5323int
5325 const char *line, int validate_only,
5326 int server)
5327{
5328
5329 smartlist_t *items = NULL;
5330 int r;
5331 const char *transports = NULL;
5333 char *type = NULL;
5334 char *addrport = NULL;
5335 tor_addr_t addr;
5336 uint16_t port = 0;
5337 int socks_ver = PROXY_NONE;
5338
5339 /* managed proxy options */
5340 int is_managed = 0;
5341 char **proxy_argv = NULL;
5342 char **tmp = NULL;
5343 int proxy_argc, i;
5344 int is_useless_proxy = 1;
5345
5346 int line_length;
5347
5348 /* Split the line into space-separated tokens */
5349 items = smartlist_new();
5350 smartlist_split_string(items, line, NULL,
5351 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5352 line_length = smartlist_len(items);
5353
5354 if (line_length < 3) {
5355 log_warn(LD_CONFIG,
5356 "Too few arguments on %sTransportPlugin line.",
5357 server ? "Server" : "Client");
5358 goto err;
5359 }
5360
5361 /* Get the first line element, split it to commas into
5362 transport_list (in case it's multiple transports) and validate
5363 the transport names. */
5364 transports = smartlist_get(items, 0);
5366 smartlist_split_string(transport_list, transports, ",",
5367 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
5368 SMARTLIST_FOREACH_BEGIN(transport_list, const char *, transport_name) {
5369 /* validate transport names */
5370 if (!string_is_C_identifier(transport_name)) {
5371 log_warn(LD_CONFIG, "Transport name is not a C identifier (%s).",
5372 transport_name);
5373 goto err;
5374 }
5375
5376 /* see if we actually need the transports provided by this proxy */
5377 if (!validate_only && transport_is_needed(transport_name))
5378 is_useless_proxy = 0;
5379 } SMARTLIST_FOREACH_END(transport_name);
5380
5381 type = smartlist_get(items, 1);
5382 if (!strcmp(type, "exec")) {
5383 is_managed = 1;
5384 } else if (server && !strcmp(type, "proxy")) {
5385 /* 'proxy' syntax only with ServerTransportPlugin */
5386 is_managed = 0;
5387 } else if (!server && !strcmp(type, "socks4")) {
5388 /* 'socks4' syntax only with ClientTransportPlugin */
5389 is_managed = 0;
5390 socks_ver = PROXY_SOCKS4;
5391 } else if (!server && !strcmp(type, "socks5")) {
5392 /* 'socks5' syntax only with ClientTransportPlugin */
5393 is_managed = 0;
5394 socks_ver = PROXY_SOCKS5;
5395 } else {
5396 log_warn(LD_CONFIG,
5397 "Strange %sTransportPlugin type '%s'",
5398 server ? "Server" : "Client", type);
5399 goto err;
5400 }
5401
5402 if (is_managed && options->Sandbox) {
5403 log_warn(LD_CONFIG,
5404 "Managed proxies are not compatible with Sandbox mode."
5405 "(%sTransportPlugin line was %s)",
5406 server ? "Server" : "Client", escaped(line));
5407 goto err;
5408 }
5409
5410 if (is_managed && options->NoExec) {
5411 log_warn(LD_CONFIG,
5412 "Managed proxies are not compatible with NoExec mode; ignoring."
5413 "(%sTransportPlugin line was %s)",
5414 server ? "Server" : "Client", escaped(line));
5415 r = 0;
5416 goto done;
5417 }
5418
5419 if (is_managed) {
5420 /* managed */
5421
5422 if (!server && !validate_only && is_useless_proxy) {
5423 log_info(LD_GENERAL,
5424 "Pluggable transport proxy (%s) does not provide "
5425 "any needed transports and will not be launched.",
5426 line);
5427 }
5428
5429 /*
5430 * If we are not just validating, use the rest of the line as the
5431 * argv of the proxy to be launched. Also, make sure that we are
5432 * only launching proxies that contribute useful transports.
5433 */
5434
5435 if (!validate_only && (server || !is_useless_proxy)) {
5436 proxy_argc = line_length - 2;
5437 tor_assert(proxy_argc > 0);
5438 proxy_argv = tor_calloc((proxy_argc + 1), sizeof(char *));
5439 tmp = proxy_argv;
5440
5441 for (i = 0; i < proxy_argc; i++) {
5442 /* store arguments */
5443 *tmp++ = smartlist_get(items, 2);
5444 smartlist_del_keeporder(items, 2);
5445 }
5446 *tmp = NULL; /* terminated with NULL, just like execve() likes it */
5447
5448 /* kickstart the thing */
5449 if (server) {
5450 pt_kickstart_server_proxy(transport_list, proxy_argv);
5451 } else {
5452 pt_kickstart_client_proxy(transport_list, proxy_argv);
5453 }
5454 }
5455 } else {
5456 /* external */
5457
5458 /* ClientTransportPlugins connecting through a proxy is managed only. */
5459 if (!server && (options->Socks4Proxy || options->Socks5Proxy ||
5460 options->HTTPSProxy || options->TCPProxy)) {
5461 log_warn(LD_CONFIG, "You have configured an external proxy with another "
5462 "proxy type. (Socks4Proxy|Socks5Proxy|HTTPSProxy|"
5463 "TCPProxy)");
5464 goto err;
5465 }
5466
5467 if (smartlist_len(transport_list) != 1) {
5468 log_warn(LD_CONFIG,
5469 "You can't have an external proxy with more than "
5470 "one transport.");
5471 goto err;
5472 }
5473
5474 addrport = smartlist_get(items, 2);
5475
5476 if (tor_addr_port_lookup(addrport, &addr, &port) < 0) {
5477 log_warn(LD_CONFIG,
5478 "Error parsing transport address '%s'", addrport);
5479 goto err;
5480 }
5481
5482 if (!port) {
5483 log_warn(LD_CONFIG,
5484 "Transport address '%s' has no port.", addrport);
5485 goto err;
5486 }
5487
5488 if (!validate_only) {
5489 log_info(LD_DIR, "%s '%s' at %s.",
5490 server ? "Server transport" : "Transport",
5491 transports, fmt_addrport(&addr, port));
5492
5493 if (!server) {
5494 transport_add_from_config(&addr, port,
5495 smartlist_get(transport_list, 0),
5496 socks_ver);
5497 }
5498 }
5499 }
5500
5501 r = 0;
5502 goto done;
5503
5504 err:
5505 r = -1;
5506
5507 done:
5508 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5509 smartlist_free(items);
5510 if (transport_list) {
5512 smartlist_free(transport_list);
5513 }
5514
5515 return r;
5516}
5517
5518/**
5519 * Parse a flag describing an extra dirport for a directory authority.
5520 *
5521 * Right now, the supported format is exactly:
5522 * `{upload,download,voting}=http://[IP:PORT]/`.
5523 * Other URL schemes, and other suffixes, might be supported in the future.
5524 *
5525 * Only call this function if `flag` starts with one of the above strings.
5526 *
5527 * Return 0 on success, and -1 on failure.
5528 *
5529 * If `ds` is provided, then add any parsed dirport to `ds`. If `ds` is NULL,
5530 * take no action other than parsing.
5531 **/
5532static int
5534{
5535 tor_assert(flag);
5536
5538
5539 if (!strcasecmpstart(flag, "upload=")) {
5540 usage = AUTH_USAGE_UPLOAD;
5541 } else if (!strcasecmpstart(flag, "download=")) {
5542 usage = AUTH_USAGE_DOWNLOAD;
5543 } else if (!strcasecmpstart(flag, "vote=")) {
5544 usage = AUTH_USAGE_VOTING;
5545 } else {
5546 // We shouldn't get called with a flag that we don't recognize.
5548 return -1;
5549 }
5550
5551 const char *eq = strchr(flag, '=');
5552 tor_assert(eq);
5553 const char *target = eq + 1;
5554
5555 // Find the part inside the http://{....}/
5556 if (strcmpstart(target, "http://")) {
5557 log_warn(LD_CONFIG, "Unsupported URL scheme in authority flag %s", flag);
5558 return -1;
5559 }
5560 const char *addr = target + strlen("http://");
5561
5562 const char *eos = strchr(addr, '/');
5563 size_t addr_len;
5564 if (eos && strcmp(eos, "/")) {
5565 log_warn(LD_CONFIG, "Unsupported URL prefix in authority flag %s", flag);
5566 return -1;
5567 } else if (eos) {
5568 addr_len = eos - addr;
5569 } else {
5570 addr_len = strlen(addr);
5571 }
5572
5573 // Finally, parse the addr:port part.
5574 char *addr_string = tor_strndup(addr, addr_len);
5575 tor_addr_port_t dirport;
5576 memset(&dirport, 0, sizeof(dirport));
5577 int rv = tor_addr_port_parse(LOG_WARN, addr_string,
5578 &dirport.addr, &dirport.port, -1);
5579 if (ds != NULL && rv == 0) {
5580 trusted_dir_server_add_dirport(ds, usage, &dirport);
5581 } else if (rv == -1) {
5582 log_warn(LD_CONFIG, "Unable to parse address in authority flag %s",flag);
5583 }
5584
5585 tor_free(addr_string);
5586 return rv;
5587}
5588
5589/** Read the contents of a DirAuthority line from <b>line</b>. If
5590 * <b>validate_only</b> is 0, and the line is well-formed, and it
5591 * shares any bits with <b>required_type</b> or <b>required_type</b>
5592 * is NO_DIRINFO (zero), then add the dirserver described in the line
5593 * (minus whatever bits it's missing) as a valid authority.
5594 * Return 0 on success or filtering out by type,
5595 * or -1 if the line isn't well-formed or if we can't add it. */
5596STATIC int
5597parse_dir_authority_line(const char *line, dirinfo_type_t required_type,
5598 int validate_only)
5599{
5600 smartlist_t *items = NULL;
5601 int r;
5602 char *addrport=NULL, *address=NULL, *nickname=NULL, *fingerprint=NULL;
5603 tor_addr_port_t ipv6_addrport, *ipv6_addrport_ptr = NULL;
5604 uint16_t dir_port = 0, or_port = 0;
5605 char digest[DIGEST_LEN];
5606 char v3_digest[DIGEST_LEN];
5607 dirinfo_type_t type = 0;
5608 double weight = 1.0;
5609 smartlist_t *extra_dirports = smartlist_new();
5610
5611 memset(v3_digest, 0, sizeof(v3_digest));
5612
5613 items = smartlist_new();
5614 smartlist_split_string(items, line, NULL,
5615 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5616 if (smartlist_len(items) < 1) {
5617 log_warn(LD_CONFIG, "No arguments on DirAuthority line.");
5618 goto err;
5619 }
5620
5621 if (is_legal_nickname(smartlist_get(items, 0))) {
5622 nickname = smartlist_get(items, 0);
5623 smartlist_del_keeporder(items, 0);
5624 }
5625
5626 while (smartlist_len(items)) {
5627 char *flag = smartlist_get(items, 0);
5628 if (TOR_ISDIGIT(flag[0]))
5629 break;
5630 if (!strcasecmp(flag, "hs") ||
5631 !strcasecmp(flag, "no-hs")) {
5632 log_warn(LD_CONFIG, "The DirAuthority options 'hs' and 'no-hs' are "
5633 "obsolete; you don't need them any more.");
5634 } else if (!strcasecmp(flag, "bridge")) {
5635 type |= BRIDGE_DIRINFO;
5636 } else if (!strcasecmp(flag, "no-v2")) {
5637 /* obsolete, but may still be contained in DirAuthority lines generated
5638 by various tools */;
5639 } else if (!strcasecmpstart(flag, "orport=")) {
5640 int ok;
5641 char *portstring = flag + strlen("orport=");
5642 or_port = (uint16_t) tor_parse_long(portstring, 10, 1, 65535, &ok, NULL);
5643 if (!ok)
5644 log_warn(LD_CONFIG, "Invalid orport '%s' on DirAuthority line.",
5645 portstring);
5646 } else if (!strcmpstart(flag, "weight=")) {
5647 int ok;
5648 const char *wstring = flag + strlen("weight=");
5649 weight = tor_parse_double(wstring, 0, (double)UINT64_MAX, &ok, NULL);
5650 if (!ok) {
5651 log_warn(LD_CONFIG, "Invalid weight '%s' on DirAuthority line.",flag);
5652 weight=1.0;
5653 }
5654 } else if (!strcasecmpstart(flag, "v3ident=")) {
5655 char *idstr = flag + strlen("v3ident=");
5656 if (strlen(idstr) != HEX_DIGEST_LEN ||
5657 base16_decode(v3_digest, DIGEST_LEN,
5658 idstr, HEX_DIGEST_LEN) != DIGEST_LEN) {
5659 log_warn(LD_CONFIG, "Bad v3 identity digest '%s' on DirAuthority line",
5660 flag);
5661 } else {
5663 }
5664 } else if (!strcasecmpstart(flag, "ipv6=")) {
5665 if (ipv6_addrport_ptr) {
5666 log_warn(LD_CONFIG, "Redundant ipv6 addr/port on DirAuthority line");
5667 } else {
5668 if (tor_addr_port_parse(LOG_WARN, flag+strlen("ipv6="),
5669 &ipv6_addrport.addr, &ipv6_addrport.port,
5670 -1) < 0
5671 || tor_addr_family(&ipv6_addrport.addr) != AF_INET6) {
5672 log_warn(LD_CONFIG, "Bad ipv6 addr/port %s on DirAuthority line",
5673 escaped(flag));
5674 goto err;
5675 }
5676 ipv6_addrport_ptr = &ipv6_addrport;
5677 }
5678 } else if (!strcasecmpstart(flag, "upload=") ||
5679 !strcasecmpstart(flag, "download=") ||
5680 !strcasecmpstart(flag, "vote=")) {
5681 // We'll handle these after creating the authority object.
5682 smartlist_add(extra_dirports, flag);
5683 flag = NULL; // prevent double-free.
5684 } else {
5685 log_warn(LD_CONFIG, "Unrecognized flag '%s' on DirAuthority line",
5686 flag);
5687 }
5688 tor_free(flag);
5689 smartlist_del_keeporder(items, 0);
5690 }
5691
5692 if (smartlist_len(items) < 2) {
5693 log_warn(LD_CONFIG, "Too few arguments to DirAuthority line.");
5694 goto err;
5695 }
5696 addrport = smartlist_get(items, 0);
5697 smartlist_del_keeporder(items, 0);
5698
5699 if (tor_addr_port_split(LOG_WARN, addrport, &address, &dir_port) < 0) {
5700 log_warn(LD_CONFIG, "Error parsing DirAuthority address '%s'.", addrport);
5701 goto err;
5702 }
5703
5704 if (!string_is_valid_ipv4_address(address)) {
5705 log_warn(LD_CONFIG, "Error parsing DirAuthority address '%s' "
5706 "(invalid IPv4 address)", address);
5707 goto err;
5708 }
5709
5710 if (!dir_port) {
5711 log_warn(LD_CONFIG, "Missing port in DirAuthority address '%s'",addrport);
5712 goto err;
5713 }
5714
5715 fingerprint = smartlist_join_strings(items, "", 0, NULL);
5716 if (strlen(fingerprint) != HEX_DIGEST_LEN) {
5717 log_warn(LD_CONFIG, "Key digest '%s' for DirAuthority is wrong length %d.",
5718 fingerprint, (int)strlen(fingerprint));
5719 goto err;
5720 }
5721 if (base16_decode(digest, DIGEST_LEN,
5722 fingerprint, HEX_DIGEST_LEN) != DIGEST_LEN) {
5723 log_warn(LD_CONFIG, "Unable to decode DirAuthority key digest.");
5724 goto err;
5725 }
5726
5727 if (validate_only) {
5728 SMARTLIST_FOREACH_BEGIN(extra_dirports, const char *, cp) {
5729 if (parse_dirauth_dirport(NULL, cp) < 0)
5730 goto err;
5731 } SMARTLIST_FOREACH_END(cp);
5732 }
5733
5734 if (!validate_only && (!required_type || required_type & type)) {
5735 dir_server_t *ds;
5736 if (required_type)
5737 type &= required_type; /* pare down what we think of them as an
5738 * authority for. */
5739 log_debug(LD_DIR, "Trusted %d dirserver at %s:%d (%s)", (int)type,
5740 address, (int)dir_port, (char*)smartlist_get(items,0));
5741 if (!(ds = trusted_dir_server_new(nickname, address, dir_port, or_port,
5742 ipv6_addrport_ptr,
5743 digest, v3_digest, type, weight)))
5744 goto err;
5745
5746 SMARTLIST_FOREACH_BEGIN(extra_dirports, const char *, cp) {
5747 if (parse_dirauth_dirport(ds, cp) < 0)
5748 goto err;
5749 } SMARTLIST_FOREACH_END(cp);
5750 dir_server_add(ds);
5751 }
5752
5753 r = 0;
5754 goto done;
5755
5756 err:
5757 r = -1;
5758
5759 done:
5760 SMARTLIST_FOREACH(extra_dirports, char*, s, tor_free(s));
5761 smartlist_free(extra_dirports);
5762 SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5763 smartlist_free(items);
5764 tor_free(addrport);
5765 tor_free(address);
5766 tor_free(nickname);
5767 tor_free(fingerprint);
5768 return r;
5769}
5770
5771/** Read the contents of a FallbackDir line from <b>line</b>. If
5772 * <b>validate_only</b> is 0, and the line is well-formed, then add the
5773 * dirserver described in the line as a fallback directory. Return 0 on
5774 * success, or -1 if the line isn't well-formed or if we can't add it. */
5775int
5777 int validate_only)
5778{
5779 int r = -1;
5780 smartlist_t *items = smartlist_new(), *positional = smartlist_new();
5781 int orport = -1;
5782 uint16_t dirport;
5783 tor_addr_t addr;
5784 int ok;
5785 char id[DIGEST_LEN];
5786 char *address=NULL;
5787 tor_addr_port_t ipv6_addrport, *ipv6_addrport_ptr = NULL;
5788 double weight=1.0;
5789
5790 memset(id, 0, sizeof(id));
5791 smartlist_split_string(items, line, NULL,
5792 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5793 SMARTLIST_FOREACH_BEGIN(items, const char *, cp) {
5794 const char *eq = strchr(cp, '=');
5795 ok = 1;
5796 if (! eq) {
5797 smartlist_add(positional, (char*)cp);
5798 continue;
5799 }
5800 if (!strcmpstart(cp, "orport=")) {
5801 orport = (int)tor_parse_long(cp+strlen("orport="), 10,
5802 1, 65535, &ok, NULL);
5803 } else if (!strcmpstart(cp, "id=")) {
5804 ok = base16_decode(id, DIGEST_LEN, cp+strlen("id="),
5805 strlen(cp)-strlen("id=")) == DIGEST_LEN;
5806 } else if (!strcasecmpstart(cp, "ipv6=")) {
5807 if (ipv6_addrport_ptr) {
5808 log_warn(LD_CONFIG, "Redundant ipv6 addr/port on FallbackDir line");
5809 } else {
5810 if (tor_addr_port_parse(LOG_WARN, cp+strlen("ipv6="),
5811 &ipv6_addrport.addr, &ipv6_addrport.port,
5812 -1) < 0
5813 || tor_addr_family(&ipv6_addrport.addr) != AF_INET6) {
5814 log_warn(LD_CONFIG, "Bad ipv6 addr/port %s on FallbackDir line",
5815 escaped(cp));
5816 goto end;
5817 }
5818 ipv6_addrport_ptr = &ipv6_addrport;
5819 }
5820 } else if (!strcmpstart(cp, "weight=")) {
5821 int num_ok;
5822 const char *wstring = cp + strlen("weight=");
5823 weight = tor_parse_double(wstring, 0, (double)UINT64_MAX, &num_ok, NULL);
5824 if (!num_ok) {
5825 log_warn(LD_CONFIG, "Invalid weight '%s' on FallbackDir line.", cp);
5826 weight=1.0;
5827 }
5828 }
5829
5830 if (!ok) {
5831 log_warn(LD_CONFIG, "Bad FallbackDir option %s", escaped(cp));
5832 goto end;
5833 }
5834 } SMARTLIST_FOREACH_END(cp);
5835
5836 if (smartlist_len(positional) != 1) {
5837 log_warn(LD_CONFIG, "Couldn't parse FallbackDir line %s", escaped(line));
5838 goto end;
5839 }
5840
5841 if (tor_digest_is_zero(id)) {
5842 log_warn(LD_CONFIG, "Missing identity on FallbackDir line");
5843 goto end;
5844 }
5845
5846 if (orport <= 0) {
5847 log_warn(LD_CONFIG, "Missing orport on FallbackDir line");
5848 goto end;
5849 }
5850
5851 if (tor_addr_port_split(LOG_INFO, smartlist_get(positional, 0),
5852 &address, &dirport) < 0 ||
5853 tor_addr_parse(&addr, address)<0) {
5854 log_warn(LD_CONFIG, "Couldn't parse address:port %s on FallbackDir line",
5855 (const char*)smartlist_get(positional, 0));
5856 goto end;
5857 }
5858
5859 if (!validate_only) {
5860 dir_server_t *ds;
5861 ds = fallback_dir_server_new(&addr, dirport, orport, ipv6_addrport_ptr,
5862 id, weight);
5863 if (!ds) {
5864 log_warn(LD_CONFIG, "Couldn't create FallbackDir %s", escaped(line));
5865 goto end;
5866 }
5867 dir_server_add(ds);
5868 }
5869
5870 r = 0;
5871
5872 end:
5873 SMARTLIST_FOREACH(items, char *, cp, tor_free(cp));
5874 smartlist_free(items);
5875 smartlist_free(positional);
5876 tor_free(address);
5877 return r;
5878}
5879
5880/** Allocate and return a new port_cfg_t with reasonable defaults.
5881 *
5882 * <b>namelen</b> is the length of the unix socket name
5883 * (typically the filesystem path), not including the trailing NUL.
5884 * It should be 0 for ports that are not zunix sockets. */
5885port_cfg_t *
5886port_cfg_new(size_t namelen)
5887{
5888 tor_assert(namelen <= SIZE_T_CEILING - sizeof(port_cfg_t) - 1);
5889 port_cfg_t *cfg = tor_malloc_zero(sizeof(port_cfg_t) + namelen + 1);
5890
5891 /* entry_cfg flags */
5892 cfg->entry_cfg.ipv4_traffic = 1;
5893 cfg->entry_cfg.ipv6_traffic = 1;
5894 cfg->entry_cfg.prefer_ipv6 = 0;
5895 cfg->entry_cfg.dns_request = 1;
5896 cfg->entry_cfg.onion_traffic = 1;
5900
5901 /* Other flags default to 0 due to tor_malloc_zero */
5902 return cfg;
5903}
5904
5905/** Free all storage held in <b>port</b> */
5906void
5908{
5909 tor_free(port);
5910}
5911
5912/** Warn for every port in <b>ports</b> of type <b>listener_type</b> that is
5913 * on a publicly routable address. */
5914static void
5916 const char *portname,
5917 const int listener_type)
5918{
5919 SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
5920 if (port->type != listener_type)
5921 continue;
5922 if (port->is_unix_addr) {
5923 /* Unix sockets aren't accessible over a network. */
5924 } else if (!tor_addr_is_internal(&port->addr, 1)) {
5925 log_warn(LD_CONFIG, "You specified a public address '%s' for %sPort. "
5926 "Other people on the Internet might find your computer and "
5927 "use it as an open proxy. Please don't allow this unless you "
5928 "have a good reason.",
5929 fmt_addrport(&port->addr, port->port), portname);
5930 } else if (!tor_addr_is_loopback(&port->addr)) {
5931 log_notice(LD_CONFIG, "You configured a non-loopback address '%s' "
5932 "for %sPort. This allows everybody on your local network to "
5933 "use your machine as a proxy. Make sure this is what you "
5934 "wanted.",
5935 fmt_addrport(&port->addr, port->port), portname);
5936 }
5937 } SMARTLIST_FOREACH_END(port);
5938}
5939
5940/** Given a list of port_cfg_t in <b>ports</b>, warn if any controller port
5941 * there is listening on any non-loopback address. If <b>forbid_nonlocal</b>
5942 * is true, then emit a stronger warning and remove the port from the list.
5943 */
5944static void
5945warn_nonlocal_controller_ports(smartlist_t *ports, unsigned forbid_nonlocal)
5946{
5947 int warned = 0;
5948 SMARTLIST_FOREACH_BEGIN(ports, port_cfg_t *, port) {
5949 if (port->type != CONN_TYPE_CONTROL_LISTENER)
5950 continue;
5951 if (port->is_unix_addr)
5952 continue;
5953 if (!tor_addr_is_loopback(&port->addr)) {
5954 if (forbid_nonlocal) {
5955 if (!warned)
5956 log_warn(LD_CONFIG,
5957 "You have a ControlPort set to accept "
5958 "unauthenticated connections from a non-local address. "
5959 "This means that programs not running on your computer "
5960 "can reconfigure your Tor, without even having to guess a "
5961 "password. That's so bad that I'm closing your ControlPort "
5962 "for you. If you need to control your Tor remotely, try "
5963 "enabling authentication and using a tool like stunnel or "
5964 "ssh to encrypt remote access.");
5965 warned = 1;
5966 port_cfg_free(port);
5967 SMARTLIST_DEL_CURRENT(ports, port);
5968 } else {
5969 log_warn(LD_CONFIG, "You have a ControlPort set to accept "
5970 "connections from a non-local address. This means that "
5971 "programs not running on your computer can reconfigure your "
5972 "Tor. That's pretty bad, since the controller "
5973 "protocol isn't encrypted! Maybe you should just listen on "
5974 "127.0.0.1 and use a tool like stunnel or ssh to encrypt "
5975 "remote connections to your control port.");
5976 return; /* No point in checking the rest */
5977 }
5978 }
5979 } SMARTLIST_FOREACH_END(port);
5980}
5981
5982/**
5983 * Take a string (<b>line</b>) that begins with either an address:port, a
5984 * port, or an AF_UNIX address, optionally quoted, prefixed with
5985 * "unix:". Parse that line, and on success, set <b>addrport_out</b> to a new
5986 * string containing the beginning portion (without prefix). Iff there was a
5987 * unix: prefix, set <b>is_unix_out</b> to true. On success, also set
5988 * <b>rest_out</b> to point to the part of the line after the address portion.
5989 *
5990 * Return 0 on success, -1 on failure.
5991 */
5992int
5994 char **addrport_out,
5995 int *is_unix_out,
5996 const char **rest_out)
5997{
5998 tor_assert(line);
5999 tor_assert(addrport_out);
6000 tor_assert(is_unix_out);
6001 tor_assert(rest_out);
6002
6003 line = eat_whitespace(line);
6004
6005 if (!strcmpstart(line, unix_q_socket_prefix)) {
6006 // It starts with unix:"
6007 size_t sz;
6008 *is_unix_out = 1;
6009 *addrport_out = NULL;
6010 line += strlen(unix_socket_prefix); /* No 'unix:', but keep the quote */
6011 *rest_out = unescape_string(line, addrport_out, &sz);
6012 if (!*rest_out || (*addrport_out && sz != strlen(*addrport_out))) {
6013 tor_free(*addrport_out);
6014 return -1;
6015 }
6016 *rest_out = eat_whitespace(*rest_out);
6017 return 0;
6018 } else {
6019 // Is there a unix: prefix?
6020 if (!strcmpstart(line, unix_socket_prefix)) {
6021 line += strlen(unix_socket_prefix);
6022 *is_unix_out = 1;
6023 } else {
6024 *is_unix_out = 0;
6025 }
6026
6027 const char *end = find_whitespace(line);
6028 if (BUG(!end)) {
6029 end = strchr(line, '\0'); // LCOV_EXCL_LINE -- this can't be NULL
6030 }
6031 tor_assert(end && end >= line);
6032 *addrport_out = tor_strndup(line, end - line);
6033 *rest_out = eat_whitespace(end);
6034 return 0;
6035 }
6036}
6037
6038static void
6039warn_client_dns_cache(const char *option, int disabling)
6040{
6041 if (disabling)
6042 return;
6043
6045 "Client-side DNS caching enables a wide variety of route-"
6046 "capture attacks. If a single bad exit node lies to you about "
6047 "an IP address, caching that address would make you visit "
6048 "an address of the attacker's choice every time you connected "
6049 "to your destination.");
6050}
6051
6052/**
6053 * Parse port configuration for a single port type.
6054 *
6055 * Read entries of the "FooPort" type from the list <b>ports</b>. Syntax is
6056 * that FooPort can have any number of entries of the format
6057 * "[Address:][Port] IsolationOptions".
6058 *
6059 * In log messages, describe the port type as <b>portname</b>.
6060 *
6061 * If no address is specified, default to <b>defaultaddr</b>. If no
6062 * FooPort is given, default to defaultport (if 0, there is no default).
6063 *
6064 * If CL_PORT_NO_STREAM_OPTIONS is set in <b>flags</b>, do not allow stream
6065 * isolation options in the FooPort entries.
6066 *
6067 * If CL_PORT_WARN_NONLOCAL is set in <b>flags</b>, warn if any of the
6068 * ports are not on a local address. If CL_PORT_FORBID_NONLOCAL is set,
6069 * this is a control port with no password set: don't even allow it.
6070 *
6071 * If CL_PORT_SERVER_OPTIONS is set in <b>flags</b>, do not allow stream
6072 * isolation options in the FooPort entries; instead allow the
6073 * server-port option set.
6074 *
6075 * If CL_PORT_TAKES_HOSTNAMES is set in <b>flags</b>, allow the options
6076 * {No,}IPv{4,6}Traffic.
6077 *
6078 * On success, if <b>out</b> is given, add a new port_cfg_t entry to
6079 * <b>out</b> for every port that the client should listen on. Return 0
6080 * on success, -1 on failure.
6081 */
6082int
6084 const config_line_t *ports,
6085 const char *portname,
6086 int listener_type,
6087 const char *defaultaddr,
6088 int defaultport,
6089 const unsigned flags)
6090{
6091 smartlist_t *elts;
6092 int retval = -1;
6093 const unsigned is_control = (listener_type == CONN_TYPE_CONTROL_LISTENER);
6094 const unsigned is_ext_orport = (listener_type == CONN_TYPE_EXT_OR_LISTENER);
6095 const unsigned allow_no_stream_options = flags & CL_PORT_NO_STREAM_OPTIONS;
6096 const unsigned use_server_options = flags & CL_PORT_SERVER_OPTIONS;
6097 const unsigned warn_nonlocal = flags & CL_PORT_WARN_NONLOCAL;
6098 const unsigned forbid_nonlocal = flags & CL_PORT_FORBID_NONLOCAL;
6099 const unsigned default_to_group_writable =
6100 flags & CL_PORT_DFLT_GROUP_WRITABLE;
6101 const unsigned takes_hostnames = flags & CL_PORT_TAKES_HOSTNAMES;
6102 const unsigned is_unix_socket = flags & CL_PORT_IS_UNIXSOCKET;
6103 int got_zero_port=0, got_nonzero_port=0;
6104 char *unix_socket_path = NULL;
6105 port_cfg_t *cfg = NULL;
6106 bool addr_is_explicit = false;
6107 tor_addr_t default_addr = TOR_ADDR_NULL;
6108
6109 /* Parse default address. This can fail for Unix socket so the default_addr
6110 * will simply be made UNSPEC. */
6111 if (defaultaddr) {
6112 tor_addr_parse(&default_addr, defaultaddr);
6113 }
6114
6115 /* If there's no FooPort, then maybe make a default one. */
6116 if (! ports) {
6117 if (defaultport && defaultaddr && out) {
6118 cfg = port_cfg_new(is_unix_socket ? strlen(defaultaddr) : 0);
6119 cfg->type = listener_type;
6120 if (is_unix_socket) {
6122 memcpy(cfg->unix_addr, defaultaddr, strlen(defaultaddr) + 1);
6123 cfg->is_unix_addr = 1;
6124 } else {
6125 cfg->port = defaultport;
6126 tor_addr_parse(&cfg->addr, defaultaddr);
6127 }
6128 smartlist_add(out, cfg);
6129 }
6130 return 0;
6131 }
6132
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;
6137
6138 for (; ports; ports = ports->next) {
6139 tor_addr_t addr;
6140 tor_addr_make_unspec(&addr);
6141 int port, ok,
6142 has_used_unix_socket_only_option = 0,
6143 is_unix_tagged_addr = 0;
6144 uint16_t ptmp=0;
6145 const char *rest_of_line = NULL;
6146
6147 if (port_cfg_line_extract_addrport(ports->value,
6148 &addrport, &is_unix_tagged_addr, &rest_of_line)<0) {
6149 log_warn(LD_CONFIG, "Invalid %sPort line with unparsable address",
6150 portname);
6151 goto err;
6152 }
6153 if (strlen(addrport) == 0) {
6154 log_warn(LD_CONFIG, "Invalid %sPort line with no address", portname);
6155 goto err;
6156 }
6157
6158 /* Split the remainder... */
6159 smartlist_split_string(elts, rest_of_line, NULL,
6160 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
6161
6162 /* Let's start to check if it's a Unix socket path. */
6163 if (is_unix_tagged_addr) {
6164#ifndef HAVE_SYS_UN_H
6165 log_warn(LD_CONFIG, "Unix sockets not supported on this system.");
6166 goto err;
6167#endif
6168 unix_socket_path = addrport;
6169 addrport = NULL;
6170 }
6171
6172 if (unix_socket_path &&
6173 ! conn_listener_type_supports_af_unix(listener_type)) {
6174 log_warn(LD_CONFIG, "%sPort does not support unix sockets", portname);
6175 goto err;
6176 }
6177
6178 if (unix_socket_path) {
6179 port = 1;
6180 } else if (is_unix_socket) {
6181 if (BUG(!addrport))
6182 goto err; // LCOV_EXCL_LINE unreachable, but coverity can't tell that
6183 unix_socket_path = tor_strdup(addrport);
6184 if (!strcmp(addrport, "0"))
6185 port = 0;
6186 else
6187 port = 1;
6188 } else if (!strcasecmp(addrport, "auto")) {
6189 port = CFG_AUTO_PORT;
6190 tor_addr_copy(&addr, &default_addr);
6191 } else if (!strcasecmpend(addrport, ":auto")) {
6192 char *addrtmp = tor_strndup(addrport, strlen(addrport)-5);
6193 port = CFG_AUTO_PORT;
6194 if (tor_addr_port_lookup(addrtmp, &addr, &ptmp)<0 || ptmp) {
6195 log_warn(LD_CONFIG, "Invalid address '%s' for %sPort",
6196 escaped(addrport), portname);
6197 tor_free(addrtmp);
6198 goto err;
6199 }
6200 tor_free(addrtmp);
6201 } else {
6202 /* Try parsing integer port before address, because, who knows?
6203 * "9050" might be a valid address. */
6204 port = (int) tor_parse_long(addrport, 10, 0, 65535, &ok, NULL);
6205 if (ok) {
6206 tor_addr_copy(&addr, &default_addr);
6207 addr_is_explicit = false;
6208 } else if (tor_addr_port_lookup(addrport, &addr, &ptmp) == 0) {
6209 if (ptmp == 0) {
6210 log_warn(LD_CONFIG, "%sPort line has address but no port", portname);
6211 goto err;
6212 }
6213 port = ptmp;
6214 addr_is_explicit = true;
6215 } else {
6216 log_warn(LD_CONFIG, "Couldn't parse address %s for %sPort",
6217 escaped(addrport), portname);
6218 goto err;
6219 }
6220 }
6221
6222 /* Default port_cfg_t object initialization */
6223 cfg = port_cfg_new(unix_socket_path ? strlen(unix_socket_path) : 0);
6224
6225 cfg->explicit_addr = addr_is_explicit;
6226 if (unix_socket_path && default_to_group_writable)
6227 cfg->is_group_writable = 1;
6228
6229 /* Now parse the rest of the options, if any. */
6230 if (use_server_options) {
6231 /* This is a server port; parse advertising options */
6232 SMARTLIST_FOREACH_BEGIN(elts, char *, elt) {
6233 if (!strcasecmp(elt, "NoAdvertise")) {
6234 cfg->server_cfg.no_advertise = 1;
6235 } else if (!strcasecmp(elt, "NoListen")) {
6236 cfg->server_cfg.no_listen = 1;
6237#if 0
6238 /* not implemented yet. */
6239 } else if (!strcasecmp(elt, "AllAddrs")) {
6240
6241 all_addrs = 1;
6242#endif /* 0 */
6243 } else if (!strcasecmp(elt, "IPv4Only")) {
6244 cfg->server_cfg.bind_ipv4_only = 1;
6245 } else if (!strcasecmp(elt, "IPv6Only")) {
6246 cfg->server_cfg.bind_ipv6_only = 1;
6247 } else {
6248 log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
6249 portname, escaped(elt));
6250 }
6251 } SMARTLIST_FOREACH_END(elt);
6252
6253 if (cfg->server_cfg.no_advertise && cfg->server_cfg.no_listen) {
6254 log_warn(LD_CONFIG, "Tried to set both NoListen and NoAdvertise "
6255 "on %sPort line '%s'",
6256 portname, escaped(ports->value));
6257 goto err;
6258 }
6259 if (cfg->server_cfg.bind_ipv4_only &&
6260 cfg->server_cfg.bind_ipv6_only) {
6261 log_warn(LD_CONFIG, "Tried to set both IPv4Only and IPv6Only "
6262 "on %sPort line '%s'",
6263 portname, escaped(ports->value));
6264 goto err;
6265 }
6266 if (cfg->server_cfg.bind_ipv4_only &&
6267 tor_addr_family(&addr) != AF_INET) {
6268 if (cfg->explicit_addr) {
6269 log_warn(LD_CONFIG, "Could not interpret %sPort address as IPv4",
6270 portname);
6271 goto err;
6272 }
6273 /* This ORPort is IPv4Only but the default address is IPv6, ignore it
6274 * since this will be configured with an IPv4 default address. */
6275 goto ignore;
6276 }
6277 if (cfg->server_cfg.bind_ipv6_only &&
6278 tor_addr_family(&addr) != AF_INET6) {
6279 if (cfg->explicit_addr) {
6280 log_warn(LD_CONFIG, "Could not interpret %sPort address as IPv6",
6281 portname);
6282 goto err;
6283 }
6284 /* This ORPort is IPv6Only but the default address is IPv4, ignore it
6285 * since this will be configured with an IPv6 default address. */
6286 goto ignore;
6287 }
6288 } else {
6289 /* This is a client port; parse isolation options */
6290 SMARTLIST_FOREACH_BEGIN(elts, char *, elt) {
6291 int no = 0, isoflag = 0;
6292 const char *elt_orig = elt;
6293
6294 if (!strcasecmpstart(elt, "SessionGroup=")) {
6295 int group = (int)tor_parse_long(elt+strlen("SessionGroup="),
6296 10, 0, INT_MAX, &ok, NULL);
6297 if (!ok || allow_no_stream_options) {
6298 log_warn(LD_CONFIG, "Invalid %sPort option '%s'",
6299 portname, escaped(elt));
6300 goto err;
6301 }
6302 if (cfg->entry_cfg.session_group >= 0) {
6303 log_warn(LD_CONFIG, "Multiple SessionGroup options on %sPort",
6304 portname);
6305 goto err;
6306 }
6307 cfg->entry_cfg.session_group = group;
6308 continue;
6309 }
6310
6311 if (!strcasecmpstart(elt, "No")) {
6312 no = 1;
6313 elt += 2;
6314 }
6315
6316 if (!strcasecmp(elt, "GroupWritable")) {
6317 cfg->is_group_writable = !no;
6318 has_used_unix_socket_only_option = 1;
6319 continue;
6320 } else if (!strcasecmp(elt, "WorldWritable")) {
6321 cfg->is_world_writable = !no;
6322 has_used_unix_socket_only_option = 1;
6323 continue;
6324 } else if (!strcasecmp(elt, "RelaxDirModeCheck")) {
6325 cfg->relax_dirmode_check = !no;
6326 has_used_unix_socket_only_option = 1;
6327 continue;
6328 }
6329
6330 if (allow_no_stream_options) {
6331 log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
6332 portname, escaped(elt));
6333 continue;
6334 }
6335
6336 if (takes_hostnames) {
6337 if (!strcasecmp(elt, "IPv4Traffic")) {
6338 cfg->entry_cfg.ipv4_traffic = ! no;
6339 continue;
6340 } else if (!strcasecmp(elt, "IPv6Traffic")) {
6341 cfg->entry_cfg.ipv6_traffic = ! no;
6342 continue;
6343 } else if (!strcasecmp(elt, "PreferIPv6")) {
6344 cfg->entry_cfg.prefer_ipv6 = ! no;
6345 continue;
6346 } else if (!strcasecmp(elt, "DNSRequest")) {
6347 cfg->entry_cfg.dns_request = ! no;
6348 continue;
6349 } else if (!strcasecmp(elt, "OnionTraffic")) {
6350 cfg->entry_cfg.onion_traffic = ! no;
6351 continue;
6352 } else if (!strcasecmp(elt, "OnionTrafficOnly")) {
6353 /* Only connect to .onion addresses. Equivalent to
6354 * NoDNSRequest, NoIPv4Traffic, NoIPv6Traffic. The option
6355 * NoOnionTrafficOnly is not supported, it's too confusing. */
6356 if (no) {
6357 log_warn(LD_CONFIG, "Unsupported %sPort option 'No%s'. Use "
6358 "DNSRequest, IPv4Traffic, and/or IPv6Traffic instead.",
6359 portname, escaped(elt));
6360 } else {
6361 cfg->entry_cfg.ipv4_traffic = 0;
6362 cfg->entry_cfg.ipv6_traffic = 0;
6363 cfg->entry_cfg.dns_request = 0;
6364 }
6365 continue;
6366 }
6367 }
6368 if (!strcasecmp(elt, "CacheIPv4DNS")) {
6369 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
6370 cfg->entry_cfg.cache_ipv4_answers = ! no;
6371 continue;
6372 } else if (!strcasecmp(elt, "CacheIPv6DNS")) {
6373 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
6374 cfg->entry_cfg.cache_ipv6_answers = ! no;
6375 continue;
6376 } else if (!strcasecmp(elt, "CacheDNS")) {
6377 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
6378 cfg->entry_cfg.cache_ipv4_answers = ! no;
6379 cfg->entry_cfg.cache_ipv6_answers = ! no;
6380 continue;
6381 } else if (!strcasecmp(elt, "UseIPv4Cache")) {
6382 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
6384 continue;
6385 } else if (!strcasecmp(elt, "UseIPv6Cache")) {
6386 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
6387 cfg->entry_cfg.use_cached_ipv6_answers = ! no;
6388 continue;
6389 } else if (!strcasecmp(elt, "UseDNSCache")) {
6390 warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
6392 cfg->entry_cfg.use_cached_ipv6_answers = ! no;
6393 continue;
6394 } else if (!strcasecmp(elt, "PreferIPv6Automap")) {
6395 cfg->entry_cfg.prefer_ipv6_virtaddr = ! no;
6396 continue;
6397 } else if (!strcasecmp(elt, "PreferSOCKSNoAuth")) {
6398 cfg->entry_cfg.socks_prefer_no_auth = ! no;
6399 continue;
6400 } else if (!strcasecmp(elt, "KeepAliveIsolateSOCKSAuth")) {
6401 cfg->entry_cfg.socks_iso_keep_alive = ! no;
6402 continue;
6403 } else if (!strcasecmp(elt, "ExtendedErrors")) {
6404 cfg->entry_cfg.extended_socks5_codes = ! no;
6405 continue;
6406 }
6407
6408 if (!strcasecmpend(elt, "s"))
6409 elt[strlen(elt)-1] = '\0'; /* kill plurals. */
6410
6411 if (!strcasecmp(elt, "IsolateDestPort")) {
6412 isoflag = ISO_DESTPORT;
6413 } else if (!strcasecmp(elt, "IsolateDestAddr")) {
6414 isoflag = ISO_DESTADDR;
6415 } else if (!strcasecmp(elt, "IsolateSOCKSAuth")) {
6416 isoflag = ISO_SOCKSAUTH;
6417 } else if (!strcasecmp(elt, "IsolateClientProtocol")) {
6418 isoflag = ISO_CLIENTPROTO;
6419 } else if (!strcasecmp(elt, "IsolateClientAddr")) {
6420 isoflag = ISO_CLIENTADDR;
6421 } else {
6422 log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
6423 portname, escaped(elt_orig));
6424 }
6425
6426 if (no) {
6427 cfg->entry_cfg.isolation_flags &= ~isoflag;
6428 } else {
6429 cfg->entry_cfg.isolation_flags |= isoflag;
6430 }
6431 } SMARTLIST_FOREACH_END(elt);
6432 }
6433
6434 if (port)
6435 got_nonzero_port = 1;
6436 else
6437 got_zero_port = 1;
6438
6439 if (cfg->entry_cfg.dns_request == 0 &&
6440 listener_type == CONN_TYPE_AP_DNS_LISTENER) {
6441 log_warn(LD_CONFIG, "You have a %sPort entry with DNS disabled; that "
6442 "won't work.", portname);
6443 goto err;
6444 }
6445 if (cfg->entry_cfg.ipv4_traffic == 0 &&
6446 cfg->entry_cfg.ipv6_traffic == 0 &&
6447 cfg->entry_cfg.onion_traffic == 0 &&
6448 listener_type != CONN_TYPE_AP_DNS_LISTENER) {
6449 log_warn(LD_CONFIG, "You have a %sPort entry with all of IPv4 and "
6450 "IPv6 and .onion disabled; that won't work.", portname);
6451 goto err;
6452 }
6453 if (cfg->entry_cfg.dns_request == 1 &&
6454 cfg->entry_cfg.ipv4_traffic == 0 &&
6455 cfg->entry_cfg.ipv6_traffic == 0 &&
6456 listener_type != CONN_TYPE_AP_DNS_LISTENER) {
6457 log_warn(LD_CONFIG, "You have a %sPort entry with DNSRequest enabled, "
6458 "but IPv4 and IPv6 disabled; DNS-based sites won't work.",
6459 portname);
6460 goto err;
6461 }
6462 if (has_used_unix_socket_only_option && !unix_socket_path) {
6463 log_warn(LD_CONFIG, "You have a %sPort entry with GroupWritable, "
6464 "WorldWritable, or RelaxDirModeCheck, but it is not a "
6465 "unix socket.", portname);
6466 goto err;
6467 }
6468 if (!(cfg->entry_cfg.isolation_flags & ISO_SOCKSAUTH) &&
6470 log_warn(LD_CONFIG, "You have a %sPort entry with both "
6471 "NoIsolateSOCKSAuth and KeepAliveIsolateSOCKSAuth set.",
6472 portname);
6473 goto err;
6474 }
6475 if (unix_socket_path &&
6477 /* `IsolateClientAddr` is nonsensical in the context of AF_LOCAL.
6478 * just silently remove the isolation flag.
6479 */
6480 cfg->entry_cfg.isolation_flags &= ~ISO_CLIENTADDR;
6481 }
6482 if (out && port) {
6483 size_t namelen = unix_socket_path ? strlen(unix_socket_path) : 0;
6484 if (unix_socket_path) {
6486 memcpy(cfg->unix_addr, unix_socket_path, namelen + 1);
6487 cfg->is_unix_addr = 1;
6488 tor_free(unix_socket_path);
6489 } else {
6490 tor_addr_copy(&cfg->addr, &addr);
6491 cfg->port = port;
6492 }
6493 cfg->type = listener_type;
6496 smartlist_add(out, cfg);
6497 /* out owns cfg now, don't re-use or free it */
6498 cfg = NULL;
6499 }
6500
6501 ignore:
6502 tor_free(cfg);
6503 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
6504 smartlist_clear(elts);
6505 tor_free(addrport);
6506 tor_free(unix_socket_path);
6507 }
6508
6509 if (warn_nonlocal && out) {
6510 if (is_control)
6511 warn_nonlocal_controller_ports(out, forbid_nonlocal);
6512 else if (is_ext_orport)
6513 port_warn_nonlocal_ext_orports(out, portname);
6514 else
6515 warn_nonlocal_client_ports(out, portname, listener_type);
6516 }
6517
6518 if (got_zero_port && got_nonzero_port) {
6519 log_warn(LD_CONFIG, "You specified a nonzero %sPort along with '%sPort 0' "
6520 "in the same configuration. Did you mean to disable %sPort or "
6521 "not?", portname, portname, portname);
6522 goto err;
6523 }
6524
6525 retval = 0;
6526 err:
6527 /* There are two ways we can error out:
6528 * 1. part way through the loop: cfg needs to be freed;
6529 * 2. ending the loop normally: cfg is always NULL.
6530 * In this case, cfg has either been:
6531 * - added to out, then set to NULL, or
6532 * - freed and set to NULL (because out is NULL, or port is 0).
6533 */
6534 tor_free(cfg);
6535
6536 /* Free the other variables from the loop.
6537 * elts is always non-NULL here, but it may or may not be empty. */
6538 SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
6539 smartlist_free(elts);
6540 tor_free(unix_socket_path);
6541 tor_free(addrport);
6542
6543 return retval;
6544}
6545
6546/** Return the number of ports which are actually going to listen with type
6547 * <b>listenertype</b>. Do not count no_listen ports. Only count unix
6548 * sockets if count_sockets is true. */
6549int
6550port_count_real_listeners(const smartlist_t *ports, int listenertype,
6551 int count_sockets)
6552{
6553 int n = 0;
6554 SMARTLIST_FOREACH_BEGIN(ports, port_cfg_t *, port) {
6555 if (port->server_cfg.no_listen)
6556 continue;
6557 if (!count_sockets && port->is_unix_addr)
6558 continue;
6559 if (port->type != listenertype)
6560 continue;
6561 ++n;
6562 } SMARTLIST_FOREACH_END(port);
6563 return n;
6564}
6565
6566/** Parse all ports from <b>options</b>. On success, set *<b>n_ports_out</b>
6567 * to the number of ports that are listed, update the *Port_set values in
6568 * <b>options</b>, and return 0. On failure, set *<b>msg</b> to a
6569 * description of the problem and return -1.
6570 *
6571 * If <b>validate_only</b> is false, set configured_client_ports to the
6572 * new list of ports parsed from <b>options</b>.
6573 **/
6574STATIC int
6575parse_ports(or_options_t *options, int validate_only,
6576 char **msg, int *n_ports_out,
6577 int *world_writable_control_socket)
6578{
6579 smartlist_t *ports;
6580 int retval = -1;
6581
6582 ports = smartlist_new();
6583
6584 *n_ports_out = 0;
6585
6586 const unsigned gw_flag = options->UnixSocksGroupWritable ?
6587 CL_PORT_DFLT_GROUP_WRITABLE : 0;
6588 if (port_parse_config(ports,
6589 options->SocksPort_lines,
6590 "Socks", CONN_TYPE_AP_LISTENER,
6591 "127.0.0.1", 9050,
6592 ((validate_only ? 0 : CL_PORT_WARN_NONLOCAL)
6593 | CL_PORT_TAKES_HOSTNAMES | gw_flag)) < 0) {
6594 *msg = tor_strdup("Invalid SocksPort configuration");
6595 goto err;
6596 }
6597 if (port_parse_config(ports,
6598 options->DNSPort_lines,
6600 "127.0.0.1", 0,
6601 CL_PORT_WARN_NONLOCAL|CL_PORT_TAKES_HOSTNAMES) < 0) {
6602 *msg = tor_strdup("Invalid DNSPort configuration");
6603 goto err;
6604 }
6605 if (port_parse_config(ports,
6606 options->TransPort_lines,
6608 "127.0.0.1", 0,
6609 CL_PORT_WARN_NONLOCAL) < 0) {
6610 *msg = tor_strdup("Invalid TransPort configuration");
6611 goto err;
6612 }
6613 if (port_parse_config(ports,
6614 options->NATDPort_lines,
6616 "127.0.0.1", 0,
6617 CL_PORT_WARN_NONLOCAL) < 0) {
6618 *msg = tor_strdup("Invalid NatdPort configuration");
6619 goto err;
6620 }
6621 if (port_parse_config(ports,
6622 options->HTTPTunnelPort_lines,
6624 "127.0.0.1", 0,
6625 ((validate_only ? 0 : CL_PORT_WARN_NONLOCAL)
6626 | CL_PORT_TAKES_HOSTNAMES | gw_flag)) < 0) {
6627 *msg = tor_strdup("Invalid HTTPTunnelPort configuration");
6628 goto err;
6629 }
6630 if (metrics_parse_ports(options, ports, msg) < 0) {
6631 goto err;
6632 }
6633
6634 {
6635 unsigned control_port_flags = CL_PORT_NO_STREAM_OPTIONS |
6636 CL_PORT_WARN_NONLOCAL;
6637 const int any_passwords = (options->HashedControlPassword ||
6639 options->CookieAuthentication);
6640 if (! any_passwords)
6641 control_port_flags |= CL_PORT_FORBID_NONLOCAL;
6642 if (options->ControlSocketsGroupWritable)
6643 control_port_flags |= CL_PORT_DFLT_GROUP_WRITABLE;
6644
6645 if (port_parse_config(ports,
6646 options->ControlPort_lines,
6647 "Control", CONN_TYPE_CONTROL_LISTENER,
6648 "127.0.0.1", 0,
6649 control_port_flags) < 0) {
6650 *msg = tor_strdup("Invalid ControlPort configuration");
6651 goto err;
6652 }
6653
6654 if (port_parse_config(ports, options->ControlSocket,
6655 "ControlSocket",
6657 control_port_flags | CL_PORT_IS_UNIXSOCKET) < 0) {
6658 *msg = tor_strdup("Invalid ControlSocket configuration");
6659 goto err;
6660 }
6661 }
6662
6663 if (port_parse_ports_relay(options, msg, ports, &have_low_ports) < 0)
6664 goto err;
6665
6666 *n_ports_out = smartlist_len(ports);
6667
6668 retval = 0;
6669
6670 /* Update the *Port_set options. The !! here is to force a boolean out of
6671 an integer. */
6672 port_update_port_set_relay(options, ports);
6673 options->SocksPort_set =
6675 options->TransPort_set =
6677 options->NATDPort_set =
6679 options->HTTPTunnelPort_set =
6681 /* Use options->ControlSocket to test if a control socket is set */
6682 options->ControlPort_set =
6684 options->DNSPort_set =
6686
6687 if (world_writable_control_socket) {
6688 SMARTLIST_FOREACH(ports, port_cfg_t *, p,
6689 if (p->type == CONN_TYPE_CONTROL_LISTENER &&
6690 p->is_unix_addr &&
6691 p->is_world_writable) {
6692 *world_writable_control_socket = 1;
6693 break;
6694 });
6695 }
6696
6697 if (!validate_only) {
6698 if (configured_ports) {
6700 port_cfg_t *, p, port_cfg_free(p));
6701 smartlist_free(configured_ports);
6702 }
6703 configured_ports = ports;
6704 ports = NULL; /* prevent free below. */
6705 }
6706
6707 err:
6708 if (ports) {
6709 SMARTLIST_FOREACH(ports, port_cfg_t *, p, port_cfg_free(p));
6710 smartlist_free(ports);
6711 }
6712 return retval;
6713}
6714
6715/* Does port bind to IPv4? */
6716int
6717port_binds_ipv4(const port_cfg_t *port)
6718{
6719 return tor_addr_family(&port->addr) == AF_INET ||
6720 (tor_addr_family(&port->addr) == AF_UNSPEC
6721 && !port->server_cfg.bind_ipv6_only);
6722}
6723
6724/* Does port bind to IPv6? */
6725int
6726port_binds_ipv6(const port_cfg_t *port)
6727{
6728 return tor_addr_family(&port->addr) == AF_INET6 ||
6729 (tor_addr_family(&port->addr) == AF_UNSPEC
6730 && !port->server_cfg.bind_ipv4_only);
6731}
6732
6733/** Return a list of port_cfg_t for client ports parsed from the
6734 * options. */
6735MOCK_IMPL(const smartlist_t *,
6737{
6738 if (!configured_ports)
6740 return configured_ports;
6741}
6742
6743/** Return an address:port string representation of the address
6744 * where the first <b>listener_type</b> listener waits for
6745 * connections. Return NULL if we couldn't find a listener. The
6746 * string is allocated on the heap and it's the responsibility of the
6747 * caller to free it after use.
6748 *
6749 * This function is meant to be used by the pluggable transport proxy
6750 * spawning code, please make sure that it fits your purposes before
6751 * using it. */
6752char *
6754{
6755 static const char *ipv4_localhost = "127.0.0.1";
6756 static const char *ipv6_localhost = "[::1]";
6757 const char *address;
6758 uint16_t port;
6759 char *string = NULL;
6760
6761 if (!configured_ports)
6762 return NULL;
6763
6765 if (cfg->server_cfg.no_listen)
6766 continue;
6767
6768 if (cfg->type == listener_type &&
6769 tor_addr_family(&cfg->addr) != AF_UNSPEC) {
6770
6771 /* We found the first listener of the type we are interested in! */
6772
6773 /* If a listener is listening on INADDR_ANY, assume that it's
6774 also listening on 127.0.0.1, and point the transport proxy
6775 there: */
6776 if (tor_addr_is_null(&cfg->addr))
6777 address = tor_addr_is_v4(&cfg->addr) ? ipv4_localhost : ipv6_localhost;
6778 else
6779 address = fmt_and_decorate_addr(&cfg->addr);
6780
6781 /* If a listener is configured with port 'auto', we are forced
6782 to iterate all listener connections and find out in which
6783 port it ended up listening: */
6784 if (cfg->port == CFG_AUTO_PORT) {
6785 port = router_get_active_listener_port_by_type_af(listener_type,
6786 tor_addr_family(&cfg->addr));
6787 if (!port)
6788 return NULL;
6789 } else {
6790 port = cfg->port;
6791 }
6792
6793 tor_asprintf(&string, "%s:%u", address, port);
6794
6795 return string;
6796 }
6797
6798 } SMARTLIST_FOREACH_END(cfg);
6799
6800 return NULL;
6801}
6802
6803/** Find and return the first configured advertised `port_cfg_t` of type @a
6804 * listener_type in @a address_family. */
6805static const port_cfg_t *
6806portconf_get_first_advertised(int listener_type, int address_family)
6807{
6808 const port_cfg_t *first_port = NULL;
6809 const port_cfg_t *first_port_explicit_addr = NULL;
6810
6811 if (address_family == AF_UNSPEC)
6812 return NULL;
6813
6814 const smartlist_t *conf_ports = get_configured_ports();
6815 SMARTLIST_FOREACH_BEGIN(conf_ports, const port_cfg_t *, cfg) {
6816 if (cfg->type == listener_type && !cfg->server_cfg.no_advertise) {
6817 if ((address_family == AF_INET && port_binds_ipv4(cfg)) ||
6818 (address_family == AF_INET6 && port_binds_ipv6(cfg))) {
6819 if (cfg->explicit_addr && !first_port_explicit_addr) {
6820 first_port_explicit_addr = cfg;
6821 } else if (!first_port) {
6822 first_port = cfg;
6823 }
6824 }
6825 }
6826 } SMARTLIST_FOREACH_END(cfg);
6827
6828 /* Prefer the port with the explicit address if any. */
6829 return (first_port_explicit_addr) ? first_port_explicit_addr : first_port;
6830}
6831
6832/** Return the first advertised port of type <b>listener_type</b> in
6833 * <b>address_family</b>. Returns 0 when no port is found, and when passed
6834 * AF_UNSPEC. */
6835int
6836portconf_get_first_advertised_port(int listener_type, int address_family)
6837{
6838 const port_cfg_t *cfg;
6839 cfg = portconf_get_first_advertised(listener_type, address_family);
6840
6841 return cfg ? cfg->port : 0;
6842}
6843
6844/** Return the first advertised address of type <b>listener_type</b> in
6845 * <b>address_family</b>. Returns NULL if there is no advertised address,
6846 * and when passed AF_UNSPEC. */
6847const tor_addr_t *
6848portconf_get_first_advertised_addr(int listener_type, int address_family)
6849{
6850 const port_cfg_t *cfg;
6851 cfg = portconf_get_first_advertised(listener_type, address_family);
6852
6853 return cfg ? &cfg->addr : NULL;
6854}
6855
6856/** Return 1 if a port exists of type <b>listener_type</b> on <b>addr</b> and
6857 * <b>port</b>. If <b>check_wildcard</b> is true, INADDR[6]_ANY and AF_UNSPEC
6858 * addresses match any address of the appropriate family; and port -1 matches
6859 * any port.
6860 * To match auto ports, pass CFG_PORT_AUTO. (Does not match on the actual
6861 * automatically chosen listener ports.) */
6862int
6863port_exists_by_type_addr_port(int listener_type, const tor_addr_t *addr,
6864 int port, int check_wildcard)
6865{
6866 if (!configured_ports || !addr)
6867 return 0;
6869 if (cfg->type == listener_type) {
6870 if (cfg->port == port || (check_wildcard && port == -1)) {
6871 /* Exact match */
6872 if (tor_addr_eq(&cfg->addr, addr)) {
6873 return 1;
6874 }
6875 /* Skip wildcard matches if we're not doing them */
6876 if (!check_wildcard) {
6877 continue;
6878 }
6879 /* Wildcard matches IPv4 */
6880 const int cfg_v4 = port_binds_ipv4(cfg);
6881 const int cfg_any_v4 = tor_addr_is_null(&cfg->addr) && cfg_v4;
6882 const int addr_v4 = tor_addr_family(addr) == AF_INET ||
6883 tor_addr_family(addr) == AF_UNSPEC;
6884 const int addr_any_v4 = tor_addr_is_null(&cfg->addr) && addr_v4;
6885 if ((cfg_any_v4 && addr_v4) || (cfg_v4 && addr_any_v4)) {
6886 return 1;
6887 }
6888 /* Wildcard matches IPv6 */
6889 const int cfg_v6 = port_binds_ipv6(cfg);
6890 const int cfg_any_v6 = tor_addr_is_null(&cfg->addr) && cfg_v6;
6891 const int addr_v6 = tor_addr_family(addr) == AF_INET6 ||
6892 tor_addr_family(addr) == AF_UNSPEC;
6893 const int addr_any_v6 = tor_addr_is_null(&cfg->addr) && addr_v6;
6894 if ((cfg_any_v6 && addr_v6) || (cfg_v6 && addr_any_v6)) {
6895 return 1;
6896 }
6897 }
6898 }
6899 } SMARTLIST_FOREACH_END(cfg);
6900 return 0;
6901}
6902
6903/* Like port_exists_by_type_addr_port, but accepts a host-order IPv4 address
6904 * instead. */
6905int
6906port_exists_by_type_addr32h_port(int listener_type, uint32_t addr_ipv4h,
6907 int port, int check_wildcard)
6908{
6909 tor_addr_t ipv4;
6910 tor_addr_from_ipv4h(&ipv4, addr_ipv4h);
6911 return port_exists_by_type_addr_port(listener_type, &ipv4, port,
6912 check_wildcard);
6913}
6914
6915/** Allocate and return a good value for the DataDirectory based on
6916 * <b>val</b>, which may be NULL. Return NULL on failure. */
6917static char *
6918get_data_directory(const char *val)
6919{
6920#ifdef _WIN32
6921 if (val) {
6922 return tor_strdup(val);
6923 } else {
6924 return tor_strdup(get_windows_conf_root());
6925 }
6926#elif defined(__ANDROID__)
6927 /* Android apps can only use paths that are configured at runtime.
6928 * /data/local/tmp is guaranteed to exist, but is only usable by the
6929 * 'shell' and 'root' users, so this fallback is for debugging only. */
6930 if (val) {
6931 return tor_strdup(val);
6932 } else {
6933 return tor_strdup("/data/local/tmp");
6934 }
6935#else /* !defined(_WIN32) */
6936 const char *d = val;
6937 if (!d)
6938 d = "~/.tor";
6939
6940 if (!strcmpstart(d, "~/")) {
6941 char *fn = expand_filename(d);
6942 if (!fn) {
6943 log_warn(LD_CONFIG,"Failed to expand filename \"%s\".", d);
6944 return NULL;
6945 }
6946 if (!val && !strcmp(fn,"/.tor")) {
6947 /* If our homedir is /, we probably don't want to use it. */
6948 /* Default to LOCALSTATEDIR/tor which is probably closer to what we
6949 * want. */
6950 log_warn(LD_CONFIG,
6951 "Default DataDirectory is \"~/.tor\". This expands to "
6952 "\"%s\", which is probably not what you want. Using "
6953 "\"%s"PATH_SEPARATOR"tor\" instead", fn, LOCALSTATEDIR);
6954 tor_free(fn);
6955 fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor");
6956 }
6957 return fn;
6958 }
6959 return tor_strdup(d);
6960#endif /* defined(_WIN32) */
6961}
6962
6963/** Check and normalize the values of options->{Key,Data,Cache}Directory;
6964 * return 0 if it is sane, -1 otherwise. */
6965static int
6967{
6968 tor_free(options->DataDirectory);
6970 if (!options->DataDirectory)
6971 return -1;
6972 if (strlen(options->DataDirectory) > (512-128)) {
6973 log_warn(LD_CONFIG, "DataDirectory is too long.");
6974 return -1;
6975 }
6976
6977 tor_free(options->KeyDirectory);
6978 if (options->KeyDirectory_option) {
6980 if (!options->KeyDirectory)
6981 return -1;
6982 } else {
6983 /* Default to the data directory's keys subdir */
6984 tor_asprintf(&options->KeyDirectory, "%s"PATH_SEPARATOR"keys",
6985 options->DataDirectory);
6986 }
6987
6988 tor_free(options->CacheDirectory);
6989 if (options->CacheDirectory_option) {
6991 options->CacheDirectory_option);
6992 if (!options->CacheDirectory)
6993 return -1;
6994 } else {
6995 /* Default to the data directory. */
6996 options->CacheDirectory = tor_strdup(options->DataDirectory);
6997 }
6998
6999 tor_free(options->FamilyKeyDirectory);
7000 if (options->FamilyKeyDirectory_option) {
7001 options->FamilyKeyDirectory =
7003 if (!options->FamilyKeyDirectory)
7004 return -1;
7005 } else {
7006 /* Default to the key directory. */
7007 options->FamilyKeyDirectory = tor_strdup(options->KeyDirectory);
7008 }
7009
7010 return 0;
7011}
7012
7013/** This string must remain the same forevermore. It is how we
7014 * recognize that the torrc file doesn't need to be backed up. */
7015#define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
7016 "if you edit it, comments will not be preserved"
7017/** This string can change; it tries to give the reader an idea
7018 * that editing this file by hand is not a good plan. */
7019#define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
7020 "to torrc.orig.1, and Tor will ignore it"
7021
7022/** Save a configuration file for the configuration in <b>options</b>
7023 * into the file <b>fname</b>. If the file already exists, and
7024 * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
7025 * replace it. Return 0 on success, -1 on failure. */
7026static int
7027write_configuration_file(const char *fname, const or_options_t *options)
7028{
7029 char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
7030 int rename_old = 0, r;
7031
7032 if (!fname)
7033 return -1;
7034
7035 switch (file_status(fname)) {
7036 /* create backups of old config files, even if they're empty */
7037 case FN_FILE:
7038 case FN_EMPTY:
7039 old_val = read_file_to_str(fname, 0, NULL);
7040 if (!old_val || strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
7041 rename_old = 1;
7042 }
7043 tor_free(old_val);
7044 break;
7045 case FN_NOENT:
7046 break;
7047 case FN_ERROR:
7048 case FN_DIR:
7049 default:
7050 log_warn(LD_CONFIG,
7051 "Config file \"%s\" is not a file? Failing.", fname);
7052 return -1;
7053 }
7054
7055 if (!(new_conf = options_dump(options, OPTIONS_DUMP_MINIMAL))) {
7056 log_warn(LD_BUG, "Couldn't get configuration string");
7057 goto err;
7058 }
7059
7060 tor_asprintf(&new_val, "%s\n%s\n\n%s",
7062
7063 if (rename_old) {
7064 char *fn_tmp = NULL;
7065 tor_asprintf(&fn_tmp, CONFIG_BACKUP_PATTERN, fname);
7066 file_status_t fn_tmp_status = file_status(fn_tmp);
7067 if (fn_tmp_status == FN_DIR || fn_tmp_status == FN_ERROR) {
7068 log_warn(LD_CONFIG,
7069 "Config backup file \"%s\" is not a file? Failing.", fn_tmp);
7070 tor_free(fn_tmp);
7071 goto err;
7072 }
7073
7074 log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
7075 if (replace_file(fname, fn_tmp) < 0) {
7076 log_warn(LD_FS,
7077 "Couldn't rename configuration file \"%s\" to \"%s\": %s",
7078 fname, fn_tmp, strerror(errno));
7079 tor_free(fn_tmp);
7080 goto err;
7081 }
7082 tor_free(fn_tmp);
7083 }
7084
7085 if (write_str_to_file(fname, new_val, 0) < 0)
7086 goto err;
7087
7088 r = 0;
7089 goto done;
7090 err:
7091 r = -1;
7092 done:
7093 tor_free(new_val);
7094 tor_free(new_conf);
7095 return r;
7096}
7097
7098/**
7099 * Save the current configuration file value to disk. Return 0 on
7100 * success, -1 on failure.
7101 **/
7102int
7104{
7105 /* This fails if we can't write to our configuration file.
7106 *
7107 * If we try falling back to datadirectory or something, we have a better
7108 * chance of saving the configuration, but a better chance of doing
7109 * something the user never expected. */
7111}
7112
7113/** Return the number of cpus configured in <b>options</b>. If we are
7114 * told to auto-detect the number of cpus, return the auto-detected number. */
7115int
7117{
7118 if (options->NumCPUs == 0) {
7119 int n = compute_num_cpus();
7120 return (n >= 1) ? n : 1;
7121 } else {
7122 return options->NumCPUs;
7123 }
7124}
7125
7126/**
7127 * Initialize the libevent library.
7128 */
7129static void
7131{
7133
7134 tor_assert(options);
7135
7137 /* If the kernel complains that some method (say, epoll) doesn't
7138 * exist, we don't care about it, since libevent will cope.
7139 */
7140 suppress_libevent_log_msg("Function not implemented");
7141
7142 memset(&cfg, 0, sizeof(cfg));
7143 cfg.num_cpus = get_num_cpus(options);
7145
7147
7149}
7150
7151/** Return a newly allocated string holding a filename relative to the
7152 * directory in <b>options</b> specified by <b>roottype</b>.
7153 * If <b>sub1</b> is present, it is the first path component after
7154 * the data directory. If <b>sub2</b> is also present, it is the second path
7155 * component after the data directory. If <b>suffix</b> is present, it
7156 * is appended to the filename.
7157 *
7158 * Note: Consider using macros in config.h that wrap this function;
7159 * you should probably never need to call it as-is.
7160 */
7161MOCK_IMPL(char *,
7163 directory_root_t roottype,
7164 const char *sub1, const char *sub2,
7165 const char *suffix))
7166{
7167 tor_assert(options);
7168
7169 const char *rootdir = NULL;
7170 switch (roottype) {
7171 case DIRROOT_DATADIR:
7172 rootdir = options->DataDirectory;
7173 break;
7174 case DIRROOT_CACHEDIR:
7175 rootdir = options->CacheDirectory;
7176 break;
7177 case DIRROOT_KEYDIR:
7178 rootdir = options->KeyDirectory;
7179 break;
7180 default:
7181 tor_assert_unreached();
7182 break;
7183 }
7184 tor_assert(rootdir);
7185
7186 if (!suffix)
7187 suffix = "";
7188
7189 char *fname = NULL;
7190
7191 if (sub1 == NULL) {
7192 tor_asprintf(&fname, "%s%s", rootdir, suffix);
7193 tor_assert(!sub2); /* If sub2 is present, sub1 must be present. */
7194 } else if (sub2 == NULL) {
7195 tor_asprintf(&fname, "%s"PATH_SEPARATOR"%s%s", rootdir, sub1, suffix);
7196 } else {
7197 tor_asprintf(&fname, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s%s",
7198 rootdir, sub1, sub2, suffix);
7199 }
7200
7201 return fname;
7202}
7203
7204/** Check whether the data directory has a private subdirectory
7205 * <b>subdir</b>. If not, try to create it. Return 0 on success,
7206 * -1 otherwise. */
7207int
7209{
7210 char *statsdir = get_datadir_fname(subdir);
7211 int return_val = 0;
7212
7213 if (check_private_dir(statsdir, CPD_CREATE, get_options()->User) < 0) {
7214 log_warn(LD_HIST, "Unable to create %s/ directory!", subdir);
7215 return_val = -1;
7216 }
7217 tor_free(statsdir);
7218 return return_val;
7219}
7220
7221/** Create a file named <b>fname</b> with contents <b>str</b> in the
7222 * subdirectory <b>subdir</b> of the data directory. <b>descr</b>
7223 * should be a short description of the file's content and will be
7224 * used for the warning message, if it's present and the write process
7225 * fails. Return 0 on success, -1 otherwise.*/
7226int
7227write_to_data_subdir(const char* subdir, const char* fname,
7228 const char* str, const char* descr)
7229{
7230 char *filename = get_datadir_fname2(subdir, fname);
7231 int return_val = 0;
7232
7233 if (write_str_to_file(filename, str, 0) < 0) {
7234 log_warn(LD_HIST, "Unable to write %s to disk!", descr ? descr : fname);
7235 return_val = -1;
7236 }
7237 tor_free(filename);
7238 return return_val;
7239}
7240
7241/** Helper to implement GETINFO functions about configuration variables (not
7242 * their values). Given a "config/names" question, set *<b>answer</b> to a
7243 * new string describing the supported configuration variables and their
7244 * types. */
7245int
7247 const char *question, char **answer,
7248 const char **errmsg)
7249{
7250 (void) conn;
7251 (void) errmsg;
7252 if (!strcmp(question, "config/names")) {
7253 smartlist_t *sl = smartlist_new();
7255 SMARTLIST_FOREACH_BEGIN(vars, const config_var_t *, var) {
7256 /* don't tell controller about invisible options */
7257 if (! config_var_is_listable(var))
7258 continue;
7259 const char *type = struct_var_get_typename(&var->member);
7260 if (!type)
7261 continue;
7262 smartlist_add_asprintf(sl, "%s %s\n",var->member.name,type);
7263 } SMARTLIST_FOREACH_END(var);
7264 *answer = smartlist_join_strings(sl, "", 0, NULL);
7265 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
7266 smartlist_free(sl);
7267 smartlist_free(vars);
7268 } else if (!strcmp(question, "config/defaults")) {
7269 smartlist_t *sl = smartlist_new();
7270 int dirauth_lines_seen = 0, fallback_lines_seen = 0;
7271 /* Possibly this should check whether the variables are listable,
7272 * but currently it does not. See ticket 31654. */
7274 SMARTLIST_FOREACH_BEGIN(vars, const config_var_t *, var) {
7275 if (var->initvalue != NULL) {
7276 if (strcmp(var->member.name, "DirAuthority") == 0) {
7277 /*
7278 * Count dirauth lines we have a default for; we'll use the
7279 * count later to decide whether to add the defaults manually
7280 */
7281 ++dirauth_lines_seen;
7282 }
7283 if (strcmp(var->member.name, "FallbackDir") == 0) {
7284 /*
7285 * Similarly count fallback lines, so that we can decide later
7286 * to add the defaults manually.
7287 */
7288 ++fallback_lines_seen;
7289 }
7290 char *val = esc_for_log(var->initvalue);
7291 smartlist_add_asprintf(sl, "%s %s\n",var->member.name,val);
7292 tor_free(val);
7293 }
7294 } SMARTLIST_FOREACH_END(var);
7295 smartlist_free(vars);
7296
7297 if (dirauth_lines_seen == 0) {
7298 /*
7299 * We didn't see any directory authorities with default values,
7300 * so add the list of default authorities manually.
7301 */
7302
7303 /*
7304 * default_authorities is defined earlier in this file and
7305 * is a const char ** NULL-terminated array of dirauth config
7306 * lines.
7307 */
7308 for (const char **i = default_authorities; *i != NULL; ++i) {
7309 char *val = esc_for_log(*i);
7310 smartlist_add_asprintf(sl, "DirAuthority %s\n", val);
7311 tor_free(val);
7312 }
7313 }
7314
7315 if (fallback_lines_seen == 0 &&
7316 get_options()->UseDefaultFallbackDirs == 1) {
7317 /*
7318 * We didn't see any explicitly configured fallback mirrors,
7319 * so add the defaults to the list manually.
7320 *
7321 * default_fallbacks is included earlier in this file and
7322 * is a const char ** NULL-terminated array of fallback config lines.
7323 */
7324 const char **i;
7325
7326 for (i = default_fallbacks; *i != NULL; ++i) {
7327 char *val = esc_for_log(*i);
7328 smartlist_add_asprintf(sl, "FallbackDir %s\n", val);
7329 tor_free(val);
7330 }
7331 }
7332
7333 *answer = smartlist_join_strings(sl, "", 0, NULL);
7334 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
7335 smartlist_free(sl);
7336 }
7337 return 0;
7338}
7339
7340/* Check whether an address has already been set against the options
7341 * depending on address family and destination type. Any existing
7342 * value will lead to a fail, even if it is the same value. If not
7343 * set and not only validating, copy it into this location too.
7344 * Returns 0 on success or -1 if this address is already set.
7345 */
7346static int
7347verify_and_store_outbound_address(sa_family_t family, tor_addr_t *addr,
7348 outbound_addr_t type, or_options_t *options, int validate_only)
7349{
7350 if (type>=OUTBOUND_ADDR_MAX || (family!=AF_INET && family!=AF_INET6)) {
7351 return -1;
7352 }
7353 int fam_index=0;
7354 if (family==AF_INET6) {
7355 fam_index=1;
7356 }
7357 tor_addr_t *dest=&options->OutboundBindAddresses[type][fam_index];
7358 if (!tor_addr_is_null(dest)) {
7359 return -1;
7360 }
7361 if (!validate_only) {
7362 tor_addr_copy(dest, addr);
7363 }
7364 return 0;
7365}
7366
7367/* Parse a list of address lines for a specific destination type.
7368 * Will store them into the options if not validate_only. If a
7369 * problem occurs, a suitable error message is store in msg.
7370 * Returns 0 on success or -1 if any address is already set.
7371 */
7372static int
7373parse_outbound_address_lines(const config_line_t *lines, outbound_addr_t type,
7374 or_options_t *options, int validate_only, char **msg)
7375{
7376 tor_addr_t addr;
7377 sa_family_t family;
7378 while (lines) {
7379 family = tor_addr_parse(&addr, lines->value);
7380 if (verify_and_store_outbound_address(family, &addr, type,
7381 options, validate_only)) {
7382 if (msg)
7383 tor_asprintf(msg, "Multiple%s%s outbound bind addresses "
7384 "configured: %s",
7385 family==AF_INET?" IPv4":(family==AF_INET6?" IPv6":""),
7386 type==OUTBOUND_ADDR_OR?" OR":
7387 (type==OUTBOUND_ADDR_EXIT?" exit":
7388 (type==OUTBOUND_ADDR_PT?" PT":"")), lines->value);
7389 return -1;
7390 }
7391 lines = lines->next;
7392 }
7393 return 0;
7394}
7395
7396/** Parse outbound bind address option lines. If <b>validate_only</b>
7397 * is not 0 update OutboundBindAddresses in <b>options</b>.
7398 * Only one address can be set for any of these values.
7399 * On failure, set <b>msg</b> (if provided) to a newly allocated string
7400 * containing a description of the problem and return -1.
7401 */
7402static int
7403parse_outbound_addresses(or_options_t *options, int validate_only, char **msg)
7404{
7405 if (!validate_only) {
7406 memset(&options->OutboundBindAddresses, 0,
7407 sizeof(options->OutboundBindAddresses));
7408 }
7409
7410 if (parse_outbound_address_lines(options->OutboundBindAddress,
7411 OUTBOUND_ADDR_ANY, options,
7412 validate_only, msg) < 0) {
7413 goto err;
7414 }
7415
7416 if (parse_outbound_address_lines(options->OutboundBindAddressOR,
7417 OUTBOUND_ADDR_OR, options, validate_only,
7418 msg) < 0) {
7419 goto err;
7420 }
7421
7422 if (parse_outbound_address_lines(options->OutboundBindAddressExit,
7423 OUTBOUND_ADDR_EXIT, options, validate_only,
7424 msg) < 0) {
7425 goto err;
7426 }
7427
7428 if (parse_outbound_address_lines(options->OutboundBindAddressPT,
7429 OUTBOUND_ADDR_PT, options, validate_only,
7430 msg) < 0) {
7431 goto err;
7432 }
7433
7434 return 0;
7435 err:
7436 return -1;
7437}
7438
7439/** Load one of the geoip files, <a>family</a> determining which
7440 * one. <a>default_fname</a> is used if on Windows and
7441 * <a>fname</a> equals "<default>". */
7442static void
7444 const char *fname,
7445 const char *default_fname)
7446{
7447 const or_options_t *options = get_options();
7448 const char *msg = "";
7449 int severity = options_need_geoip_info(options, &msg) ? LOG_WARN : LOG_INFO;
7450 int r;
7451
7452#ifdef _WIN32
7453 char *free_fname = NULL; /* Used to hold any temporary-allocated value */
7454 /* XXXX Don't use this "<default>" junk; make our filename options
7455 * understand prefixes somehow. -NM */
7456 if (!strcmp(fname, "<default>")) {
7457 const char *conf_root = get_windows_conf_root();
7458 tor_asprintf(&free_fname, "%s\\%s", conf_root, default_fname);
7459 fname = free_fname;
7460 }
7461 r = geoip_load_file(family, fname, severity);
7462 tor_free(free_fname);
7463#else /* !defined(_WIN32) */
7464 (void)default_fname;
7465 r = geoip_load_file(family, fname, severity);
7466#endif /* defined(_WIN32) */
7467
7468 if (r < 0 && severity == LOG_WARN) {
7469 log_warn(LD_GENERAL, "%s", msg);
7470 }
7471}
7472
7473/** Load geoip files for IPv4 and IPv6 if <a>options</a> and
7474 * <a>old_options</a> indicate we should. */
7475static void
7477 const or_options_t *old_options)
7478{
7479 /* XXXX Reload GeoIPFile on SIGHUP. -NM */
7480
7481 if (options->GeoIPFile &&
7482 ((!old_options || !opt_streq(old_options->GeoIPFile,
7483 options->GeoIPFile))
7484 || !geoip_is_loaded(AF_INET))) {
7485 config_load_geoip_file_(AF_INET, options->GeoIPFile, "geoip");
7486 /* Okay, now we need to maybe change our mind about what is in
7487 * which country. We do this for IPv4 only since that's what we
7488 * store in node->country. */
7490 }
7491 if (options->GeoIPv6File &&
7492 ((!old_options || !opt_streq(old_options->GeoIPv6File,
7493 options->GeoIPv6File))
7494 || !geoip_is_loaded(AF_INET6))) {
7495 config_load_geoip_file_(AF_INET6, options->GeoIPv6File, "geoip6");
7496 }
7497}
7498
7499/** Initialize cookie authentication (used so far by the ControlPort
7500 * and Extended ORPort).
7501 *
7502 * Allocate memory and create a cookie (of length <b>cookie_len</b>)
7503 * in <b>cookie_out</b>.
7504 * Then write it down to <b>fname</b> and prepend it with <b>header</b>.
7505 *
7506 * If <b>group_readable</b> is set, set <b>fname</b> to be readable
7507 * by the default GID.
7508 *
7509 * If the whole procedure was successful, set
7510 * <b>cookie_is_set_out</b> to True. */
7511int
7512init_cookie_authentication(const char *fname, const char *header,
7513 int cookie_len, int group_readable,
7514 uint8_t **cookie_out, int *cookie_is_set_out)
7515{
7516 char cookie_file_str_len = strlen(header) + cookie_len;
7517 char *cookie_file_str = tor_malloc(cookie_file_str_len);
7518 int retval = -1;
7519
7520 /* We don't want to generate a new cookie every time we call
7521 * options_act(). One should be enough. */
7522 if (*cookie_is_set_out) {
7523 retval = 0; /* we are all set */
7524 goto done;
7525 }
7526
7527 /* If we've already set the cookie, free it before re-setting
7528 it. This can happen if we previously generated a cookie, but
7529 couldn't write it to a disk. */
7530 if (*cookie_out)
7531 tor_free(*cookie_out);
7532
7533 /* Generate the cookie */
7534 *cookie_out = tor_malloc(cookie_len);
7535 crypto_rand((char *)*cookie_out, cookie_len);
7536
7537 /* Create the string that should be written on the file. */
7538 memcpy(cookie_file_str, header, strlen(header));
7539 memcpy(cookie_file_str+strlen(header), *cookie_out, cookie_len);
7540 if (write_bytes_to_file(fname, cookie_file_str, cookie_file_str_len, 1)) {
7541 log_warn(LD_FS,"Error writing auth cookie to %s.", escaped(fname));
7542 goto done;
7543 }
7544
7545#ifndef _WIN32
7546 if (group_readable) {
7547 if (chmod(fname, 0640)) {
7548 log_warn(LD_FS,"Unable to make %s group-readable.", escaped(fname));
7549 }
7550 }
7551#else /* defined(_WIN32) */
7552 (void) group_readable;
7553#endif /* !defined(_WIN32) */
7554
7555 /* Success! */
7556 log_info(LD_GENERAL, "Generated auth cookie file in '%s'.", escaped(fname));
7557 *cookie_is_set_out = 1;
7558 retval = 0;
7559
7560 done:
7561 memwipe(cookie_file_str, 0, cookie_file_str_len);
7562 tor_free(cookie_file_str);
7563 return retval;
7564}
7565
7566/**
7567 * Return true if any option is set in <b>options</b> to make us behave
7568 * as a client.
7569 */
7570int
7572{
7573 return (options->SocksPort_set ||
7574 options->TransPort_set ||
7575 options->NATDPort_set ||
7576 options->DNSPort_set ||
7577 options->HTTPTunnelPort_set);
7578}
void tor_addr_copy(tor_addr_t *dest, const tor_addr_t *src)
Definition address.c:933
void tor_addr_make_unspec(tor_addr_t *a)
Definition address.c:225
int string_is_valid_ipv4_address(const char *string)
Definition address.c:2133
int tor_addr_parse(tor_addr_t *addr, const char *src)
Definition address.c:1349
int tor_addr_port_parse(int severity, const char *addrport, tor_addr_t *address_out, uint16_t *port_out, int default_port)
Definition address.c:1857
int tor_addr_is_loopback(const tor_addr_t *addr)
Definition address.c:805
int tor_addr_is_v4(const tor_addr_t *addr)
Definition address.c:750
int tor_addr_port_split(int severity, const char *addrport, char **address_out, uint16_t *port_out)
Definition address.c:1916
int tor_addr_is_null(const tor_addr_t *addr)
Definition address.c:780
const char * fmt_addrport(const tor_addr_t *addr, uint16_t port)
Definition address.c:1199
#define fmt_and_decorate_addr(a)
Definition address.h:245
static sa_family_t tor_addr_family(const tor_addr_t *a)
Definition address.h:189
#define tor_addr_from_ipv4h(dest, v4addr)
Definition address.h:329
#define tor_addr_eq(a, b)
Definition address.h:282
void addressmap_clear_invalid_automaps(const or_options_t *options)
Definition addressmap.c:271
void addressmap_register(const char *address, char *new_address, time_t expires, addressmap_entry_source_t source, const int wildcard_addr, const int wildcard_new_addr, uint64_t stream_id)
Definition addressmap.c:576
void addressmap_clear_configured(void)
Definition addressmap.c:304
void addressmap_clear_excluded_trackexithosts(const or_options_t *options)
Definition addressmap.c:197
int parse_virtual_addr_network(const char *val, sa_family_t family, int validate_only, char **msg)
Definition addressmap.c:814
Header for addressmap.c.
Header file for directory authority mode.
int base16_decode(char *dest, size_t destlen, const char *src, size_t srclen)
Definition binascii.c:506
void mark_bridge_list(void)
Definition bridges.c:84
void sweep_bridge_list(void)
Definition bridges.c:95
int transport_is_needed(const char *transport_name)
Definition bridges.c:555
void bridge_add_from_config(bridge_line_t *bridge_line)
Definition bridges.c:572
Header file for circuitbuild.c.
Header file for channel.c.
void circuit_mark_all_dirty_circs_as_unusable(void)
void circuit_mark_all_unused_circs(void)
Header file for circuitlist.c.
Header file for circuitmux.c.
void cmux_ewma_set_options(const or_options_t *options, const networkstatus_t *consensus)
Header file for circuitmux_ewma.c.
int circuit_build_times_disabled_(const or_options_t *options, int ignore_consensus)
Header file for circuitstats.c.
#define ARRAY_LENGTH(x)
const char * tor_libevent_get_header_version_str(void)
void suppress_libevent_log_msg(const char *msg)
void tor_libevent_initialize(tor_libevent_cfg_t *torcfg)
const char * tor_libevent_get_version_str(void)
void configure_libevent_logging(void)
size_t atomic_counter_exchange(atomic_counter_t *counter, size_t newval)
void atomic_counter_init(atomic_counter_t *counter)
size_t atomic_counter_get(atomic_counter_t *counter)
void atomic_counter_destroy(atomic_counter_t *counter)
const char * tor_compress_version_str(compress_method_t method)
Definition compress.c:447
int tor_compress_supports_method(compress_method_t method)
Definition compress.c:334
const char * tor_compress_header_version_str(compress_method_t method)
Definition compress.c:468
Headers for compress.c.
Read configuration files from disk, with full include support.
int config_ensure_bandwidth_cap(uint64_t *value, const char *desc, char **msg)
Definition config.c:3003
const char * short_name
Definition config.c:2477
static config_line_t * get_options_defaults(void)
Definition config.c:963
static void options_commit_listener_transaction(listener_transaction_t *xn)
Definition config.c:1718
static int compute_group_readable_flag(const char *datadir, const char *subdir, int datadir_gr, int subdir_gr)
Definition config.c:1531
static int validate_transport_socks_arguments(const smartlist_t *args)
Definition config.c:5085
void options_init(or_options_t *options)
Definition config.c:2934
int options_save_current(void)
Definition config.c:7103
static const char * default_fallbacks[]
Definition config.c:799
static void print_usage(void)
Definition config.c:2720
takes_argument_t
Definition config.c:2462
@ ARGUMENT_NONE
Definition config.c:2464
@ ARGUMENT_NECESSARY
Definition config.c:2466
@ ARGUMENT_OPTIONAL
Definition config.c:2468
STATIC void add_default_trusted_dir_authorities(dirinfo_type_t type)
Definition config.c:1224
int pt_parse_transport_line(const or_options_t *options, const char *line, int validate_only, int server)
Definition config.c:5324
#define OR_OPTIONS_MAGIC
Definition config.c:875
const char * get_torrc_fname(int defaults_fname)
Definition config.c:4787
#define MAX_MAX_CIRCUIT_DIRTINESS
Definition config.c:3030
#define MIN_MAX_CIRCUIT_DIRTINESS
Definition config.c:3026
static void warn_nonlocal_client_ports(const smartlist_t *ports, const char *portname, const int listener_type)
Definition config.c:5915
static void set_protocol_warning_severity_level(int warning_severity)
Definition config.c:1189
static int validate_ports_csv(smartlist_t *sl, const char *name, char **msg)
Definition config.c:2979
or_options_t * get_options_mutable(void)
Definition config.c:940
void bridge_line_free_(bridge_line_t *bridge_line)
Definition config.c:5119
int get_num_cpus(const or_options_t *options)
Definition config.c:7116
const smartlist_t * get_configured_ports(void)
Definition config.c:6736
static void list_deprecated_options(void)
Definition config.c:2751
void add_default_fallback_dir_servers(void)
Definition config.c:1238
static const config_var_t option_vars_[]
Definition config.c:316
static atomic_counter_t protocol_warning_severity_level
Definition config.c:1177
static int write_configuration_file(const char *fname, const or_options_t *options)
Definition config.c:7027
STATIC int options_act_reversible(const or_options_t *old_options, char **msg)
Definition config.c:1930
#define MIN_CIRCUIT_STREAM_TIMEOUT
Definition config.c:3034
char * options_get_dir_fname2_suffix(const or_options_t *options, directory_root_t roottype, const char *sub1, const char *sub2, const char *suffix)
Definition config.c:7165
STATIC void or_options_free_(or_options_t *options)
Definition config.c:1068
static bool testing_network_configured
Definition config.c:958
static listener_transaction_t * options_start_listener_transaction(const or_options_t *old_options, char **msg_out)
Definition config.c:1633
static void list_torrc_options(void)
Definition config.c:2733
static int validate_data_directories(or_options_t *options)
Definition config.c:6966
static int in_option_validation
Definition config.c:914
int getinfo_helper_config(control_connection_t *conn, const char *question, char **answer, const char **errmsg)
Definition config.c:7246
static void print_library_versions(void)
Definition config.c:2782
static int opt_streq(const char *s1, const char *s2)
Definition config.c:4193
STATIC int parse_ports(or_options_t *options, int validate_only, char **msg, int *n_ports_out, int *world_writable_control_socket)
Definition config.c:6575
int consider_adding_dir_servers(const or_options_t *options, const or_options_t *old_options)
Definition config.c:1306
static const char * default_authorities[]
Definition config.c:789
static int options_transition_affects_guards(const or_options_t *old_options, const or_options_t *new_options)
Definition config.c:2040
const char * escaped_safe_str_client(const char *address)
Definition config.c:1149
static int warn_if_option_path_is_relative(const char *option, const char *filepath)
Definition config.c:3124
char * get_first_listener_addrport_string(int listener_type)
Definition config.c:6753
#define V_D(member, type, initvalue)
Definition config.c:291
int options_init_from_torrc(int argc, char **argv)
Definition config.c:4493
static or_options_t * global_options
Definition config.c:900
static void config_load_geoip_file_(sa_family_t family, const char *fname, const char *default_fname)
Definition config.c:7443
static const config_abbrev_t option_abbrevs_[]
Definition config.c:195
#define OBSOLETE(varname)
Definition config.c:295
int quiet
Definition config.c:2483
void port_cfg_free_(port_cfg_t *port)
Definition config.c:5907
static int options_switch_id(char **msg_out)
Definition config.c:1499
static int handle_cmdline_master_key(tor_cmdline_mode_t command, const char *value)
Definition config.c:2903
static char * find_torrc_filename(const config_line_t *cmd_arg, int defaults_file, int *using_default_fname, int *ignore_missing_torrc)
Definition config.c:4351
takes_argument_t takes_argument
Definition config.c:2479
STATIC void options_commit_log_transaction(log_transaction_t *xn)
Definition config.c:1846
static void options_rollback_listener_transaction(struct listener_transaction_t *xn)
Definition config.c:1759
STATIC int open_and_add_file_log(const log_severity_list_t *severity, const char *filename, int truncate_log)
Definition config.c:4891
static or_options_t * global_default_options
Definition config.c:903
static void cleanup_protocol_warning_severity_level(void)
Definition config.c:1210
static int parse_outbound_addresses(or_options_t *options, int validate_only, char **msg)
Definition config.c:7403
STATIC int options_create_directories(char **msg_out)
Definition config.c:1557
static char * load_torrc_from_stdin(void)
Definition config.c:4426
const char * safe_str_client_opts(const or_options_t *options, const char *address)
Definition config.c:1109
int portconf_get_first_advertised_port(int listener_type, int address_family)
Definition config.c:6836
static char * torrc_defaults_fname
Definition config.c:907
static int handle_cmdline_passphrase_fd(tor_cmdline_mode_t command, const char *value)
Definition config.c:2879
const char * name
Definition config.c:2475
int port_cfg_line_extract_addrport(const char *line, char **addrport_out, int *is_unix_out, const char **rest_out)
Definition config.c:5993
const char * escaped_safe_str(const char *address)
Definition config.c:1161
int check_or_create_data_subdir(const char *subdir)
Definition config.c:7208
static const char * get_default_conf_file(int defaults_file)
Definition config.c:4317
int options_any_client_port_set(const or_options_t *options)
Definition config.c:7571
or_options_t * options_new(void)
Definition config.c:2924
int create_keys_directory(const or_options_t *options)
Definition config.c:1414
#define MAX_CIRCS_AVAILABLE_TIME
Definition config.c:3022
void init_protocol_warning_severity_level(void)
Definition config.c:1200
static int check_and_create_data_directory(int create, const char *directory, int group_readable, const char *owner, char **msg_out)
Definition config.c:1377
static int handle_cmdline_no_passphrase(tor_cmdline_mode_t command)
Definition config.c:2825
char * options_dump(const or_options_t *options, int how_to_dump)
Definition config.c:2954
int get_protocol_warning_severity_level(void)
Definition config.c:1182
static int warn_about_relative_paths(const or_options_t *options)
Definition config.c:3143
static char * torrc_fname
Definition config.c:905
int parse_dir_fallback_line(const char *line, int validate_only)
Definition config.c:5776
const or_options_t * get_options(void)
Definition config.c:949
int option_is_recognized(const char *key)
Definition config.c:2672
setopt_err_t options_trial_assign(config_line_t *list, unsigned flags, char **msg)
Definition config.c:2703
static int options_init_log_granularity(const or_options_t *options, int validate_only)
Definition config.c:4910
STATIC int options_act(const or_options_t *old_options)
Definition config.c:2074
#define RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT
Definition config.c:3041
STATIC int parse_dir_authority_line(const char *line, dirinfo_type_t required_type, int validate_only)
Definition config.c:5597
#define VAR(varname, conftype, member, initvalue)
Definition config.c:263
STATIC int options_init_logs(const or_options_t *old_options, const or_options_t *options, int validate_only)
Definition config.c:4949
STATIC void options_rollback_log_transaction(log_transaction_t *xn)
Definition config.c:1900
static int validate_dir_servers(const or_options_t *options, const or_options_t *old_options)
Definition config.c:1254
static int handle_cmdline_format(tor_cmdline_mode_t command, const char *value)
Definition config.c:2838
#define VPORT(member)
Definition config.c:304
static bool have_set_startup_options
Definition config.c:916
#define GENERATED_FILE_PREFIX
Definition config.c:7015
void parsed_cmdline_free_(parsed_cmdline_t *cmdline)
Definition config.c:2661
static char * load_torrc_from_disk(const config_line_t *cmd_arg, int defaults_file)
Definition config.c:4441
STATIC const config_mgr_t * get_options_mgr(void)
Definition config.c:923
static const config_format_t options_format
Definition config.c:878
static int options_act_once_on_startup(char **msg_out)
Definition config.c:1439
static void config_maybe_load_geoip_files_(const or_options_t *options, const or_options_t *old_options)
Definition config.c:7476
static const port_cfg_t * portconf_get_first_advertised(int listener_type, int address_family)
Definition config.c:6806
static const struct @0 testing_tor_network_defaults[]
static int options_check_transition_cb(const void *old, const void *new, char **msg)
Definition config.c:4200
int set_options(or_options_t *new_val, char **msg)
Definition config.c:985
static void warn_nonlocal_controller_ports(smartlist_t *ports, unsigned forbid_nonlocal)
Definition config.c:5945
const char * safe_str_opts(const or_options_t *options, const char *address)
Definition config.c:1131
port_cfg_t * port_cfg_new(size_t namelen)
Definition config.c:5886
static int handle_cmdline_newpass(tor_cmdline_mode_t command)
Definition config.c:2866
STATIC log_transaction_t * options_start_log_transaction(const or_options_t *old_options, char **msg_out)
Definition config.c:1811
int addressmap_register_auto(const char *from, const char *to, time_t expires, addressmap_entry_source_t addrmap_source, const char **msg)
Definition config.c:4847
int options_need_geoip_info(const or_options_t *options, const char **reason_out)
Definition config.c:1997
#define UINT64_MAX_STRING
Definition config.c:310
void config_register_addressmaps(const or_options_t *options)
Definition config.c:4801
static void options_clear_cb(const config_mgr_t *mgr, void *opts)
Definition config.c:1030
void config_free_all(void)
Definition config.c:1076
int port_count_real_listeners(const smartlist_t *ports, int listenertype, int count_sockets)
Definition config.c:6550
static void init_libevent(const or_options_t *options)
Definition config.c:7130
bridge_line_t * parse_bridge_line(const char *line)
Definition config.c:5145
int port_exists_by_type_addr_port(int listener_type, const tor_addr_t *addr, int port, int check_wildcard)
Definition config.c:6863
static int parse_dirauth_dirport(dir_server_t *ds, const char *flag)
Definition config.c:5533
tor_cmdline_mode_t command
Definition config.c:2481
int init_cookie_authentication(const char *fname, const char *header, int cookie_len, int group_readable, uint8_t **cookie_out, int *cookie_is_set_out)
Definition config.c:7512
static const struct @1 CMDLINE_ONLY_OPTIONS[]
parsed_cmdline_t * config_parse_commandline(int argc, char **argv, int ignore_errors)
Definition config.c:2557
const tor_addr_t * portconf_get_first_advertised_addr(int listener_type, int address_family)
Definition config.c:6848
setopt_err_t options_init_from_string(const char *cf_defaults, const char *cf, int command, const char *command_arg, char **msg)
Definition config.c:4677
static int options_validate_cb(const void *old_options, void *options, char **msg)
Definition config.c:3288
const char * option_get_canonical_name(const char *key)
Definition config.c:2680
static void list_enabled_modules(void)
Definition config.c:2763
static setopt_err_t options_validate_and_set(const or_options_t *old_options, or_options_t *new_options, char **msg_out)
Definition config.c:3052
static smartlist_t * configured_ports
Definition config.c:911
config_line_t * option_get_assignment(const or_options_t *options, const char *key)
Definition config.c:2688
STATIC int parse_tcp_proxy_line(const char *line, or_options_t *options, char **msg)
Definition config.c:5261
#define DOWNLOAD_SCHEDULE(name)
Definition config.c:187
int write_to_data_subdir(const char *subdir, const char *fname, const char *str, const char *descr)
Definition config.c:7227
static char * get_data_directory(const char *val)
Definition config.c:6918
int port_parse_config(smartlist_t *out, const config_line_t *ports, const char *portname, int listener_type, const char *defaultaddr, int defaultport, const unsigned flags)
Definition config.c:6083
static parsed_cmdline_t * global_cmdline
Definition config.c:909
#define GENERATED_FILE_COMMENT
Definition config.c:7019
Header file for config.c.
#define MAX_DEFAULT_MEMORY_QUEUE_SIZE
Definition config.h:31
#define CONFIG_BACKUP_PATTERN
Definition config.h:48
#define MIN_HEARTBEAT_PERIOD
Definition config.h:25
setopt_err_t
Definition config.h:51
const config_line_t * config_line_find(const config_line_t *lines, const char *key)
Definition confline.c:74
void config_line_append(config_line_t **lst, const char *key, const char *val)
Definition confline.c:32
int config_lines_eq(const config_line_t *a, const config_line_t *b)
Definition confline.c:287
Header for confline.c.
#define CONFIG_LINE_APPEND
Definition confline.h:22
#define CONFIG_LINE_NORMAL
Definition confline.h:19
#define END_OF_CONFIG_VARS
Definition confmacros.h:22
void config_init(const config_mgr_t *mgr, void *options)
Definition confmgt.c:1158
void config_mgr_freeze(config_mgr_t *mgr)
Definition confmgt.c:285
void warn_deprecated_option(const char *what, const char *why)
Definition confmgt.c:692
config_line_t * config_get_changes(const config_mgr_t *mgr, const void *options1, const void *options2)
Definition confmgt.c:1096
bool config_var_is_listable(const config_var_t *var)
Definition confmgt.c:619
const char * config_find_option_name(const config_mgr_t *mgr, const char *key)
Definition confmgt.c:513
const char * config_expand_abbrev(const config_mgr_t *mgr, const char *option, int command_line, int warn_obsolete)
Definition confmgt.c:415
bool config_var_is_settable(const config_var_t *var)
Definition confmgt.c:558
void * config_dup(const config_mgr_t *mgr, const void *old)
Definition confmgt.c:1132
smartlist_t * config_mgr_list_deprecated_vars(const config_mgr_t *mgr)
Definition confmgt.c:333
config_line_t * config_get_assigned_option(const config_mgr_t *mgr, const void *options, const char *key, int escape_val)
Definition confmgt.c:843
smartlist_t * config_mgr_list_vars(const config_mgr_t *mgr)
Definition confmgt.c:319
validation_status_t config_validate(const config_mgr_t *mgr, const void *old_options, void *options, char **msg_out)
Definition confmgt.c:1272
int config_assign(const config_mgr_t *mgr, void *options, config_line_t *list, unsigned config_assign_flags, char **msg)
Definition confmgt.c:937
char * config_dump(const config_mgr_t *mgr, const void *default_options, const void *options, int minimal, int comment_defaults)
Definition confmgt.c:1314
config_mgr_t * config_mgr_new(const config_format_t *toplevel_fmt)
Definition confmgt.c:145
void * config_new(const config_mgr_t *mgr)
Definition confmgt.c:387
Header for confmgt.c.
#define CAL_WARN_DEPRECATIONS
Definition confmgt.h:63
validation_status_t
Definition confmgt.h:83
#define PLURAL(tok)
Definition conftypes.h:272
@ CONFIG_TYPE_FILENAME
Definition conftypes.h:41
char * alloc_http_authenticator(const char *authenticator)
int retry_all_listeners(smartlist_t *new_conns, int close_all_noncontrol)
void connection_bucket_adjust(const or_options_t *options)
int conn_listener_type_supports_af_unix(int type)
Definition connection.c:765
void connection_mark_all_noncontrol_connections(void)
void connection_check_oos(int n_socks, int failed)
Header file for connection.c.
#define CONN_TYPE_AP_HTTP_CONNECT_LISTENER
Definition connection.h:75
#define CONN_TYPE_CONTROL_LISTENER
Definition connection.h:58
#define CONN_TYPE_EXT_OR_LISTENER
Definition connection.h:73
#define MAX_SOCKS5_AUTH_SIZE_TOTAL
Definition connection.h:215
#define MAX_SOCKS5_AUTH_FIELD_SIZE
Definition connection.h:211
#define CONN_TYPE_AP_NATD_LISTENER
Definition connection.h:66
#define CONN_TYPE_AP_LISTENER
Definition connection.h:48
#define CONN_TYPE_AP_DNS_LISTENER
Definition connection.h:68
#define CONN_TYPE_AP_TRANS_LISTENER
Definition connection.h:63
Header file for connection_edge.c.
int address_is_invalid_destination(const char *address, int client)
Base connection structure.
void control_ports_write_to_file(void)
Definition control.c:134
int control_connection_add_local_fd(tor_socket_t sock, unsigned flags)
Definition control.c:95
void monitor_owning_controller_process(const char *process_spec)
Definition control.c:573
Header file for control.c.
smartlist_t * decode_hashed_passwords(config_line_t *passwords)
Header file for control_auth.c.
void control_adjust_event_log_severity(void)
void control_event_logmsg_pending(void)
void control_event_logmsg(int severity, log_domain_mask_t domain, const char *msg)
void control_event_conf_changed(const config_line_t *changes)
Header file for control_events.c.
#define HEX_DIGEST_LEN
int crypto_digest256(char *digest, const char *m, size_t len, digest_algorithm_t algorithm)
const char * crypto_get_library_version_string(void)
const char * crypto_get_library_name(void)
Headers for crypto_init.c.
Headers for crypto_nss_mgt.c.
Headers for crypto_openssl_mgt.c.
void crypto_rand(char *to, size_t n)
Common functions for using (pseudo-)random number generators.
void memwipe(void *mem, uint8_t byte, size_t sz)
Definition crypto_util.c:55
Common functions for cryptographic routines.
const char * unescape_string(const char *s, char **result, size_t *size_out)
Definition cstring.c:30
bool start_daemon_has_been_called(void)
Definition daemon.c:47
int start_daemon(void)
Definition daemon.c:59
int finish_daemon(const char *desired_cwd)
Definition daemon.c:122
Header for daemon.c.
#define DIGEST_LEN
#define DIGEST256_LEN
int check_private_dir(const char *dirname, cpd_check_t check, const char *effective_user)
Definition dir.c:71
unsigned int cpd_check_t
Definition dir.h:20
int options_act_dirauth_stats(const or_options_t *old_options, bool *print_notice_out)
int options_validate_dirauth_mode(const or_options_t *old_options, or_options_t *options, char **msg)
Header for feature/dirauth/dirauth_config.c.
int dirclient_fetches_dir_info_later(const or_options_t *options)
int dirclient_fetches_dir_info_early(const or_options_t *options)
Header for feature/dirclient/dirclient_modes.c.
void trusted_dir_server_add_dirport(dir_server_t *ds, auth_dirport_usage_t usage, const tor_addr_port_t *dirport)
Definition dirlist.c:477
dir_server_t * fallback_dir_server_new(const tor_addr_t *ipv4_addr, uint16_t ipv4_dirport, uint16_t ipv4_orport, const tor_addr_port_t *addrport_ipv6, const char *id_digest, double weight)
Definition dirlist.c:553
void clear_dir_servers(void)
Definition dirlist.c:600
void dir_server_add(dir_server_t *ent)
Definition dirlist.c:564
dir_server_t * trusted_dir_server_new(const char *nickname, const char *address, uint16_t ipv4_dirport, uint16_t ipv4_orport, const tor_addr_port_t *ipv6_addrport, const char *digest, const char *v3_auth_digest, dirinfo_type_t type, double weight)
Definition dirlist.c:419
Header file for dirlist.c.
auth_dirport_usage_t
Definition dirlist.h:22
@ AUTH_USAGE_VOTING
Definition dirlist.h:30
@ AUTH_USAGE_DOWNLOAD
Definition dirlist.h:33
@ AUTH_USAGE_UPLOAD
Definition dirlist.h:28
Header file for dirserv.c.
int dns_reset(void)
Definition dns.c:253
Header file for dns.c.
int guards_update_all(void)
Header file for circuitbuild.c.
char * esc_for_log(const char *s)
Definition escape.c:30
const char * escaped(const char *s)
Definition escape.c:126
Header for ext_orport.c.
file_status_t
Definition files.h:59
int geoip_load_file(sa_family_t family, const char *filename, int severity)
Definition geoip.c:324
int geoip_is_loaded(sa_family_t family)
Definition geoip.c:458
Header file for geoip.c.
Header file for geoip_stats.c.
Header for gethostname.c.
void consider_hibernation(time_t now)
Definition hibernate.c:1107
int we_are_hibernating(void)
Definition hibernate.c:946
Header file for hibernate.c.
int hs_config_client_auth_all(const or_options_t *options, int validate_only)
Definition hs_config.c:710
int hs_config_service_all(const or_options_t *options, int validate_only)
Definition hs_config.c:644
Header file containing configuration ABI/API for the HS subsystem.
Header file containing PoW denial of service defenses for the HS subsystem for all versions.
int hs_service_load_all_keys(void)
uint16_t sa_family_t
Definition inaddr_st.h:77
int string_is_key_value(int severity, const char *string)
Definition keyval.c:25
Header for keyval.c.
const char * tor_libc_get_header_version_str(void)
Definition libc.c:78
const char * tor_libc_get_version_str(void)
Definition libc.c:51
const char * tor_libc_get_name(void)
Definition libc.c:36
Header for lib/osinfo/libc.c.
int add_file_log(const log_severity_list_t *severity, const char *filename, int fd)
Definition log.c:1154
void flush_log_messages_from_startup(void)
Definition log.c:1064
void mark_logs_temp(void)
Definition log.c:1137
void rollback_log_changes(void)
Definition log.c:1125
void logs_set_pending_callback_callback(pending_callback_callback cb)
Definition log.c:973
int add_callback_log(const log_severity_list_t *severity, log_callback cb)
Definition log.c:983
int get_min_log_level(void)
Definition log.c:1432
void set_log_time_granularity(int granularity_msec)
Definition log.c:248
void tor_log_update_sigsafe_err_fds(void)
Definition log.c:626
void add_stream_log(const log_severity_list_t *severity, const char *name, int fd)
Definition log.c:907
void logs_set_domain_logging(int enabled)
Definition log.c:940
int parse_log_severity_config(const char **cfg_ptr, log_severity_list_t *severity_out)
Definition log.c:1328
void close_temp_logs(void)
Definition log.c:1101
#define log_fn(severity, domain, args,...)
Definition log.h:283
#define LOG_DEBUG
Definition log.h:42
#define LD_OR
Definition log.h:92
#define LD_FS
Definition log.h:70
#define LD_BUG
Definition log.h:86
#define LD_HIST
Definition log.h:99
#define LD_NET
Definition log.h:66
#define LD_GENERAL
Definition log.h:62
#define LD_DIR
Definition log.h:88
#define LOG_NOTICE
Definition log.h:50
#define LD_CONFIG
Definition log.h:68
#define LD_CIRC
Definition log.h:82
#define LOG_WARN
Definition log.h:53
#define LOG_INFO
Definition log.h:45
#define bool_eq(a, b)
Definition logic.h:16
int try_locking(const or_options_t *options, int err_if_locked)
Definition main.c:667
int have_lockfile(void)
Definition main.c:703
Header file for main.c.
void note_that_we_maybe_cant_complete_circuits(void)
Definition mainloop.c:235
void tor_shutdown_event_loop_and_exit(int exitcode)
Definition mainloop.c:786
void reset_main_loop_counters(void)
Definition mainloop.c:511
int tor_event_loop_shutdown_is_pending(void)
Definition mainloop.c:814
Header file for mainloop.c.
#define tor_free(p)
Definition malloc.h:56
int get_total_system_memory(size_t *mem_out)
Definition meminfo.c:129
Header for meminfo.c.
int metrics_parse_ports(or_options_t *options, smartlist_t *ports, char **err_msg_out)
Definition metrics.c:175
Header for feature/metrics/metrics.c.
int net_is_disabled(void)
Definition netstatus.c:25
Header for netstatus.c.
#define tor_socket_t
Definition nettypes.h:36
networkstatus_t * networkstatus_get_latest_consensus(void)
void update_consensus_networkstatus_fetch_time(time_t now)
Header file for networkstatus.c.
int is_legal_nickname(const char *s)
Definition nickname.c:19
Header file for nickname.c.
void router_dir_info_changed(void)
Definition nodelist.c:2526
Header file for nodelist.c.
int compute_num_cpus(void)
Definition numcpus.c:85
Header for numcpus.c.
Master header file for Tor-specific functionality.
addressmap_entry_source_t
Definition or.h:1021
@ ADDRMAPSRC_TORRC
Definition or.h:1029
#define CFG_AUTO_PORT
Definition or.h:994
#define ISO_DEFAULT
Definition or.h:978
#define ISO_CLIENTPROTO
Definition or.h:966
#define ISO_DESTADDR
Definition or.h:962
#define SESSION_GROUP_UNSET
Definition or.h:981
#define ISO_SOCKSAUTH
Definition or.h:964
#define ISO_DESTPORT
Definition or.h:960
#define ISO_CLIENTADDR
Definition or.h:968
dirinfo_type_t
Definition or.h:890
@ V3_DIRINFO
Definition or.h:893
@ BRIDGE_DIRINFO
Definition or.h:895
@ EXTRAINFO_DIRINFO
Definition or.h:897
@ MICRODESC_DIRINFO
Definition or.h:899
@ TCP_PROXY_PROTOCOL_HAPROXY
outbound_addr_t
@ OUTBOUND_ADDR_OR
@ OUTBOUND_ADDR_EXIT
@ OUTBOUND_ADDR_ANY
@ OUTBOUND_ADDR_MAX
@ OUTBOUND_ADDR_PT
long tor_parse_long(const char *s, int base, long min, long max, int *ok, char **next)
Definition parse_int.c:59
double tor_parse_double(const char *s, double min, double max, int *ok, char **next)
Definition parse_int.c:97
char * make_path_absolute(const char *fname)
Definition path.c:281
int path_is_relative(const char *filename)
Definition path.c:146
char * expand_filename(const char *filename)
Definition path.c:85
int write_pidfile(const char *filename)
Definition pidfile.c:31
Header for pidfile.c.
int policies_parse_from_options(const or_options_t *options)
Definition policies.c:1268
int validate_addr_policies(const or_options_t *options, char **msg)
Definition policies.c:1152
Header file for policies.c.
Listener port configuration structure.
int tor_asprintf(char **strp, const char *fmt,...)
Definition printf.c:75
int tor_snprintf(char *str, size_t size, const char *format,...)
Definition printf.c:27
void tor_disable_spawning_background_processes(void)
Definition process.c:132
Header for process.c.
int tor_validate_process_specifier(const char *process_spec, const char **msg)
Definition procmon.c:157
Headers for procmon.c.
quiet_level_t quiet_level
Definition quiet_level.c:20
void add_default_log_for_quiet_level(quiet_level_t quiet)
Definition quiet_level.c:24
quiet_level_t
Definition quiet_level.h:16
@ QUIET_SILENT
Definition quiet_level.h:22
@ QUIET_HUSH
Definition quiet_level.h:20
Header file for relay.c.
int port_parse_ports_relay(or_options_t *options, char **msg, smartlist_t *ports_out, int *have_low_ports_out)
int options_validate_relay_mode(const or_options_t *old_options, or_options_t *options, char **msg)
Header for feature/relay/relay_config.c.
int tor_addr_port_lookup(const char *s, tor_addr_t *addr_out, uint16_t *port_out)
Definition resolve.c:252
Header for resolve.c.
int set_max_file_descriptors(rlim_t limit, int *max_out)
Definition restrict.c:183
int tor_disable_debugger_attach(void)
Definition restrict.c:43
int tor_mlockall(void)
Definition restrict.c:117
Header for restrict.c.
uint16_t router_get_active_listener_port_by_type_af(int listener_type, sa_family_t family)
Definition router.c:1498
void refresh_all_country_info(void)
Header file for routerlist.c.
Header file for routermode.c.
int routerset_needs_geoip(const routerset_t *set)
Definition routerset.c:197
routerset_t * routerset_new(void)
Definition routerset.c:51
int routerset_equal(const routerset_t *old, const routerset_t *new)
Definition routerset.c:439
int routerset_is_list(const routerset_t *set)
Definition routerset.c:188
int routerset_add_unknown_ccs(routerset_t **setp, int only_if_some_cc_set)
Definition routerset.c:272
int routerset_parse(routerset_t *target, const char *s, const char *description)
Definition routerset.c:115
int routerset_len(const routerset_t *set)
Definition routerset.c:212
void routerset_union(routerset_t *target, const routerset_t *source)
Definition routerset.c:174
Header file for routerset.c.
int sandbox_is_active(void)
Definition sandbox.c:2371
Header file for sandbox.c.
void scheduler_conf_changed(void)
Definition scheduler.c:452
Header file for scheduler*.c.
int switch_id(const char *user, const unsigned flags)
Definition setuid.c:230
Header for setuid.c.
#define SWITCH_ID_WARN_IF_NO_CAPS
Definition setuid.h:19
#define SWITCH_ID_KEEP_BINDLOW
Definition setuid.h:17
static const char default_fname[]
int smartlist_strings_eq(const smartlist_t *sl1, const smartlist_t *sl2)
Definition smartlist.c:157
void smartlist_add_asprintf(struct smartlist_t *sl, const char *pattern,...)
Definition smartlist.c:36
char * smartlist_join_strings(smartlist_t *sl, const char *join, int terminate, size_t *len_out)
Definition smartlist.c:279
void smartlist_add_all(smartlist_t *s1, const smartlist_t *s2)
void smartlist_add_strdup(struct smartlist_t *sl, const char *string)
smartlist_t * smartlist_new(void)
void smartlist_add(smartlist_t *sl, void *element)
void smartlist_clear(smartlist_t *sl)
void smartlist_del_keeporder(smartlist_t *sl, int idx)
#define SMARTLIST_FOREACH_BEGIN(sl, type, var)
#define SMARTLIST_FOREACH(sl, type, var, cmd)
#define SMARTLIST_DEL_CURRENT(sl, var)
int smartlist_split_string(smartlist_t *sl, const char *str, const char *sep, int flags, int max)
void check_network_configuration(bool server_mode)
Definition socket.c:69
int get_n_open_sockets(void)
Definition socket.c:440
int or_state_loaded(void)
Definition statefile.c:228
int or_state_load(void)
Definition statefile.c:412
Header for statefile.c.
unsigned int command
Definition confline.h:35
unsigned int cache_ipv4_answers
unsigned int socks_iso_keep_alive
unsigned int use_cached_ipv4_answers
unsigned int prefer_ipv6_virtaddr
unsigned int socks_prefer_no_auth
unsigned int extended_socks5_codes
smartlist_t * new_listeners
Definition config.c:1616
unsigned old_conn_limit
Definition config.c:1615
bool logs_initialized
Definition config.c:1792
bool safelogging_changed
Definition config.c:1795
struct config_line_t * ControlPort_lines
tor_addr_t Socks4ProxyAddr
tor_addr_t HTTPProxyAddr
uint64_t MaxMemInQueues
struct config_line_t * MyFamily
struct config_line_t * NATDPort_lines
int DirReqStatistics_option
char * CacheDirectory
struct config_line_t * AlternateBridgeAuthority
tor_addr_t HTTPSProxyAddr
char * SyslogIdentityTag
uint16_t Socks4ProxyPort
int ConnLimit_high_thresh
char * KeyDirectory
struct routerset_t * ExcludeExitNodes
int TestingEnableConnBwEvent
struct config_line_t * OutboundBindAddressExit
struct config_line_t * DNSPort_lines
char * BridgePassword_AuthDigest_
char * BridgePassword
char * FamilyKeyDirectory_option
uint64_t MaxMemInQueues_low_threshold
char * command_arg
struct smartlist_t * RejectPlaintextPorts
char * FamilyKeyDirectory
tor_addr_t TCPProxyAddr
struct config_line_t * Logs
struct routerset_t * ExcludeExitNodesUnion_
int TestingDirConnectionMaxStall
int ClientBootstrapConsensusMaxInProgressTries
char * CookieAuthFile
struct smartlist_t * WarnPlaintextPorts
struct smartlist_t * TrackHostExits
struct smartlist_t * FirewallPorts
int TestingClientMaxIntervalWithoutRequest
struct smartlist_t * Schedulers
tcp_proxy_protocol_t TCPProxyProtocol
int FetchDirInfoExtraEarly
struct config_line_t * ClientTransportPlugin
struct config_line_t * OutboundBindAddressPT
struct smartlist_t * SchedulerTypes_
char * TransProxyType
uint64_t BandwidthRate
struct config_line_t * DirAuthorities
struct config_line_t * Bridges
int ControlSocketsGroupWritable
uint64_t OwningControllerFD
double KISTSockBufSizeFactor
struct config_line_t * ControlSocket
struct config_line_t * OutboundBindAddress
int UseDefaultFallbackDirs
struct config_line_t * AlternateDirAuthority
int DataDirectoryGroupReadable
int CacheDirectoryGroupReadable
int KeyDirectoryGroupReadable
char * KeyDirectory_option
struct smartlist_t * NodeFamilySets
uint64_t ConstrainedSockSize
struct config_line_t * AddressMap
struct smartlist_t * FilesOpenedByIncludes
int HiddenServiceStatistics_option
char * HTTPProxyAuthenticator
struct config_line_t * HashedControlPassword
int TokenBucketRefillInterval
int LearnCircuitBuildTimeout
struct config_line_t * FallbackDir
struct routerset_t * EntryNodes
int HiddenServiceStatistics
int UsingTestNetworkDefaults_
int UnixSocksGroupWritable
struct config_line_t * NodeFamilies
char * VirtualAddrNetworkIPv6
struct routerset_t * ExcludeNodes
char * OwningControllerProcess
struct config_line_t * ReachableORAddresses
char * Socks5ProxyUsername
struct config_line_t * HashedControlSessionPassword
char * Socks5ProxyPassword
int CookieAuthFileGroupReadable
int TestingEnableCellStatsEvent
struct routerset_t * ExitNodes
tor_addr_t Socks5ProxyAddr
struct config_line_t * ReachableDirAddresses
int MaxClientCircuitsPending
tor_addr_t OutboundBindAddresses[OUTBOUND_ADDR_MAX][2]
struct routerset_t * HSLayer2Nodes
char * CacheDirectory_option
uint16_t TCPProxyPort
struct config_line_t * OutboundBindAddressOR
int ReconfigDropsBridgeDescs
int CircuitsAvailableTimeout
uint16_t Socks5ProxyPort
enum or_options_t::@2 TransProxyType_parsed
struct smartlist_t * AutomapHostsSuffixes
int ConnDirectionStatistics
char * VirtualAddrNetworkIPv4
int AutomapHostsOnResolve
char * HTTPSProxyAuthenticator
tor_cmdline_mode_t command
int DisableDebuggerAttachment
uint16_t HTTPProxyPort
struct smartlist_t * FamilyIds
struct config_line_t * TransPort_lines
char * DataDirectory
struct smartlist_t * LongLivedPorts
struct config_line_t * RendConfigLines
struct config_line_t * ReachableAddresses
char * ConfluxClientUX_option
int HiddenServiceSingleHopMode
double PathsNeededToBuildCircuits
int UseEntryGuards_option
struct config_line_t * HTTPTunnelPort_lines
char * DataDirectory_option
int ClientDNSRejectInternalAddresses
struct routerset_t * MiddleNodes
struct config_line_t * SocksPort_lines
uint16_t HTTPSProxyPort
uint64_t BandwidthBurst
struct routerset_t * HSLayer3Nodes
const char * command_arg
Definition config.h:201
quiet_level_t quiet_level
Definition config.h:203
struct config_line_t * cmdline_opts
Definition config.h:194
struct config_line_t * other_opts
Definition config.h:197
tor_cmdline_mode_t command
Definition config.h:199
char unix_addr[FLEXIBLE_ARRAY_MEMBER]
Definition port_cfg_st.h:38
uint8_t type
Definition port_cfg_st.h:23
unsigned is_unix_addr
Definition port_cfg_st.h:24
entry_port_cfg_t entry_cfg
Definition port_cfg_st.h:32
tor_addr_t addr
Definition port_cfg_st.h:20
const char * struct_var_get_typename(const struct_member_t *member)
Definition structvar.c:225
Header for lib/confmgt/structvar.c.
int subsystems_set_options(const config_mgr_t *mgr, struct or_options_t *options)
Definition subsysmgr.c:410
void subsystems_prefork(void)
Definition subsysmgr.c:237
void subsystems_postfork(void)
Definition subsysmgr.c:258
void subsystems_dump_list(void)
Definition subsysmgr.c:301
int subsystems_register_options_formats(config_mgr_t *mgr)
Definition subsysmgr.c:316
Header for subsysmgr.c.
#define STATIC
Definition testsupport.h:32
#define MOCK_IMPL(rv, funcname, arglist)
tor_cmdline_mode_t
@ CMD_HASH_PASSWORD
@ CMD_LIST_FINGERPRINT
@ CMD_VERIFY_CONFIG
@ CMD_RUN_TOR
@ CMD_KEY_EXPIRATION
@ CMD_KEYGEN
@ CMD_DUMP_CONFIG
@ CMD_IMMEDIATE
@ CMD_KEYGEN_FAMILY
#define SIZE_T_CEILING
Definition torint.h:126
Header for version.c.
const char * get_version(void)
Definition version.c:38
Header for feature/relay/transport_config.c.
int pt_proxies_configuration_pending(void)
Definition transports.c:399
int transport_add_from_config(const tor_addr_t *addr, uint16_t port, const char *name, int socks_ver)
Definition transports.c:342
char * pt_stringify_socks_args(const smartlist_t *socks_args)
void pt_configure_remaining_proxies(void)
Definition transports.c:614
void sweep_proxy_list(void)
void mark_transport_list(void)
Definition transports.c:183
static smartlist_t * transport_list
Definition transports.c:146
void sweep_transport_list(void)
Definition transports.c:194
void pt_prepare_proxy_list_for_config_read(void)
Headers for transports.c.
const char * get_uname(void)
Definition uname.c:67
Header for uname.c.
#define tor_assert_nonfatal_unreached()
Definition util_bug.h:177
#define tor_assert(expr)
Definition util_bug.h:103
int strcasecmpstart(const char *s1, const char *s2)
int strcmpstart(const char *s1, const char *s2)
const char * find_whitespace(const char *s)
int strcasecmpend(const char *s1, const char *s2)
int strcmp_opt(const char *s1, const char *s2)
int string_is_C_identifier(const char *string)
const char * eat_whitespace(const char *s)
int tor_digest_is_zero(const char *digest)
Definition util_string.c:98