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