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