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