Tor 0.4.9.1-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 {