tor  0.4.1.0-alpha-dev
config.c
Go to the documentation of this file.
1 /* Copyright (c) 2001 Matej Pfajfar.
2  * Copyright (c) 2001-2004, Roger Dingledine.
3  * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4  * Copyright (c) 2007-2019, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
6 
61 #define CONFIG_PRIVATE
62 #include "core/or/or.h"
63 #include "app/config/config.h"
64 #include "app/config/confparse.h"
65 #include "app/config/statefile.h"
66 #include "app/main/main.h"
67 #include "app/main/subsysmgr.h"
70 #include "core/mainloop/mainloop.h"
71 #include "core/mainloop/netstatus.h"
72 #include "core/or/channel.h"
73 #include "core/or/circuitbuild.h"
74 #include "core/or/circuitlist.h"
75 #include "core/or/circuitmux.h"
77 #include "core/or/circuitstats.h"
79 #include "core/or/connection_or.h"
80 #include "core/or/dos.h"
81 #include "core/or/policies.h"
82 #include "core/or/relay.h"
83 #include "core/or/scheduler.h"
84 #include "feature/client/addressmap.h"
85 #include "feature/client/bridges.h"
91 #include "feature/dirauth/bwauth.h"
93 #include "feature/dircache/consdiffmgr.h"
97 #include "feature/hs/hs_config.h"
103 #include "feature/nodelist/routerset.h"
104 #include "feature/relay/dns.h"
105 #include "feature/relay/ext_orport.h"
107 #include "feature/rend/rendclient.h"
109 #include "lib/geoip/geoip.h"
111 #include "feature/stats/predict_ports.h"
112 #include "feature/stats/rephist.h"
113 #include "lib/compress/compress.h"
117 #include "lib/encoding/confline.h"
118 #include "lib/net/resolve.h"
119 #include "lib/sandbox/sandbox.h"
120 #include "lib/version/torversion.h"
121 
122 #ifdef ENABLE_NSS
124 #else
126 #endif
127 
128 #ifdef _WIN32
129 #include <shlobj.h>
130 #endif
131 #ifdef HAVE_FCNTL_H
132 #include <fcntl.h>
133 #endif
134 #ifdef HAVE_SYS_STAT_H
135 #include <sys/stat.h>
136 #endif
137 #ifdef HAVE_SYS_PARAM_H
138 #include <sys/param.h>
139 #endif
140 #ifdef HAVE_UNISTD_H
141 #include <unistd.h>
142 #endif
143 
144 #include "lib/meminfo/meminfo.h"
145 #include "lib/osinfo/uname.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/dirvote.h"
159 #include "feature/dirauth/dirauth_periodic.h"
162 
163 #include "core/or/connection_st.h"
164 #include "core/or/port_cfg_st.h"
165 
166 #ifdef HAVE_SYSTEMD
167 # if defined(__COVERITY__) && !defined(__INCLUDE_LEVEL__)
168 /* Systemd's use of gcc's __INCLUDE_LEVEL__ extension macro appears to confuse
169  * Coverity. Here's a kludge to unconfuse it.
170  */
171 # define __INCLUDE_LEVEL__ 2
172 #endif /* defined(__COVERITY__) && !defined(__INCLUDE_LEVEL__) */
173 #include <systemd/sd-daemon.h>
174 #endif /* defined(HAVE_SYSTEMD) */
175 
176 /* Prefix used to indicate a Unix socket in a FooPort configuration. */
177 static const char unix_socket_prefix[] = "unix:";
178 /* Prefix used to indicate a Unix socket with spaces in it, in a FooPort
179  * configuration. */
180 static const char unix_q_socket_prefix[] = "unix:\"";
181 
182 /* limits for TCP send and recv buffer size used for constrained sockets */
183 #define MIN_CONSTRAINED_TCP_BUFFER 2048
184 #define MAX_CONSTRAINED_TCP_BUFFER 262144 /* 256k */
185 
188 #define DOWNLOAD_SCHEDULE(name) \
189  { #name "DownloadSchedule", #name "DownloadInitialDelay", 0, 1 }
190 
194  PLURAL(AuthDirBadDirCC),
195  PLURAL(AuthDirBadExitCC),
196  PLURAL(AuthDirInvalidCC),
197  PLURAL(AuthDirRejectCC),
198  PLURAL(EntryNode),
199  PLURAL(ExcludeNode),
200  PLURAL(FirewallPort),
201  PLURAL(LongLivedPort),
202  PLURAL(HiddenServiceNode),
203  PLURAL(HiddenServiceExcludeNode),
204  PLURAL(NumCPU),
205  PLURAL(RendNode),
206  PLURAL(RecommendedPackage),
207  PLURAL(RendExcludeNode),
208  PLURAL(StrictEntryNode),
209  PLURAL(StrictExitNode),
210  PLURAL(StrictNode),
211  { "l", "Log", 1, 0},
212  { "AllowUnverifiedNodes", "AllowInvalidNodes", 0, 0},
213  { "AutomapHostSuffixes", "AutomapHostsSuffixes", 0, 0},
214  { "AutomapHostOnResolve", "AutomapHostsOnResolve", 0, 0},
215  { "BandwidthRateBytes", "BandwidthRate", 0, 0},
216  { "BandwidthBurstBytes", "BandwidthBurst", 0, 0},
217  { "DirFetchPostPeriod", "StatusFetchPeriod", 0, 0},
218  { "DirServer", "DirAuthority", 0, 0}, /* XXXX later, make this warn? */
219  { "MaxConn", "ConnLimit", 0, 1},
220  { "MaxMemInCellQueues", "MaxMemInQueues", 0, 0},
221  { "ORBindAddress", "ORListenAddress", 0, 0},
222  { "DirBindAddress", "DirListenAddress", 0, 0},
223  { "SocksBindAddress", "SocksListenAddress", 0, 0},
224  { "UseHelperNodes", "UseEntryGuards", 0, 0},
225  { "NumHelperNodes", "NumEntryGuards", 0, 0},
226  { "UseEntryNodes", "UseEntryGuards", 0, 0},
227  { "NumEntryNodes", "NumEntryGuards", 0, 0},
228  { "ResolvConf", "ServerDNSResolvConfFile", 0, 1},
229  { "SearchDomains", "ServerDNSSearchDomains", 0, 1},
230  { "ServerDNSAllowBrokenResolvConf", "ServerDNSAllowBrokenConfig", 0, 0},
231  { "PreferTunnelledDirConns", "PreferTunneledDirConns", 0, 0},
232  { "BridgeAuthoritativeDirectory", "BridgeAuthoritativeDir", 0, 0},
233  { "HashedControlPassword", "__HashedControlSessionPassword", 1, 0},
234  { "VirtualAddrNetwork", "VirtualAddrNetworkIPv4", 0, 0},
235  { "SocksSocketsGroupWritable", "UnixSocksGroupWritable", 0, 1},
236  { "_HSLayer2Nodes", "HSLayer2Nodes", 0, 1 },
237  { "_HSLayer3Nodes", "HSLayer3Nodes", 0, 1 },
238 
239  DOWNLOAD_SCHEDULE(ClientBootstrapConsensusAuthority),
240  DOWNLOAD_SCHEDULE(ClientBootstrapConsensusAuthorityOnly),
241  DOWNLOAD_SCHEDULE(ClientBootstrapConsensusFallback),
242  DOWNLOAD_SCHEDULE(TestingBridge),
243  DOWNLOAD_SCHEDULE(TestingBridgeBootstrap),
244  DOWNLOAD_SCHEDULE(TestingClient),
245  DOWNLOAD_SCHEDULE(TestingClientConsensus),
246  DOWNLOAD_SCHEDULE(TestingServer),
247  DOWNLOAD_SCHEDULE(TestingServerConsensus),
248 
249  { NULL, NULL, 0, 0},
250 };
251 
255 
260 #define VAR(name,conftype,member,initvalue) \
261  { name, CONFIG_TYPE_ ## conftype, offsetof(or_options_t, member), \
262  initvalue CONF_TEST_MEMBERS(or_options_t, conftype, member) }
263 
264 #define V(member,conftype,initvalue) \
265  VAR(#member, conftype, member, initvalue)
266 
267 #ifdef TOR_UNIT_TESTS
268 #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL, {.INT=NULL} }
269 #else
270 #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL }
271 #endif
272 
280 #define VPORT(member) \
281  VAR(#member "Lines", LINELIST_V, member ## _lines, NULL), \
282  VAR(#member, LINELIST_S, member ## _lines, NULL), \
283  VAR("__" #member, LINELIST_S, member ## _lines, NULL)
284 
286 #define UINT64_MAX_STRING "18446744073709551615"
287 
293  V(AccountingMax, MEMUNIT, "0 bytes"),
294  VAR("AccountingRule", STRING, AccountingRule_option, "max"),
295  V(AccountingStart, STRING, NULL),
296  V(Address, STRING, NULL),
297  OBSOLETE("AllowDotExit"),
298  OBSOLETE("AllowInvalidNodes"),
299  V(AllowNonRFC953Hostnames, BOOL, "0"),
300  OBSOLETE("AllowSingleHopCircuits"),
301  OBSOLETE("AllowSingleHopExits"),
302  V(AlternateBridgeAuthority, LINELIST, NULL),
303  V(AlternateDirAuthority, LINELIST, NULL),
304  OBSOLETE("AlternateHSAuthority"),
305  V(AssumeReachable, BOOL, "0"),
306  OBSOLETE("AuthDirBadDir"),
307  OBSOLETE("AuthDirBadDirCCs"),
308  V(AuthDirBadExit, LINELIST, NULL),
309  V(AuthDirBadExitCCs, CSV, ""),
310  V(AuthDirInvalid, LINELIST, NULL),
311  V(AuthDirInvalidCCs, CSV, ""),
312  V(AuthDirFastGuarantee, MEMUNIT, "100 KB"),
313  V(AuthDirGuardBWGuarantee, MEMUNIT, "2 MB"),
314  V(AuthDirPinKeys, BOOL, "1"),
315  V(AuthDirReject, LINELIST, NULL),
316  V(AuthDirRejectCCs, CSV, ""),
317  OBSOLETE("AuthDirRejectUnlisted"),
318  OBSOLETE("AuthDirListBadDirs"),
319  V(AuthDirListBadExits, BOOL, "0"),
320  V(AuthDirMaxServersPerAddr, UINT, "2"),
321  OBSOLETE("AuthDirMaxServersPerAuthAddr"),
322  V(AuthDirHasIPv6Connectivity, BOOL, "0"),
323  VAR("AuthoritativeDirectory", BOOL, AuthoritativeDir, "0"),
324  V(AutomapHostsOnResolve, BOOL, "0"),
325  V(AutomapHostsSuffixes, CSV, ".onion,.exit"),
326  V(AvoidDiskWrites, BOOL, "0"),
327  V(BandwidthBurst, MEMUNIT, "1 GB"),
328  V(BandwidthRate, MEMUNIT, "1 GB"),
329  V(BridgeAuthoritativeDir, BOOL, "0"),
330  VAR("Bridge", LINELIST, Bridges, NULL),
331  V(BridgePassword, STRING, NULL),
332  V(BridgeRecordUsageByCountry, BOOL, "1"),
333  V(BridgeRelay, BOOL, "0"),
334  V(BridgeDistribution, STRING, NULL),
335  VAR("CacheDirectory", FILENAME, CacheDirectory_option, NULL),
336  V(CacheDirectoryGroupReadable, AUTOBOOL, "auto"),
337  V(CellStatistics, BOOL, "0"),
338  V(PaddingStatistics, BOOL, "1"),
339  V(LearnCircuitBuildTimeout, BOOL, "1"),
340  V(CircuitBuildTimeout, INTERVAL, "0"),
341  OBSOLETE("CircuitIdleTimeout"),
342  V(CircuitsAvailableTimeout, INTERVAL, "0"),
343  V(CircuitStreamTimeout, INTERVAL, "0"),
344  V(CircuitPriorityHalflife, DOUBLE, "-1.0"), /*negative:'Use default'*/
345  V(ClientDNSRejectInternalAddresses, BOOL,"1"),
346  V(ClientOnly, BOOL, "0"),
347  V(ClientPreferIPv6ORPort, AUTOBOOL, "auto"),
348  V(ClientPreferIPv6DirPort, AUTOBOOL, "auto"),
349  V(ClientAutoIPv6ORPort, BOOL, "0"),
350  V(ClientRejectInternalAddresses, BOOL, "1"),
351  V(ClientTransportPlugin, LINELIST, NULL),
352  V(ClientUseIPv6, BOOL, "0"),
353  V(ClientUseIPv4, BOOL, "1"),
354  V(ConsensusParams, STRING, NULL),
355  V(ConnLimit, UINT, "1000"),
356  V(ConnDirectionStatistics, BOOL, "0"),
357  V(ConstrainedSockets, BOOL, "0"),
358  V(ConstrainedSockSize, MEMUNIT, "8192"),
359  V(ContactInfo, STRING, NULL),
360  OBSOLETE("ControlListenAddress"),
361  VPORT(ControlPort),
362  V(ControlPortFileGroupReadable,BOOL, "0"),
363  V(ControlPortWriteToFile, FILENAME, NULL),
364  V(ControlSocket, LINELIST, NULL),
365  V(ControlSocketsGroupWritable, BOOL, "0"),
366  V(UnixSocksGroupWritable, BOOL, "0"),
367  V(CookieAuthentication, BOOL, "0"),
368  V(CookieAuthFileGroupReadable, BOOL, "0"),
369  V(CookieAuthFile, STRING, NULL),
370  V(CountPrivateBandwidth, BOOL, "0"),
371  VAR("DataDirectory", FILENAME, DataDirectory_option, NULL),
372  V(DataDirectoryGroupReadable, BOOL, "0"),
373  V(DisableOOSCheck, BOOL, "1"),
374  V(DisableNetwork, BOOL, "0"),
375  V(DirAllowPrivateAddresses, BOOL, "0"),
376  V(TestingAuthDirTimeToLearnReachability, INTERVAL, "30 minutes"),
377  OBSOLETE("DirListenAddress"),
378  V(DirPolicy, LINELIST, NULL),
379  VPORT(DirPort),
380  V(DirPortFrontPage, FILENAME, NULL),
381  VAR("DirReqStatistics", BOOL, DirReqStatistics_option, "1"),
382  VAR("DirAuthority", LINELIST, DirAuthorities, NULL),
383  V(DirCache, BOOL, "1"),
384  /* A DirAuthorityFallbackRate of 0.1 means that 0.5% of clients try an
385  * authority when all fallbacks are up, and 2% try an authority when 25% of
386  * fallbacks are down. (We rebuild the list when 25% of fallbacks are down).
387  *
388  * We want to reduce load on authorities, but keep these two figures within
389  * an order of magnitude, so there isn't too much load shifting to
390  * authorities when fallbacks go down. */
391  V(DirAuthorityFallbackRate, DOUBLE, "0.1"),
392  V(DisableAllSwap, BOOL, "0"),
393  V(DisableDebuggerAttachment, BOOL, "1"),
394  OBSOLETE("DisableIOCP"),
395  OBSOLETE("DisableV2DirectoryInfo_"),
396  OBSOLETE("DynamicDHGroups"),
397  VPORT(DNSPort),
398  OBSOLETE("DNSListenAddress"),
399  V(DormantClientTimeout, INTERVAL, "24 hours"),
400  V(DormantTimeoutDisabledByIdleStreams, BOOL, "1"),
401  V(DormantOnFirstStartup, BOOL, "0"),
402  V(DormantCanceledByStartup, BOOL, "0"),
403  /* DoS circuit creation options. */
404  V(DoSCircuitCreationEnabled, AUTOBOOL, "auto"),
405  V(DoSCircuitCreationMinConnections, UINT, "0"),
406  V(DoSCircuitCreationRate, UINT, "0"),
407  V(DoSCircuitCreationBurst, UINT, "0"),
408  V(DoSCircuitCreationDefenseType, INT, "0"),
409  V(DoSCircuitCreationDefenseTimePeriod, INTERVAL, "0"),
410  /* DoS connection options. */
411  V(DoSConnectionEnabled, AUTOBOOL, "auto"),
412  V(DoSConnectionMaxConcurrentCount, UINT, "0"),
413  V(DoSConnectionDefenseType, INT, "0"),
414  /* DoS single hop client options. */
415  V(DoSRefuseSingleHopClientRendezvous, AUTOBOOL, "auto"),
416  V(DownloadExtraInfo, BOOL, "0"),
417  V(TestingEnableConnBwEvent, BOOL, "0"),
418  V(TestingEnableCellStatsEvent, BOOL, "0"),
419  OBSOLETE("TestingEnableTbEmptyEvent"),
420  V(EnforceDistinctSubnets, BOOL, "1"),
421  V(EntryNodes, ROUTERSET, NULL),
422  V(EntryStatistics, BOOL, "0"),
423  V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "10 minutes"),
424  V(ExcludeNodes, ROUTERSET, NULL),
425  V(ExcludeExitNodes, ROUTERSET, NULL),
426  OBSOLETE("ExcludeSingleHopRelays"),
427  V(ExitNodes, ROUTERSET, NULL),
428  /* Researchers need a way to tell their clients to use specific
429  * middles that they also control, to allow safe live-network
430  * experimentation with new padding machines. */
431  V(MiddleNodes, ROUTERSET, NULL),
432  V(ExitPolicy, LINELIST, NULL),
433  V(ExitPolicyRejectPrivate, BOOL, "1"),
434  V(ExitPolicyRejectLocalInterfaces, BOOL, "0"),
435  V(ExitPortStatistics, BOOL, "0"),
436  V(ExtendAllowPrivateAddresses, BOOL, "0"),
437  V(ExitRelay, AUTOBOOL, "auto"),
438  VPORT(ExtORPort),
439  V(ExtORPortCookieAuthFile, STRING, NULL),
440  V(ExtORPortCookieAuthFileGroupReadable, BOOL, "0"),
441  V(ExtraInfoStatistics, BOOL, "1"),
442  V(ExtendByEd25519ID, AUTOBOOL, "auto"),
443  V(FallbackDir, LINELIST, NULL),
444 
445  V(UseDefaultFallbackDirs, BOOL, "1"),
446 
447  OBSOLETE("FallbackNetworkstatusFile"),
448  V(FascistFirewall, BOOL, "0"),
449  V(FirewallPorts, CSV, ""),
450  OBSOLETE("FastFirstHopPK"),
451  V(FetchDirInfoEarly, BOOL, "0"),
452  V(FetchDirInfoExtraEarly, BOOL, "0"),
453  V(FetchServerDescriptors, BOOL, "1"),
454  V(FetchHidServDescriptors, BOOL, "1"),
455  V(FetchUselessDescriptors, BOOL, "0"),
456  OBSOLETE("FetchV2Networkstatus"),
457  V(GeoIPExcludeUnknown, AUTOBOOL, "auto"),
458 #ifdef _WIN32
459  V(GeoIPFile, FILENAME, "<default>"),
460  V(GeoIPv6File, FILENAME, "<default>"),
461 #else
462  V(GeoIPFile, FILENAME,
463  SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip"),
464  V(GeoIPv6File, FILENAME,
465  SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip6"),
466 #endif /* defined(_WIN32) */
467  OBSOLETE("Group"),
468  V(GuardLifetime, INTERVAL, "0 minutes"),
469  V(HardwareAccel, BOOL, "0"),
470  V(HeartbeatPeriod, INTERVAL, "6 hours"),
471  V(MainloopStats, BOOL, "0"),
472  V(AccelName, STRING, NULL),
473  V(AccelDir, FILENAME, NULL),
474  V(HashedControlPassword, LINELIST, NULL),
475  OBSOLETE("HidServDirectoryV2"),
476  VAR("HiddenServiceDir", LINELIST_S, RendConfigLines, NULL),
477  VAR("HiddenServiceDirGroupReadable", LINELIST_S, RendConfigLines, NULL),
478  VAR("HiddenServiceOptions",LINELIST_V, RendConfigLines, NULL),
479  VAR("HiddenServicePort", LINELIST_S, RendConfigLines, NULL),
480  VAR("HiddenServiceVersion",LINELIST_S, RendConfigLines, NULL),
481  VAR("HiddenServiceAuthorizeClient",LINELIST_S,RendConfigLines, NULL),
482  VAR("HiddenServiceAllowUnknownPorts",LINELIST_S, RendConfigLines, NULL),
483  VAR("HiddenServiceMaxStreams",LINELIST_S, RendConfigLines, NULL),
484  VAR("HiddenServiceMaxStreamsCloseCircuit",LINELIST_S, RendConfigLines, NULL),
485  VAR("HiddenServiceNumIntroductionPoints", LINELIST_S, RendConfigLines, NULL),
486  VAR("HiddenServiceExportCircuitID", LINELIST_S, RendConfigLines, NULL),
487  VAR("HiddenServiceStatistics", BOOL, HiddenServiceStatistics_option, "1"),
488  V(HidServAuth, LINELIST, NULL),
489  V(ClientOnionAuthDir, FILENAME, NULL),
490  OBSOLETE("CloseHSClientCircuitsImmediatelyOnTimeout"),
491  OBSOLETE("CloseHSServiceRendCircuitsImmediatelyOnTimeout"),
492  V(HiddenServiceSingleHopMode, BOOL, "0"),
493  V(HiddenServiceNonAnonymousMode,BOOL, "0"),
494  V(HTTPProxy, STRING, NULL),
495  V(HTTPProxyAuthenticator, STRING, NULL),
496  V(HTTPSProxy, STRING, NULL),
497  V(HTTPSProxyAuthenticator, STRING, NULL),
498  VPORT(HTTPTunnelPort),
499  V(IPv6Exit, BOOL, "0"),
500  VAR("ServerTransportPlugin", LINELIST, ServerTransportPlugin, NULL),
501  V(ServerTransportListenAddr, LINELIST, NULL),
502  V(ServerTransportOptions, LINELIST, NULL),
503  V(SigningKeyLifetime, INTERVAL, "30 days"),
504  V(Socks4Proxy, STRING, NULL),
505  V(Socks5Proxy, STRING, NULL),
506  V(Socks5ProxyUsername, STRING, NULL),
507  V(Socks5ProxyPassword, STRING, NULL),
508  VAR("KeyDirectory", FILENAME, KeyDirectory_option, NULL),
509  V(KeyDirectoryGroupReadable, BOOL, "0"),
510  VAR("HSLayer2Nodes", ROUTERSET, HSLayer2Nodes, NULL),
511  VAR("HSLayer3Nodes", ROUTERSET, HSLayer3Nodes, NULL),
512  V(KeepalivePeriod, INTERVAL, "5 minutes"),
513  V(KeepBindCapabilities, AUTOBOOL, "auto"),
514  VAR("Log", LINELIST, Logs, NULL),
515  V(LogMessageDomains, BOOL, "0"),
516  V(LogTimeGranularity, MSEC_INTERVAL, "1 second"),
517  V(TruncateLogFile, BOOL, "0"),
518  V(SyslogIdentityTag, STRING, NULL),
519  V(AndroidIdentityTag, STRING, NULL),
520  V(LongLivedPorts, CSV,
521  "21,22,706,1863,5050,5190,5222,5223,6523,6667,6697,8300"),
522  VAR("MapAddress", LINELIST, AddressMap, NULL),
523  V(MaxAdvertisedBandwidth, MEMUNIT, "1 GB"),
524  V(MaxCircuitDirtiness, INTERVAL, "10 minutes"),
525  V(MaxClientCircuitsPending, UINT, "32"),
526  V(MaxConsensusAgeForDiffs, INTERVAL, "0 seconds"),
527  VAR("MaxMemInQueues", MEMUNIT, MaxMemInQueues_raw, "0"),
528  OBSOLETE("MaxOnionsPending"),
529  V(MaxOnionQueueDelay, MSEC_INTERVAL, "1750 msec"),
530  V(MaxUnparseableDescSizeToLog, MEMUNIT, "10 MB"),
531  V(MinMeasuredBWsForAuthToIgnoreAdvertised, INT, "500"),
532  VAR("MyFamily", LINELIST, MyFamily_lines, NULL),
533  V(NewCircuitPeriod, INTERVAL, "30 seconds"),
534  OBSOLETE("NamingAuthoritativeDirectory"),
535  OBSOLETE("NATDListenAddress"),
536  VPORT(NATDPort),
537  V(Nickname, STRING, NULL),
538  OBSOLETE("PredictedPortsRelevanceTime"),
539  OBSOLETE("WarnUnsafeSocks"),
540  VAR("NodeFamily", LINELIST, NodeFamilies, NULL),
541  V(NoExec, BOOL, "0"),
542  V(NumCPUs, UINT, "0"),
543  V(NumDirectoryGuards, UINT, "0"),
544  V(NumEntryGuards, UINT, "0"),
545  V(NumPrimaryGuards, UINT, "0"),
546  V(OfflineMasterKey, BOOL, "0"),
547  OBSOLETE("ORListenAddress"),
548  VPORT(ORPort),
549  V(OutboundBindAddress, LINELIST, NULL),
550  V(OutboundBindAddressOR, LINELIST, NULL),
551  V(OutboundBindAddressExit, LINELIST, NULL),
552 
553  OBSOLETE("PathBiasDisableRate"),
554  V(PathBiasCircThreshold, INT, "-1"),
555  V(PathBiasNoticeRate, DOUBLE, "-1"),
556  V(PathBiasWarnRate, DOUBLE, "-1"),
557  V(PathBiasExtremeRate, DOUBLE, "-1"),
558  V(PathBiasScaleThreshold, INT, "-1"),
559  OBSOLETE("PathBiasScaleFactor"),
560  OBSOLETE("PathBiasMultFactor"),
561  V(PathBiasDropGuards, AUTOBOOL, "0"),
562  OBSOLETE("PathBiasUseCloseCounts"),
563 
564  V(PathBiasUseThreshold, INT, "-1"),
565  V(PathBiasNoticeUseRate, DOUBLE, "-1"),
566  V(PathBiasExtremeUseRate, DOUBLE, "-1"),
567  V(PathBiasScaleUseThreshold, INT, "-1"),
568 
569  V(PathsNeededToBuildCircuits, DOUBLE, "-1"),
570  V(PerConnBWBurst, MEMUNIT, "0"),
571  V(PerConnBWRate, MEMUNIT, "0"),
572  V(PidFile, STRING, NULL),
573  V(TestingTorNetwork, BOOL, "0"),
574  V(TestingMinExitFlagThreshold, MEMUNIT, "0"),
575  V(TestingMinFastFlagThreshold, MEMUNIT, "0"),
576 
577  V(TestingLinkCertLifetime, INTERVAL, "2 days"),
578  V(TestingAuthKeyLifetime, INTERVAL, "2 days"),
579  V(TestingLinkKeySlop, INTERVAL, "3 hours"),
580  V(TestingAuthKeySlop, INTERVAL, "3 hours"),
581  V(TestingSigningKeySlop, INTERVAL, "1 day"),
582 
583  V(OptimisticData, AUTOBOOL, "auto"),
584  OBSOLETE("PortForwarding"),
585  OBSOLETE("PortForwardingHelper"),
586  OBSOLETE("PreferTunneledDirConns"),
587  V(ProtocolWarnings, BOOL, "0"),
588  V(PublishServerDescriptor, CSV, "1"),
589  V(PublishHidServDescriptors, BOOL, "1"),
590  V(ReachableAddresses, LINELIST, NULL),
591  V(ReachableDirAddresses, LINELIST, NULL),
592  V(ReachableORAddresses, LINELIST, NULL),
593  V(RecommendedVersions, LINELIST, NULL),
594  V(RecommendedClientVersions, LINELIST, NULL),
595  V(RecommendedServerVersions, LINELIST, NULL),
596  V(RecommendedPackages, LINELIST, NULL),
597  V(ReducedConnectionPadding, BOOL, "0"),
598  V(ConnectionPadding, AUTOBOOL, "auto"),
599  V(RefuseUnknownExits, AUTOBOOL, "auto"),
600  V(CircuitPadding, BOOL, "1"),
601  V(ReducedCircuitPadding, BOOL, "0"),
602  V(RejectPlaintextPorts, CSV, ""),
603  V(RelayBandwidthBurst, MEMUNIT, "0"),
604  V(RelayBandwidthRate, MEMUNIT, "0"),
605  V(RendPostPeriod, INTERVAL, "1 hour"),
606  V(RephistTrackTime, INTERVAL, "24 hours"),
607  V(RunAsDaemon, BOOL, "0"),
608  V(ReducedExitPolicy, BOOL, "0"),
609  OBSOLETE("RunTesting"), // currently unused
610  V(Sandbox, BOOL, "0"),
611  V(SafeLogging, STRING, "1"),
612  V(SafeSocks, BOOL, "0"),
613  V(ServerDNSAllowBrokenConfig, BOOL, "1"),
614  V(ServerDNSAllowNonRFC953Hostnames, BOOL,"0"),
615  V(ServerDNSDetectHijacking, BOOL, "1"),
616  V(ServerDNSRandomizeCase, BOOL, "1"),
617  V(ServerDNSResolvConfFile, STRING, NULL),
618  V(ServerDNSSearchDomains, BOOL, "0"),
619  V(ServerDNSTestAddresses, CSV,
620  "www.google.com,www.mit.edu,www.yahoo.com,www.slashdot.org"),
621  OBSOLETE("SchedulerLowWaterMark__"),
622  OBSOLETE("SchedulerHighWaterMark__"),
623  OBSOLETE("SchedulerMaxFlushCells__"),
624  V(KISTSchedRunInterval, MSEC_INTERVAL, "0 msec"),
625  V(KISTSockBufSizeFactor, DOUBLE, "1.0"),
626  V(Schedulers, CSV, "KIST,KISTLite,Vanilla"),
627  V(ShutdownWaitLength, INTERVAL, "30 seconds"),
628  OBSOLETE("SocksListenAddress"),
629  V(SocksPolicy, LINELIST, NULL),
630  VPORT(SocksPort),
631  V(SocksTimeout, INTERVAL, "2 minutes"),
632  V(SSLKeyLifetime, INTERVAL, "0"),
633  OBSOLETE("StrictEntryNodes"),
634  OBSOLETE("StrictExitNodes"),
635  V(StrictNodes, BOOL, "0"),
636  OBSOLETE("Support022HiddenServices"),
637  V(TestSocks, BOOL, "0"),
638  V(TokenBucketRefillInterval, MSEC_INTERVAL, "100 msec"),
639  OBSOLETE("Tor2webMode"),
640  OBSOLETE("Tor2webRendezvousPoints"),
641  OBSOLETE("TLSECGroup"),
642  V(TrackHostExits, CSV, NULL),
643  V(TrackHostExitsExpire, INTERVAL, "30 minutes"),
644  OBSOLETE("TransListenAddress"),
645  VPORT(TransPort),
646  V(TransProxyType, STRING, "default"),
647  OBSOLETE("TunnelDirConns"),
648  V(UpdateBridgesFromAuthority, BOOL, "0"),
649  V(UseBridges, BOOL, "0"),
650  VAR("UseEntryGuards", BOOL, UseEntryGuards_option, "1"),
651  OBSOLETE("UseEntryGuardsAsDirGuards"),
652  V(UseGuardFraction, AUTOBOOL, "auto"),
653  V(UseMicrodescriptors, AUTOBOOL, "auto"),
654  OBSOLETE("UseNTorHandshake"),
655  V(User, STRING, NULL),
656  OBSOLETE("UserspaceIOCPBuffers"),
657  V(AuthDirSharedRandomness, BOOL, "1"),
658  V(AuthDirTestEd25519LinkKeys, BOOL, "1"),
659  OBSOLETE("V1AuthoritativeDirectory"),
660  OBSOLETE("V2AuthoritativeDirectory"),
661  VAR("V3AuthoritativeDirectory",BOOL, V3AuthoritativeDir, "0"),
662  V(TestingV3AuthInitialVotingInterval, INTERVAL, "30 minutes"),
663  V(TestingV3AuthInitialVoteDelay, INTERVAL, "5 minutes"),
664  V(TestingV3AuthInitialDistDelay, INTERVAL, "5 minutes"),
665  V(TestingV3AuthVotingStartOffset, INTERVAL, "0"),
666  V(V3AuthVotingInterval, INTERVAL, "1 hour"),
667  V(V3AuthVoteDelay, INTERVAL, "5 minutes"),
668  V(V3AuthDistDelay, INTERVAL, "5 minutes"),
669  V(V3AuthNIntervalsValid, UINT, "3"),
670  V(V3AuthUseLegacyKey, BOOL, "0"),
671  V(V3BandwidthsFile, FILENAME, NULL),
672  V(GuardfractionFile, FILENAME, NULL),
673  VAR("VersioningAuthoritativeDirectory",BOOL,VersioningAuthoritativeDir, "0"),
674  OBSOLETE("VoteOnHidServDirectoriesV2"),
675  V(VirtualAddrNetworkIPv4, STRING, "127.192.0.0/10"),
676  V(VirtualAddrNetworkIPv6, STRING, "[FE80::]/10"),
677  V(WarnPlaintextPorts, CSV, "23,109,110,143"),
678  OBSOLETE("UseFilteringSSLBufferevents"),
679  OBSOLETE("__UseFilteringSSLBufferevents"),
680  VAR("__ReloadTorrcOnSIGHUP", BOOL, ReloadTorrcOnSIGHUP, "1"),
681  VAR("__AllDirActionsPrivate", BOOL, AllDirActionsPrivate, "0"),
682  VAR("__DisablePredictedCircuits",BOOL,DisablePredictedCircuits, "0"),
683  VAR("__DisableSignalHandlers", BOOL, DisableSignalHandlers, "0"),
684  VAR("__LeaveStreamsUnattached",BOOL, LeaveStreamsUnattached, "0"),
685  VAR("__HashedControlSessionPassword", LINELIST, HashedControlSessionPassword,
686  NULL),
687  VAR("__OwningControllerProcess",STRING,OwningControllerProcess, NULL),
688  VAR("__OwningControllerFD", UINT64, OwningControllerFD, UINT64_MAX_STRING),
689  V(MinUptimeHidServDirectoryV2, INTERVAL, "96 hours"),
690  V(TestingServerDownloadInitialDelay, CSV_INTERVAL, "0"),
691  V(TestingClientDownloadInitialDelay, CSV_INTERVAL, "0"),
692  V(TestingServerConsensusDownloadInitialDelay, CSV_INTERVAL, "0"),
693  V(TestingClientConsensusDownloadInitialDelay, CSV_INTERVAL, "0"),
694  /* With the ClientBootstrapConsensus*Download* below:
695  * Clients with only authorities will try:
696  * - at least 3 authorities over 10 seconds, then exponentially backoff,
697  * with the next attempt 3-21 seconds later,
698  * Clients with authorities and fallbacks will try:
699  * - at least 2 authorities and 4 fallbacks over 21 seconds, then
700  * exponentially backoff, with the next attempts 4-33 seconds later,
701  * Clients will also retry when an application request arrives.
702  * After a number of failed requests, clients retry every 3 days + 1 hour.
703  *
704  * Clients used to try 2 authorities over 10 seconds, then wait for
705  * 60 minutes or an application request.
706  *
707  * When clients have authorities and fallbacks available, they use these
708  * schedules: (we stagger the times to avoid thundering herds) */
709  V(ClientBootstrapConsensusAuthorityDownloadInitialDelay, CSV_INTERVAL, "6"),
710  V(ClientBootstrapConsensusFallbackDownloadInitialDelay, CSV_INTERVAL, "0"),
711  /* When clients only have authorities available, they use this schedule: */
712  V(ClientBootstrapConsensusAuthorityOnlyDownloadInitialDelay, CSV_INTERVAL,
713  "0"),
714  /* We don't want to overwhelm slow networks (or mirrors whose replies are
715  * blocked), but we also don't want to fail if only some mirrors are
716  * blackholed. Clients will try 3 directories simultaneously.
717  * (Relays never use simultaneous connections.) */
718  V(ClientBootstrapConsensusMaxInProgressTries, UINT, "3"),
719  /* When a client has any running bridges, check each bridge occasionally,
720  * whether or not that bridge is actually up. */
721  V(TestingBridgeDownloadInitialDelay, CSV_INTERVAL,"10800"),
722  /* When a client is just starting, or has no running bridges, check each
723  * bridge a few times quickly, and then try again later. These schedules
724  * are much longer than the other schedules, because we try each and every
725  * configured bridge with this schedule. */
726  V(TestingBridgeBootstrapDownloadInitialDelay, CSV_INTERVAL, "0"),
727  V(TestingClientMaxIntervalWithoutRequest, INTERVAL, "10 minutes"),
728  V(TestingDirConnectionMaxStall, INTERVAL, "5 minutes"),
729  OBSOLETE("TestingConsensusMaxDownloadTries"),
730  OBSOLETE("ClientBootstrapConsensusMaxDownloadTries"),
731  OBSOLETE("ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries"),
732  OBSOLETE("TestingDescriptorMaxDownloadTries"),
733  OBSOLETE("TestingMicrodescMaxDownloadTries"),
734  OBSOLETE("TestingCertMaxDownloadTries"),
735  V(TestingDirAuthVoteExit, ROUTERSET, NULL),
736  V(TestingDirAuthVoteExitIsStrict, BOOL, "0"),
737  V(TestingDirAuthVoteGuard, ROUTERSET, NULL),
738  V(TestingDirAuthVoteGuardIsStrict, BOOL, "0"),
739  V(TestingDirAuthVoteHSDir, ROUTERSET, NULL),
740  V(TestingDirAuthVoteHSDirIsStrict, BOOL, "0"),
741  VAR("___UsingTestNetworkDefaults", BOOL, UsingTestNetworkDefaults_, "0"),
742 
743  END_OF_CONFIG_VARS
744 };
745 
749  V(DirAllowPrivateAddresses, BOOL, "1"),
750  V(EnforceDistinctSubnets, BOOL, "0"),
751  V(AssumeReachable, BOOL, "1"),
752  V(AuthDirMaxServersPerAddr, UINT, "0"),
753  V(ClientBootstrapConsensusAuthorityDownloadInitialDelay, CSV_INTERVAL, "0"),
754  V(ClientBootstrapConsensusFallbackDownloadInitialDelay, CSV_INTERVAL, "0"),
755  V(ClientBootstrapConsensusAuthorityOnlyDownloadInitialDelay, CSV_INTERVAL,
756  "0"),
757  V(ClientDNSRejectInternalAddresses, BOOL,"0"),
758  V(ClientRejectInternalAddresses, BOOL, "0"),
759  V(CountPrivateBandwidth, BOOL, "1"),
760  V(ExitPolicyRejectPrivate, BOOL, "0"),
761  V(ExtendAllowPrivateAddresses, BOOL, "1"),
762  V(V3AuthVotingInterval, INTERVAL, "5 minutes"),
763  V(V3AuthVoteDelay, INTERVAL, "20 seconds"),
764  V(V3AuthDistDelay, INTERVAL, "20 seconds"),
765  V(TestingV3AuthInitialVotingInterval, INTERVAL, "150 seconds"),
766  V(TestingV3AuthInitialVoteDelay, INTERVAL, "20 seconds"),
767  V(TestingV3AuthInitialDistDelay, INTERVAL, "20 seconds"),
768  V(TestingAuthDirTimeToLearnReachability, INTERVAL, "0 minutes"),
769  V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "0 minutes"),
770  V(MinUptimeHidServDirectoryV2, INTERVAL, "0 minutes"),
771  V(TestingServerDownloadInitialDelay, CSV_INTERVAL, "0"),
772  V(TestingClientDownloadInitialDelay, CSV_INTERVAL, "0"),
773  V(TestingServerConsensusDownloadInitialDelay, CSV_INTERVAL, "0"),
774  V(TestingClientConsensusDownloadInitialDelay, CSV_INTERVAL, "0"),
775  V(TestingBridgeDownloadInitialDelay, CSV_INTERVAL, "10"),
776  V(TestingBridgeBootstrapDownloadInitialDelay, CSV_INTERVAL, "0"),
777  V(TestingClientMaxIntervalWithoutRequest, INTERVAL, "5 seconds"),
778  V(TestingDirConnectionMaxStall, INTERVAL, "30 seconds"),
779  V(TestingEnableConnBwEvent, BOOL, "1"),
780  V(TestingEnableCellStatsEvent, BOOL, "1"),
781  VAR("___UsingTestNetworkDefaults", BOOL, UsingTestNetworkDefaults_, "1"),
782  V(RendPostPeriod, INTERVAL, "2 minutes"),
783 
784  END_OF_CONFIG_VARS
785 };
786 
787 #undef VAR
788 #undef V
789 #undef OBSOLETE
790 
791 static const config_deprecation_t option_deprecation_notes_[] = {
792  /* Deprecated since 0.3.2.0-alpha. */
793  { "HTTPProxy", "It only applies to direct unencrypted HTTP connections "
794  "to your directory server, which your Tor probably wasn't using." },
795  { "HTTPProxyAuthenticator", "HTTPProxy is deprecated in favor of HTTPSProxy "
796  "which should be used with HTTPSProxyAuthenticator." },
797  /* End of options deprecated since 0.3.2.1-alpha */
798 
799  /* Options deprecated since 0.3.2.2-alpha */
800  { "ReachableDirAddresses", "It has no effect on relays, and has had no "
801  "effect on clients since 0.2.8." },
802  { "ClientPreferIPv6DirPort", "It has no effect on relays, and has had no "
803  "effect on clients since 0.2.8." },
804  /* End of options deprecated since 0.3.2.2-alpha. */
805 
806  { NULL, NULL }
807 };
808 
809 #ifdef _WIN32
810 static char *get_windows_conf_root(void);
811 #endif
812 static int options_act_reversible(const or_options_t *old_options, char **msg);
813 static int options_transition_allowed(const or_options_t *old,
814  const or_options_t *new,
815  char **msg);
817  const or_options_t *old_options, const or_options_t *new_options);
819  const or_options_t *old_options, const or_options_t *new_options);
821  const or_options_t *old_options, const or_options_t *new_options);
822 static int normalize_nickname_list(config_line_t **normalized_out,
823  const config_line_t *lst, const char *name,
824  char **msg);
825 static char *get_bindaddr_from_transport_listen_line(const char *line,
826  const char *transport);
827 static int parse_ports(or_options_t *options, int validate_only,
828  char **msg_out, int *n_ports_out,
829  int *world_writable_control_socket);
830 static int check_server_ports(const smartlist_t *ports,
831  const or_options_t *options,
832  int *num_low_ports_out);
833 static int validate_data_directories(or_options_t *options);
834 static int write_configuration_file(const char *fname,
835  const or_options_t *options);
836 static int options_init_logs(const or_options_t *old_options,
837  or_options_t *options, int validate_only);
838 
839 static void init_libevent(const or_options_t *options);
840 static int opt_streq(const char *s1, const char *s2);
841 static int parse_outbound_addresses(or_options_t *options, int validate_only,
842  char **msg);
843 static void config_maybe_load_geoip_files_(const or_options_t *options,
844  const or_options_t *old_options);
845 static int options_validate_cb(void *old_options, void *options,
846  void *default_options,
847  int from_setconf, char **msg);
848 static void options_free_cb(void *options);
850 static void set_protocol_warning_severity_level(int warning_severity);
851 
853 #define OR_OPTIONS_MAGIC 9090909
854 
857  sizeof(or_options_t),
859  offsetof(or_options_t, magic_),
861  option_deprecation_notes_,
862  option_vars_,
863  options_validate_cb,
865  NULL
866 };
867 
868 /*
869  * Functions to read and write the global options pointer.
870  */
871 
878 static char *torrc_fname = NULL;
880 static char *torrc_defaults_fname = NULL;
886 static int have_parsed_cmdline = 0;
888 static char *global_dirfrontpagecontents = NULL;
893 static int in_option_validation = 0;
894 /* True iff we've initialized libevent */
895 static int libevent_initialized = 0;
896 
898 MOCK_IMPL(const char*,
899 get_dirportfrontpage, (void))
900 {
902 }
903 
906 get_options_mutable, (void))
907 {
909  tor_assert_nonfatal(! in_option_validation);
910  return global_options;
911 }
912 
915 get_options,(void))
916 {
917  return get_options_mutable();
918 }
919 
924 int
925 set_options(or_options_t *new_val, char **msg)
926 {
927  int i;
928  smartlist_t *elements;
929  config_line_t *line;
930  or_options_t *old_options = global_options;
931  global_options = new_val;
932  /* Note that we pass the *old* options below, for comparison. It
933  * pulls the new options directly out of global_options. */
934  if (options_act_reversible(old_options, msg)<0) {
935  tor_assert(*msg);
936  global_options = old_options;
937  return -1;
938  }
939  if (options_act(old_options) < 0) { /* acting on the options failed. die. */
941  log_err(LD_BUG,
942  "Acting on config options left us in a broken state. Dying.");
944  }
945  global_options = old_options;
946  return -1;
947  }
948  /* Issues a CONF_CHANGED event to notify controller of the change. If Tor is
949  * just starting up then the old_options will be undefined. */
950  if (old_options && old_options != global_options) {
951  elements = smartlist_new();
952  for (i=0; options_format.vars[i].name; ++i) {
953  const config_var_t *var = &options_format.vars[i];
954  const char *var_name = var->name;
955  if (var->type == CONFIG_TYPE_LINELIST_S ||
956  var->type == CONFIG_TYPE_OBSOLETE) {
957  continue;
958  }
959  if (!config_is_same(&options_format, new_val, old_options, var_name)) {
961  var_name, 1);
962 
963  if (line) {
964  config_line_t *next;
965  for (; line; line = next) {
966  next = line->next;
967  smartlist_add(elements, line->key);
968  smartlist_add(elements, line->value);
969  tor_free(line);
970  }
971  } else {
973  smartlist_add(elements, NULL);
974  }
975  }
976  }
977  control_event_conf_changed(elements);
978  SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
979  smartlist_free(elements);
980  }
981 
982  if (old_options != global_options) {
983  or_options_free(old_options);
984  /* If we are here it means we've successfully applied the new options and
985  * that the global options have been changed to the new values. We'll
986  * check if we need to remove or add periodic events. */
987  periodic_events_on_new_options(global_options);
988  }
989 
990  return 0;
991 }
992 
995 STATIC void
997 {
998  if (!options)
999  return;
1000 
1001  routerset_free(options->ExcludeExitNodesUnion_);
1002  if (options->NodeFamilySets) {
1003  SMARTLIST_FOREACH(options->NodeFamilySets, routerset_t *,
1004  rs, routerset_free(rs));
1005  smartlist_free(options->NodeFamilySets);
1006  }
1007  if (options->SchedulerTypes_) {
1008  SMARTLIST_FOREACH(options->SchedulerTypes_, int *, i, tor_free(i));
1009  smartlist_free(options->SchedulerTypes_);
1010  }
1011  if (options->FilesOpenedByIncludes) {
1012  SMARTLIST_FOREACH(options->FilesOpenedByIncludes, char *, f, tor_free(f));
1013  smartlist_free(options->FilesOpenedByIncludes);
1014  }
1015  tor_free(options->DataDirectory);
1016  tor_free(options->CacheDirectory);
1017  tor_free(options->KeyDirectory);
1019  tor_free(options->command_arg);
1020  tor_free(options->master_key_fname);
1021  config_free_lines(options->MyFamily);
1022  config_free(&options_format, options);
1023 }
1024 
1027 void
1029 {
1030  or_options_free(global_options);
1031  global_options = NULL;
1032  or_options_free(global_default_options);
1033  global_default_options = NULL;
1034 
1035  config_free_lines(global_cmdline_options);
1036  global_cmdline_options = NULL;
1037 
1038  config_free_lines(global_cmdline_only_options);
1040 
1041  if (configured_ports) {
1043  port_cfg_t *, p, port_cfg_free(p));
1044  smartlist_free(configured_ports);
1045  configured_ports = NULL;
1046  }
1047 
1051 
1053 
1054  have_parsed_cmdline = 0;
1055  libevent_initialized = 0;
1056 }
1057 
1064 const char *
1065 safe_str_client_opts(const or_options_t *options, const char *address)
1066 {
1067  tor_assert(address);
1068  if (!options) {
1069  options = get_options();
1070  }
1071 
1072  if (options->SafeLogging_ == SAFELOG_SCRUB_ALL)
1073  return "[scrubbed]";
1074  else
1075  return address;
1076 }
1077 
1085 const char *
1086 safe_str_opts(const or_options_t *options, const char *address)
1087 {
1088  tor_assert(address);
1089  if (!options) {
1090  options = get_options();
1091  }
1092 
1093  if (options->SafeLogging_ != SAFELOG_SCRUB_NONE)
1094  return "[scrubbed]";
1095  else
1096  return address;
1097 }
1098 
1102 const char *
1103 escaped_safe_str_client(const char *address)
1104 {
1105  if (get_options()->SafeLogging_ == SAFELOG_SCRUB_ALL)
1106  return "[scrubbed]";
1107  else
1108  return escaped(address);
1109 }
1110 
1114 const char *
1115 escaped_safe_str(const char *address)
1116 {
1117  if (get_options()->SafeLogging_ != SAFELOG_SCRUB_NONE)
1118  return "[scrubbed]";
1119  else
1120  return escaped(address);
1121 }
1122 
1132 
1135 int
1137 {
1139 }
1140 
1142 static void
1144 {
1146  warning_severity);
1147 }
1148 
1153 void
1155 {
1158 }
1159 
1163 static void
1165 {
1167 }
1168 
1171 static const char *default_authorities[] = {
1172 #include "auth_dirs.inc"
1173  NULL
1174 };
1175 
1179 static const char *default_fallbacks[] = {
1180 #include "fallback_dirs.inc"
1181  NULL
1182 };
1183 
1188 STATIC void
1190 {
1191  int i;
1192  for (i=0; default_authorities[i]; i++) {
1193  if (parse_dir_authority_line(default_authorities[i], type, 0)<0) {
1194  log_err(LD_BUG, "Couldn't parse internal DirAuthority line %s",
1195  default_authorities[i]);
1196  }
1197  }
1198 }
1199 
1203 add_default_fallback_dir_servers,(void))
1204 {
1205  int i;
1206  for (i=0; default_fallbacks[i]; i++) {
1208  log_err(LD_BUG, "Couldn't parse internal FallbackDir line %s",
1209  default_fallbacks[i]);
1210  }
1211  }
1212 }
1213 
1218 static int
1220 {
1221  config_line_t *cl;
1222 
1223  if (options->DirAuthorities &&
1224  (options->AlternateDirAuthority || options->AlternateBridgeAuthority)) {
1225  log_warn(LD_CONFIG,
1226  "You cannot set both DirAuthority and Alternate*Authority.");
1227  return -1;
1228  }
1229 
1230  /* do we want to complain to the user about being partitionable? */
1231  if ((options->DirAuthorities &&
1232  (!old_options ||
1233  !config_lines_eq(options->DirAuthorities,
1234  old_options->DirAuthorities))) ||
1235  (options->AlternateDirAuthority &&
1236  (!old_options ||
1238  old_options->AlternateDirAuthority)))) {
1239  log_warn(LD_CONFIG,
1240  "You have used DirAuthority or AlternateDirAuthority to "
1241  "specify alternate directory authorities in "
1242  "your configuration. This is potentially dangerous: it can "
1243  "make you look different from all other Tor users, and hurt "
1244  "your anonymity. Even if you've specified the same "
1245  "authorities as Tor uses by default, the defaults could "
1246  "change in the future. Be sure you know what you're doing.");
1247  }
1248 
1249  /* Now go through the four ways you can configure an alternate
1250  * set of directory authorities, and make sure none are broken. */
1251  for (cl = options->DirAuthorities; cl; cl = cl->next)
1252  if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
1253  return -1;
1254  for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
1255  if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
1256  return -1;
1257  for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
1258  if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
1259  return -1;
1260  for (cl = options->FallbackDir; cl; cl = cl->next)
1261  if (parse_dir_fallback_line(cl->value, 1)<0)
1262  return -1;
1263  return 0;
1264 }
1265 
1269 int
1271  const or_options_t *old_options)
1272 {
1273  config_line_t *cl;
1274  int need_to_update =
1275  !smartlist_len(router_get_trusted_dir_servers()) ||
1276  !smartlist_len(router_get_fallback_dir_servers()) || !old_options ||
1277  !config_lines_eq(options->DirAuthorities, old_options->DirAuthorities) ||
1278  !config_lines_eq(options->FallbackDir, old_options->FallbackDir) ||
1279  (options->UseDefaultFallbackDirs != old_options->UseDefaultFallbackDirs) ||
1281  old_options->AlternateBridgeAuthority) ||
1283  old_options->AlternateDirAuthority);
1284 
1285  if (!need_to_update)
1286  return 0; /* all done */
1287 
1288  /* "You cannot set both DirAuthority and Alternate*Authority."
1289  * Checking that this restriction holds allows us to simplify
1290  * the unit tests. */
1291  tor_assert(!(options->DirAuthorities &&
1292  (options->AlternateDirAuthority
1293  || options->AlternateBridgeAuthority)));
1294 
1295  /* Start from a clean slate. */
1297 
1298  if (!options->DirAuthorities) {
1299  /* then we may want some of the defaults */
1300  dirinfo_type_t type = NO_DIRINFO;
1301  if (!options->AlternateBridgeAuthority) {
1302  type |= BRIDGE_DIRINFO;
1303  }
1304  if (!options->AlternateDirAuthority) {
1306  /* Only add the default fallback directories when the DirAuthorities,
1307  * AlternateDirAuthority, and FallbackDir directory config options
1308  * are set to their defaults, and when UseDefaultFallbackDirs is 1. */
1309  if (!options->FallbackDir && options->UseDefaultFallbackDirs) {
1310  add_default_fallback_dir_servers();
1311  }
1312  }
1313  /* if type == NO_DIRINFO, we don't want to add any of the
1314  * default authorities, because we've replaced them all */
1315  if (type != NO_DIRINFO)
1317  }
1318 
1319  for (cl = options->DirAuthorities; cl; cl = cl->next)
1320  if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
1321  return -1;
1322  for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
1323  if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
1324  return -1;
1325  for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
1326  if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
1327  return -1;
1328  for (cl = options->FallbackDir; cl; cl = cl->next)
1329  if (parse_dir_fallback_line(cl->value, 0)<0)
1330  return -1;
1331  return 0;
1332 }
1333 
1340 static int
1342  const char *directory,
1343  int group_readable,
1344  const char *owner,
1345  char **msg_out)
1346 {
1347  cpd_check_t cpd_opts = create ? CPD_CREATE : CPD_CHECK;
1348  if (group_readable)
1349  cpd_opts |= CPD_GROUP_READ;
1350  if (check_private_dir(directory,
1351  cpd_opts,
1352  owner) < 0) {
1353  tor_asprintf(msg_out,
1354  "Couldn't %s private data directory \"%s\"",
1355  create ? "create" : "access",
1356  directory);
1357  return -1;
1358  }
1359 
1360 #ifndef _WIN32
1361  if (group_readable) {
1362  /* Only new dirs created get new opts, also enforce group read. */
1363  if (chmod(directory, 0750)) {
1364  log_warn(LD_FS,"Unable to make %s group-readable: %s",
1365  directory, strerror(errno));
1366  }
1367  }
1368 #endif /* !defined(_WIN32) */
1369 
1370  return 0;
1371 }
1372 
1377 int
1379 {
1380  /* Make sure DataDirectory exists, and is private. */
1381  cpd_check_t cpd_opts = CPD_CREATE;
1382  if (options->DataDirectoryGroupReadable)
1383  cpd_opts |= CPD_GROUP_READ;
1384  if (check_private_dir(options->DataDirectory, cpd_opts, options->User)) {
1385  log_err(LD_OR, "Can't create/check datadirectory %s",
1386  options->DataDirectory);
1387  return -1;
1388  }
1389 
1390  /* Check the key directory. */
1391  if (check_private_dir(options->KeyDirectory, CPD_CREATE, options->User)) {
1392  return -1;
1393  }
1394  return 0;
1395 }
1396 
1397 /* Helps determine flags to pass to switch_id. */
1398 static int have_low_ports = -1;
1399 
1406 static int
1407 options_act_reversible(const or_options_t *old_options, char **msg)
1408 {
1409  smartlist_t *new_listeners = smartlist_new();
1410  or_options_t *options = get_options_mutable();
1411  int running_tor = options->command == CMD_RUN_TOR;
1412  int set_conn_limit = 0;
1413  int r = -1;
1414  int logs_marked = 0, logs_initialized = 0;
1415  int old_min_log_level = get_min_log_level();
1416 
1417  /* Daemonize _first_, since we only want to open most of this stuff in
1418  * the subprocess. Libevent bases can't be reliably inherited across
1419  * processes. */
1420  if (running_tor && options->RunAsDaemon) {
1422  subsystems_prefork();
1423  /* No need to roll back, since you can't change the value. */
1424  if (start_daemon())
1425  subsystems_postfork();
1426  }
1427 
1428 #ifdef HAVE_SYSTEMD
1429  /* Our PID may have changed, inform supervisor */
1430  sd_notifyf(0, "MAINPID=%ld\n", (long int)getpid());
1431 #endif
1432 
1433 #ifndef HAVE_SYS_UN_H
1434  if (options->ControlSocket || options->ControlSocketsGroupWritable) {
1435  *msg = tor_strdup("Unix domain sockets (ControlSocket) not supported "
1436  "on this OS/with this build.");
1437  goto rollback;
1438  }
1439 #else /* !(!defined(HAVE_SYS_UN_H)) */
1440  if (options->ControlSocketsGroupWritable && !options->ControlSocket) {
1441  *msg = tor_strdup("Setting ControlSocketGroupWritable without setting"
1442  "a ControlSocket makes no sense.");
1443  goto rollback;
1444  }
1445 #endif /* !defined(HAVE_SYS_UN_H) */
1446 
1447  if (running_tor) {
1448  int n_ports=0;
1449  /* We need to set the connection limit before we can open the listeners. */
1450  if (! sandbox_is_active()) {
1451  if (set_max_file_descriptors((unsigned)options->ConnLimit,
1452  &options->ConnLimit_) < 0) {
1453  *msg = tor_strdup("Problem with ConnLimit value. "
1454  "See logs for details.");
1455  goto rollback;
1456  }
1457  set_conn_limit = 1;
1458  } else {
1459  tor_assert(old_options);
1460  options->ConnLimit_ = old_options->ConnLimit_;
1461  }
1462 
1463  /* Set up libevent. (We need to do this before we can register the
1464  * listeners as listeners.) */
1465  if (running_tor && !libevent_initialized) {
1466  init_libevent(options);
1467  libevent_initialized = 1;
1468 
1469  /* This has to come up after libevent is initialized. */
1470  control_initialize_event_queue();
1471 
1472  /*
1473  * Initialize the scheduler - this has to come after
1474  * options_init_from_torrc() sets up libevent - why yes, that seems
1475  * completely sensible to hide the libevent setup in the option parsing
1476  * code! It also needs to happen before init_keys(), so it needs to
1477  * happen here too. How yucky. */
1478  scheduler_init();
1479  }
1480 
1481  /* Adjust the port configuration so we can launch listeners. */
1482  if (parse_ports(options, 0, msg, &n_ports, NULL)) {
1483  if (!*msg)
1484  *msg = tor_strdup("Unexpected problem parsing port config");
1485  goto rollback;
1486  }
1487 
1488  /* Set the hibernation state appropriately.*/
1489  consider_hibernation(time(NULL));
1490 
1491  /* Launch the listeners. (We do this before we setuid, so we can bind to
1492  * ports under 1024.) We don't want to rebind if we're hibernating or
1493  * shutting down. If networking is disabled, this will close all but the
1494  * control listeners, but disable those. */
1495  if (!we_are_hibernating()) {
1496  if (retry_all_listeners(new_listeners, options->DisableNetwork) < 0) {
1497  *msg = tor_strdup("Failed to bind one of the listener ports.");
1498  goto rollback;
1499  }
1500  }
1501  if (options->DisableNetwork) {
1502  /* Aggressively close non-controller stuff, NOW */
1503  log_notice(LD_NET, "DisableNetwork is set. Tor will not make or accept "
1504  "non-control network connections. Shutting down all existing "
1505  "connections.");
1507  /* We can't complete circuits until the network is re-enabled. */
1509  }
1510  }
1511 
1512 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
1513  /* Open /dev/pf before dropping privileges. */
1514  if (options->TransPort_set &&
1515  options->TransProxyType_parsed == TPT_DEFAULT) {
1516  if (get_pf_socket() < 0) {
1517  *msg = tor_strdup("Unable to open /dev/pf for transparent proxy.");
1518  goto rollback;
1519  }
1520  }
1521 #endif /* defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H) */
1522 
1523  /* Attempt to lock all current and future memory with mlockall() only once */
1524  if (options->DisableAllSwap) {
1525  if (tor_mlockall() == -1) {
1526  *msg = tor_strdup("DisableAllSwap failure. Do you have proper "
1527  "permissions?");
1528  goto done;
1529  }
1530  }
1531 
1532  /* Setuid/setgid as appropriate */
1533  if (options->User) {
1534  tor_assert(have_low_ports != -1);
1535  unsigned switch_id_flags = 0;
1536  if (options->KeepBindCapabilities == 1) {
1537  switch_id_flags |= SWITCH_ID_KEEP_BINDLOW;
1538  switch_id_flags |= SWITCH_ID_WARN_IF_NO_CAPS;
1539  }
1540  if (options->KeepBindCapabilities == -1 && have_low_ports) {
1541  switch_id_flags |= SWITCH_ID_KEEP_BINDLOW;
1542  }
1543  if (switch_id(options->User, switch_id_flags) != 0) {
1544  /* No need to roll back, since you can't change the value. */
1545  *msg = tor_strdup("Problem with User value. See logs for details.");
1546  goto done;
1547  }
1548  }
1549 
1550  /* Ensure data directory is private; create if possible. */
1551  /* It's okay to do this in "options_act_reversible()" even though it isn't
1552  * actually reversible, since you can't change the DataDirectory while
1553  * Tor is running. */
1554  if (check_and_create_data_directory(running_tor /* create */,
1555  options->DataDirectory,
1556  options->DataDirectoryGroupReadable,
1557  options->User,
1558  msg) < 0) {
1559  goto done;
1560  }
1561  if (check_and_create_data_directory(running_tor /* create */,
1562  options->KeyDirectory,
1563  options->KeyDirectoryGroupReadable,
1564  options->User,
1565  msg) < 0) {
1566  goto done;
1567  }
1568 
1569  /* We need to handle the group-readable flag for the cache directory
1570  * specially, since the directory defaults to being the same as the
1571  * DataDirectory. */
1572  int cache_dir_group_readable;
1573  if (options->CacheDirectoryGroupReadable != -1) {
1574  /* If the user specified a value, use their setting */
1575  cache_dir_group_readable = options->CacheDirectoryGroupReadable;
1576  } else if (!strcmp(options->CacheDirectory, options->DataDirectory)) {
1577  /* If the user left the value as "auto", and the cache is the same as the
1578  * datadirectory, use the datadirectory setting.
1579  */
1580  cache_dir_group_readable = options->DataDirectoryGroupReadable;
1581  } else {
1582  /* Otherwise, "auto" means "not group readable". */
1583  cache_dir_group_readable = 0;
1584  }
1585  if (check_and_create_data_directory(running_tor /* create */,
1586  options->CacheDirectory,
1587  cache_dir_group_readable,
1588  options->User,
1589  msg) < 0) {
1590  goto done;
1591  }
1592 
1593  /* Bail out at this point if we're not going to be a client or server:
1594  * we don't run Tor itself. */
1595  if (!running_tor)
1596  goto commit;
1597 
1598  mark_logs_temp(); /* Close current logs once new logs are open. */
1599  logs_marked = 1;
1600  /* Configure the tor_log(s) */
1601  if (options_init_logs(old_options, options, 0)<0) {
1602  *msg = tor_strdup("Failed to init Log options. See logs for details.");
1603  goto rollback;
1604  }
1605  logs_initialized = 1;
1606 
1607  commit:
1608  r = 0;
1609  if (logs_marked) {
1610  log_severity_list_t *severity =
1611  tor_malloc_zero(sizeof(log_severity_list_t));
1612  close_temp_logs();
1616  tor_free(severity);
1618  }
1619  if (logs_initialized) {
1621  }
1622 
1623  {
1624  const char *badness = NULL;
1625  int bad_safelog = 0, bad_severity = 0, new_badness = 0;
1626  if (options->SafeLogging_ != SAFELOG_SCRUB_ALL) {
1627  bad_safelog = 1;
1628  if (!old_options || old_options->SafeLogging_ != options->SafeLogging_)
1629  new_badness = 1;
1630  }
1631  if (get_min_log_level() >= LOG_INFO) {
1632  bad_severity = 1;
1633  if (get_min_log_level() != old_min_log_level)
1634  new_badness = 1;
1635  }
1636  if (bad_safelog && bad_severity)
1637  badness = "you disabled SafeLogging, and "
1638  "you're logging more than \"notice\"";
1639  else if (bad_safelog)
1640  badness = "you disabled SafeLogging";
1641  else
1642  badness = "you're logging more than \"notice\"";
1643  if (new_badness)
1644  log_warn(LD_GENERAL, "Your log may contain sensitive information - %s. "
1645  "Don't log unless it serves an important reason. "
1646  "Overwrite the log afterwards.", badness);
1647  }
1648 
1649  if (set_conn_limit) {
1650  /*
1651  * If we adjusted the conn limit, recompute the OOS threshold too
1652  *
1653  * How many possible sockets to keep in reserve? If we have lots of
1654  * possible sockets, keep this below a limit and set ConnLimit_high_thresh
1655  * very close to ConnLimit_, but if ConnLimit_ is low, shrink it in
1656  * proportion.
1657  *
1658  * Somewhat arbitrarily, set socks_in_reserve to 5% of ConnLimit_, but
1659  * cap it at 64.
1660  */
1661  int socks_in_reserve = options->ConnLimit_ / 20;
1662  if (socks_in_reserve > 64) socks_in_reserve = 64;
1663 
1664  options->ConnLimit_high_thresh = options->ConnLimit_ - socks_in_reserve;
1665  options->ConnLimit_low_thresh = (options->ConnLimit_ / 4) * 3;
1666  log_info(LD_GENERAL,
1667  "Recomputed OOS thresholds: ConnLimit %d, ConnLimit_ %d, "
1668  "ConnLimit_high_thresh %d, ConnLimit_low_thresh %d",
1669  options->ConnLimit, options->ConnLimit_,
1670  options->ConnLimit_high_thresh,
1671  options->ConnLimit_low_thresh);
1672 
1673  /* Give the OOS handler a chance with the new thresholds */
1675  }
1676 
1677  goto done;
1678 
1679  rollback:
1680  r = -1;
1681  tor_assert(*msg);
1682 
1683  if (logs_marked) {
1686  }
1687 
1688  if (set_conn_limit && old_options)
1689  set_max_file_descriptors((unsigned)old_options->ConnLimit,
1690  &options->ConnLimit_);
1691 
1692  SMARTLIST_FOREACH(new_listeners, connection_t *, conn,
1693  {
1694  log_notice(LD_NET, "Closing partially-constructed %s on %s:%d",
1695  conn_type_to_string(conn->type), conn->address, conn->port);
1697  connection_mark_for_close(conn);
1698  });
1699 
1700  done:
1701  smartlist_free(new_listeners);
1702  return r;
1703 }
1704 
1707 int
1708 options_need_geoip_info(const or_options_t *options, const char **reason_out)
1709 {
1710  int bridge_usage = should_record_bridge_info(options);
1711  int routerset_usage =
1712  routerset_needs_geoip(options->EntryNodes) ||
1713  routerset_needs_geoip(options->ExitNodes) ||
1714  routerset_needs_geoip(options->MiddleNodes) ||
1716  routerset_needs_geoip(options->ExcludeNodes) ||
1719 
1720  if (routerset_usage && reason_out) {
1721  *reason_out = "We've been configured to use (or avoid) nodes in certain "
1722  "countries, and we need GEOIP information to figure out which ones they "
1723  "are.";
1724  } else if (bridge_usage && reason_out) {
1725  *reason_out = "We've been configured to see which countries can access "
1726  "us as a bridge, and we need GEOIP information to tell which countries "
1727  "clients are in.";
1728  }
1729  return bridge_usage || routerset_usage;
1730 }
1731 
1734 uint32_t
1736 {
1737  uint64_t bw = options->BandwidthRate;
1738  if (bw > options->MaxAdvertisedBandwidth)
1739  bw = options->MaxAdvertisedBandwidth;
1740  if (options->RelayBandwidthRate > 0 && bw > options->RelayBandwidthRate)
1741  bw = options->RelayBandwidthRate;
1742  /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1743  return (uint32_t)bw;
1744 }
1745 
1748 uint32_t
1750 {
1751  uint64_t bw = options->BandwidthBurst;
1752  if (options->RelayBandwidthBurst > 0 && bw > options->RelayBandwidthBurst)
1753  bw = options->RelayBandwidthBurst;
1754  /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1755  return (uint32_t)bw;
1756 }
1757 
1758 /* Used in the various options_transition_affects* functions. */
1759 #define YES_IF_CHANGED_BOOL(opt) \
1760  if (!CFG_EQ_BOOL(old_options, new_options, opt)) return 1;
1761 #define YES_IF_CHANGED_INT(opt) \
1762  if (!CFG_EQ_INT(old_options, new_options, opt)) return 1;
1763 #define YES_IF_CHANGED_STRING(opt) \
1764  if (!CFG_EQ_STRING(old_options, new_options, opt)) return 1;
1765 #define YES_IF_CHANGED_LINELIST(opt) \
1766  if (!CFG_EQ_LINELIST(old_options, new_options, opt)) return 1;
1767 #define YES_IF_CHANGED_SMARTLIST(opt) \
1768  if (!CFG_EQ_SMARTLIST(old_options, new_options, opt)) return 1;
1769 #define YES_IF_CHANGED_ROUTERSET(opt) \
1770  if (!CFG_EQ_ROUTERSET(old_options, new_options, opt)) return 1;
1771 
1776 static int
1778  const or_options_t *new_options)
1779 {
1780  /* NOTE: Make sure this function stays in sync with
1781  * node_passes_guard_filter */
1782  tor_assert(old_options);
1783  tor_assert(new_options);
1784 
1785  YES_IF_CHANGED_BOOL(UseEntryGuards);
1786  YES_IF_CHANGED_BOOL(UseBridges);
1787  YES_IF_CHANGED_BOOL(ClientUseIPv4);
1788  YES_IF_CHANGED_BOOL(ClientUseIPv6);
1789  YES_IF_CHANGED_BOOL(FascistFirewall);
1790  YES_IF_CHANGED_ROUTERSET(ExcludeNodes);
1791  YES_IF_CHANGED_ROUTERSET(EntryNodes);
1792  YES_IF_CHANGED_SMARTLIST(FirewallPorts);
1793  YES_IF_CHANGED_LINELIST(Bridges);
1794  YES_IF_CHANGED_LINELIST(ReachableORAddresses);
1795  YES_IF_CHANGED_LINELIST(ReachableDirAddresses);
1796 
1797  return 0;
1798 }
1799 
1804 static int
1806  const or_options_t *new_options)
1807 {
1808  tor_assert(old_options);
1809  tor_assert(new_options);
1810 
1811  if (authdir_mode_v3(old_options) != authdir_mode_v3(new_options))
1812  return 1;
1813  if (! authdir_mode_v3(new_options))
1814  return 0;
1815  YES_IF_CHANGED_INT(V3AuthVotingInterval);
1816  YES_IF_CHANGED_INT(V3AuthVoteDelay);
1817  YES_IF_CHANGED_INT(V3AuthDistDelay);
1818  YES_IF_CHANGED_INT(TestingV3AuthInitialVotingInterval);
1819  YES_IF_CHANGED_INT(TestingV3AuthInitialVoteDelay);
1820  YES_IF_CHANGED_INT(TestingV3AuthInitialDistDelay);
1821  YES_IF_CHANGED_INT(TestingV3AuthVotingStartOffset);
1822 
1823  return 0;
1824 }
1825 
1835 STATIC int
1836 options_act(const or_options_t *old_options)
1837 {
1838  config_line_t *cl;
1839  or_options_t *options = get_options_mutable();
1840  int running_tor = options->command == CMD_RUN_TOR;
1841  char *msg=NULL;
1842  const int transition_affects_workers =
1843  old_options && options_transition_affects_workers(old_options, options);
1844  const int transition_affects_guards =
1845  old_options && options_transition_affects_guards(old_options, options);
1846 
1847  if (options->NoExec || options->Sandbox) {
1849  }
1850 
1851  /* disable ptrace and later, other basic debugging techniques */
1852  {
1853  /* Remember if we already disabled debugger attachment */
1854  static int disabled_debugger_attach = 0;
1855  /* Remember if we already warned about being configured not to disable
1856  * debugger attachment */
1857  static int warned_debugger_attach = 0;
1858  /* Don't disable debugger attachment when we're running the unit tests. */
1859  if (options->DisableDebuggerAttachment && !disabled_debugger_attach &&
1860  running_tor) {
1861  int ok = tor_disable_debugger_attach();
1862  /* LCOV_EXCL_START the warned_debugger_attach is 0 can't reach inside. */
1863  if (warned_debugger_attach && ok == 1) {
1864  log_notice(LD_CONFIG, "Disabled attaching debuggers for unprivileged "
1865  "users.");
1866  }
1867  /* LCOV_EXCL_STOP */
1868  disabled_debugger_attach = (ok == 1);
1869  } else if (!options->DisableDebuggerAttachment &&
1870  !warned_debugger_attach) {
1871  log_notice(LD_CONFIG, "Not disabling debugger attaching for "
1872  "unprivileged users.");
1873  warned_debugger_attach = 1;
1874  }
1875  }
1876 
1877  /* Write control ports to disk as appropriate */
1879 
1880  if (running_tor && !have_lockfile()) {
1881  if (try_locking(options, 1) < 0)
1882  return -1;
1883  }
1884 
1885  {
1886  int warning_severity = options->ProtocolWarnings ? LOG_WARN : LOG_INFO;
1887  set_protocol_warning_severity_level(warning_severity);
1888  }
1889 
1890  if (consider_adding_dir_servers(options, old_options) < 0) {
1891  // XXXX This should get validated earlier, and committed here, to
1892  // XXXX lower opportunities for reaching an error case.
1893  return -1;
1894  }
1895 
1896  if (rend_non_anonymous_mode_enabled(options)) {
1897  log_warn(LD_GENERAL, "This copy of Tor was compiled or configured to run "
1898  "in a non-anonymous mode. It will provide NO ANONYMITY.");
1899  }
1900 
1901  /* If we are a bridge with a pluggable transport proxy but no
1902  Extended ORPort, inform the user that they are missing out. */
1903  if (server_mode(options) && options->ServerTransportPlugin &&
1904  !options->ExtORPort_lines) {
1905  log_notice(LD_CONFIG, "We use pluggable transports but the Extended "
1906  "ORPort is disabled. Tor and your pluggable transports proxy "
1907  "communicate with each other via the Extended ORPort so it "
1908  "is suggested you enable it: it will also allow your Bridge "
1909  "to collect statistics about its clients that use pluggable "
1910  "transports. Please enable it using the ExtORPort torrc option "
1911  "(e.g. set 'ExtORPort auto').");
1912  }
1913 
1914  if (options->Bridges) {
1915  mark_bridge_list();
1916  for (cl = options->Bridges; cl; cl = cl->next) {
1917  bridge_line_t *bridge_line = parse_bridge_line(cl->value);
1918  if (!bridge_line) {
1919  // LCOV_EXCL_START
1920  log_warn(LD_BUG,
1921  "Previously validated Bridge line could not be added!");
1922  return -1;
1923  // LCOV_EXCL_STOP
1924  }
1925  bridge_add_from_config(bridge_line);
1926  }
1928  }
1929 
1930  if (running_tor && hs_config_service_all(options, 0)<0) {
1931  // LCOV_EXCL_START
1932  log_warn(LD_BUG,
1933  "Previously validated hidden services line could not be added!");
1934  return -1;
1935  // LCOV_EXCL_STOP
1936  }
1937 
1938  if (running_tor && hs_config_client_auth_all(options, 0) < 0) {
1939  // LCOV_EXCL_START
1940  log_warn(LD_BUG, "Previously validated client authorization for "
1941  "hidden services could not be added!");
1942  return -1;
1943  // LCOV_EXCL_STOP
1944  }
1945 
1946  if (running_tor && !old_options &&
1947  options->OwningControllerFD != UINT64_MAX) {
1948  const unsigned ctrl_flags =
1949  CC_LOCAL_FD_IS_OWNER |
1950  CC_LOCAL_FD_IS_AUTHENTICATED;
1951  tor_socket_t ctrl_sock = (tor_socket_t)options->OwningControllerFD;
1952  if (control_connection_add_local_fd(ctrl_sock, ctrl_flags) < 0) {
1953  log_warn(LD_CONFIG, "Could not add local controller connection with "
1954  "given FD.");
1955  return -1;
1956  }
1957  }
1958 
1959  /* Load state */
1960  if (! or_state_loaded() && running_tor) {
1961  if (or_state_load())
1962  return -1;
1963  rep_hist_load_mtbf_data(time(NULL));
1964  }
1965 
1966  /* If we have an ExtORPort, initialize its auth cookie. */
1967  if (running_tor &&
1968  init_ext_or_cookie_authentication(!!options->ExtORPort_lines) < 0) {
1969  log_warn(LD_CONFIG,"Error creating Extended ORPort cookie file.");
1970  return -1;
1971  }
1972 
1975  if (!options->DisableNetwork) {
1976  if (options->ClientTransportPlugin) {
1977  for (cl = options->ClientTransportPlugin; cl; cl = cl->next) {
1978  if (parse_transport_line(options, cl->value, 0, 0) < 0) {
1979  // LCOV_EXCL_START
1980  log_warn(LD_BUG,
1981  "Previously validated ClientTransportPlugin line "
1982  "could not be added!");
1983  return -1;
1984  // LCOV_EXCL_STOP
1985  }
1986  }
1987  }
1988 
1989  if (options->ServerTransportPlugin && server_mode(options)) {
1990  for (cl = options->ServerTransportPlugin; cl; cl = cl->next) {
1991  if (parse_transport_line(options, cl->value, 0, 1) < 0) {
1992  // LCOV_EXCL_START
1993  log_warn(LD_BUG,
1994  "Previously validated ServerTransportPlugin line "
1995  "could not be added!");
1996  return -1;
1997  // LCOV_EXCL_STOP
1998  }
1999  }
2000  }
2001  }
2003  sweep_proxy_list();
2004 
2005  /* Start the PT proxy configuration. By doing this configuration
2006  here, we also figure out which proxies need to be restarted and
2007  which not. */
2008  if (pt_proxies_configuration_pending() && !net_is_disabled())
2010 
2011  /* Bail out at this point if we're not going to be a client or server:
2012  * we want to not fork, and to log stuff to stderr. */
2013  if (!running_tor)
2014  return 0;
2015 
2016  /* Finish backgrounding the process */
2017  if (options->RunAsDaemon) {
2018  /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
2019  finish_daemon(options->DataDirectory);
2020  }
2021 
2022  /* We want to reinit keys as needed before we do much of anything else:
2023  keys are important, and other things can depend on them. */
2024  if (transition_affects_workers ||
2025  (options->V3AuthoritativeDir && (!old_options ||
2026  !old_options->V3AuthoritativeDir))) {
2027  if (init_keys() < 0) {
2028  log_warn(LD_BUG,"Error initializing keys; exiting");
2029  return -1;
2030  }
2031  }
2032 
2033  /* Write our PID to the PID file. If we do not have write permissions we
2034  * will log a warning and exit. */
2035  if (options->PidFile && !sandbox_is_active()) {
2036  if (write_pidfile(options->PidFile) < 0) {
2037  log_err(LD_CONFIG, "Unable to write PIDFile %s",
2038  escaped(options->PidFile));
2039  return -1;
2040  }
2041  }
2042 
2043  /* Register addressmap directives */
2044  config_register_addressmaps(options);
2045  parse_virtual_addr_network(options->VirtualAddrNetworkIPv4, AF_INET,0,NULL);
2046  parse_virtual_addr_network(options->VirtualAddrNetworkIPv6, AF_INET6,0,NULL);
2047 
2048  /* Update address policies. */
2049  if (policies_parse_from_options(options) < 0) {
2050  /* This should be impossible, but let's be sure. */
2051  log_warn(LD_BUG,"Error parsing already-validated policy options.");
2052  return -1;
2053  }
2054 
2055  if (server_mode(options)) {
2056  static int cdm_initialized = 0;
2057  if (cdm_initialized == 0) {
2058  cdm_initialized = 1;
2059  consdiffmgr_configure(NULL);
2060  consdiffmgr_validate();
2061  }
2062  }
2063 
2064  if (init_control_cookie_authentication(options->CookieAuthentication) < 0) {
2065  log_warn(LD_CONFIG,"Error creating control cookie authentication file.");
2066  return -1;
2067  }
2068 
2070 
2071  /* reload keys as needed for rendezvous services. */
2072  if (hs_service_load_all_keys() < 0) {
2073  log_warn(LD_GENERAL,"Error loading rendezvous service keys");
2074  return -1;
2075  }
2076 
2077  /* Inform the scheduler subsystem that a configuration changed happened. It
2078  * might be a change of scheduler or parameter. */
2080 
2081  /* Set up accounting */
2082  if (accounting_parse_options(options, 0)<0) {
2083  // LCOV_EXCL_START
2084  log_warn(LD_BUG,"Error in previously validated accounting options");
2085  return -1;
2086  // LCOV_EXCL_STOP
2087  }
2088  if (accounting_is_enabled(options))
2089  configure_accounting(time(NULL));
2090 
2091  /* Change the cell EWMA settings */
2092  cmux_ewma_set_options(options, networkstatus_get_latest_consensus());
2093 
2094  /* Update the BridgePassword's hashed version as needed. We store this as a
2095  * digest so that we can do side-channel-proof comparisons on it.
2096  */
2097  if (options->BridgePassword) {
2098  char *http_authenticator;
2099  http_authenticator = alloc_http_authenticator(options->BridgePassword);
2100  if (!http_authenticator) {
2101  // XXXX This should get validated in options_validate().
2102  log_warn(LD_BUG, "Unable to allocate HTTP authenticator. Not setting "
2103  "BridgePassword.");
2104  return -1;
2105  }
2106  options->BridgePassword_AuthDigest_ = tor_malloc(DIGEST256_LEN);
2108  http_authenticator, strlen(http_authenticator),
2109  DIGEST_SHA256);
2110  tor_free(http_authenticator);
2111  }
2112 
2113  if (parse_outbound_addresses(options, 0, &msg) < 0) {
2114  // LCOV_EXCL_START
2115  log_warn(LD_BUG, "Failed parsing previously validated outbound "
2116  "bind addresses: %s", msg);
2117  tor_free(msg);
2118  return -1;
2119  // LCOV_EXCL_STOP
2120  }
2121 
2122  config_maybe_load_geoip_files_(options, old_options);
2123 
2124  if (geoip_is_loaded(AF_INET) && options->GeoIPExcludeUnknown) {
2125  /* ExcludeUnknown is true or "auto" */
2126  const int is_auto = options->GeoIPExcludeUnknown == -1;
2127  int changed;
2128 
2129  changed = routerset_add_unknown_ccs(&options->ExcludeNodes, is_auto);
2130  changed += routerset_add_unknown_ccs(&options->ExcludeExitNodes, is_auto);
2131 
2132  if (changed)
2134  }
2135 
2136  /* Check for transitions that need action. */
2137  if (old_options) {
2138  int revise_trackexithosts = 0;
2139  int revise_automap_entries = 0;
2140  int abandon_circuits = 0;
2141  if ((options->UseEntryGuards && !old_options->UseEntryGuards) ||
2142  options->UseBridges != old_options->UseBridges ||
2143  (options->UseBridges &&
2144  !config_lines_eq(options->Bridges, old_options->Bridges)) ||
2145  !routerset_equal(old_options->ExcludeNodes,options->ExcludeNodes) ||
2146  !routerset_equal(old_options->ExcludeExitNodes,
2147  options->ExcludeExitNodes) ||
2148  !routerset_equal(old_options->EntryNodes, options->EntryNodes) ||
2149  !routerset_equal(old_options->ExitNodes, options->ExitNodes) ||
2150  !routerset_equal(old_options->HSLayer2Nodes,
2151  options->HSLayer2Nodes) ||
2152  !routerset_equal(old_options->HSLayer3Nodes,
2153  options->HSLayer3Nodes) ||
2154  !routerset_equal(old_options->MiddleNodes, options->MiddleNodes) ||
2155  options->StrictNodes != old_options->StrictNodes) {
2156  log_info(LD_CIRC,
2157  "Changed to using entry guards or bridges, or changed "
2158  "preferred or excluded node lists. "
2159  "Abandoning previous circuits.");
2160  abandon_circuits = 1;
2161  }
2162 
2163  if (transition_affects_guards) {
2164  if (guards_update_all()) {
2165  abandon_circuits = 1;
2166  }
2167  }
2168 
2169  if (abandon_circuits) {
2172  revise_trackexithosts = 1;
2173  }
2174 
2175  if (!smartlist_strings_eq(old_options->TrackHostExits,
2176  options->TrackHostExits))
2177  revise_trackexithosts = 1;
2178 
2179  if (revise_trackexithosts)
2181 
2182  if (!options->AutomapHostsOnResolve &&
2183  old_options->AutomapHostsOnResolve) {
2184  revise_automap_entries = 1;
2185  } else {
2186  if (!smartlist_strings_eq(old_options->AutomapHostsSuffixes,
2187  options->AutomapHostsSuffixes))
2188  revise_automap_entries = 1;
2189  else if (!opt_streq(old_options->VirtualAddrNetworkIPv4,
2190  options->VirtualAddrNetworkIPv4) ||
2191  !opt_streq(old_options->VirtualAddrNetworkIPv6,
2192  options->VirtualAddrNetworkIPv6))
2193  revise_automap_entries = 1;
2194  }
2195 
2196  if (revise_automap_entries)
2198 
2199 /* How long should we delay counting bridge stats after becoming a bridge?
2200  * We use this so we don't count clients who used our bridge thinking it is
2201  * a relay. If you change this, don't forget to change the log message
2202  * below. It's 4 hours (the time it takes to stop being used by clients)
2203  * plus some extra time for clock skew. */
2204 #define RELAY_BRIDGE_STATS_DELAY (6 * 60 * 60)
2205 
2206  if (! bool_eq(options->BridgeRelay, old_options->BridgeRelay)) {
2207  int was_relay = 0;
2208  if (options->BridgeRelay) {
2209  time_t int_start = time(NULL);
2210  if (config_lines_eq(old_options->ORPort_lines,options->ORPort_lines)) {
2211  int_start += RELAY_BRIDGE_STATS_DELAY;
2212  was_relay = 1;
2213  }
2214  geoip_bridge_stats_init(int_start);
2215  log_info(LD_CONFIG, "We are acting as a bridge now. Starting new "
2216  "GeoIP stats interval%s.", was_relay ? " in 6 "
2217  "hours from now" : "");
2218  } else {
2220  log_info(LD_GENERAL, "We are no longer acting as a bridge. "
2221  "Forgetting GeoIP stats.");
2222  }
2223  }
2224 
2225  if (transition_affects_workers) {
2226  log_info(LD_GENERAL,
2227  "Worker-related options changed. Rotating workers.");
2228  const int server_mode_turned_on =
2229  server_mode(options) && !server_mode(old_options);
2230  const int dir_server_mode_turned_on =
2231  dir_server_mode(options) && !dir_server_mode(old_options);
2232 
2233  if (server_mode_turned_on || dir_server_mode_turned_on) {
2234  cpu_init();
2235  }
2236 
2237  if (server_mode_turned_on) {
2238  ip_address_changed(0);
2239  if (have_completed_a_circuit() || !any_predicted_circuits(time(NULL)))
2241  }
2243  if (dns_reset())
2244  return -1;
2245  } else {
2246  if (dns_reset())
2247  return -1;
2248  }
2249 
2250  if (options->PerConnBWRate != old_options->PerConnBWRate ||
2251  options->PerConnBWBurst != old_options->PerConnBWBurst)
2252  connection_or_update_token_buckets(get_connection_array(), options);
2253 
2254  if (options->BandwidthRate != old_options->BandwidthRate ||
2255  options->BandwidthBurst != old_options->BandwidthBurst ||
2256  options->RelayBandwidthRate != old_options->RelayBandwidthRate ||
2257  options->RelayBandwidthBurst != old_options->RelayBandwidthBurst)
2258  connection_bucket_adjust(options);
2259 
2260  if (options->MainloopStats != old_options->MainloopStats) {
2262  }
2263  }
2264 
2265  /* Only collect directory-request statistics on relays and bridges. */
2266  options->DirReqStatistics = options->DirReqStatistics_option &&
2267  server_mode(options);
2268  options->HiddenServiceStatistics =
2269  options->HiddenServiceStatistics_option && server_mode(options);
2270 
2271  if (options->CellStatistics || options->DirReqStatistics ||
2272  options->EntryStatistics || options->ExitPortStatistics ||
2273  options->ConnDirectionStatistics ||
2274  options->HiddenServiceStatistics ||
2275  options->BridgeAuthoritativeDir) {
2276  time_t now = time(NULL);
2277  int print_notice = 0;
2278 
2279  /* Only collect other relay-only statistics on relays. */
2280  if (!public_server_mode(options)) {
2281  options->CellStatistics = 0;
2282  options->EntryStatistics = 0;
2283  options->ConnDirectionStatistics = 0;
2284  options->ExitPortStatistics = 0;
2285  }
2286 
2287  if ((!old_options || !old_options->CellStatistics) &&
2288  options->CellStatistics) {
2290  print_notice = 1;
2291  }
2292  if ((!old_options || !old_options->DirReqStatistics) &&
2293  options->DirReqStatistics) {
2294  if (geoip_is_loaded(AF_INET)) {
2296  print_notice = 1;
2297  } else {
2298  /* disable statistics collection since we have no geoip file */
2299  options->DirReqStatistics = 0;
2300  if (options->ORPort_set)
2301  log_notice(LD_CONFIG, "Configured to measure directory request "
2302  "statistics, but no GeoIP database found. "
2303  "Please specify a GeoIP database using the "
2304  "GeoIPFile option.");
2305  }
2306  }
2307  if ((!old_options || !old_options->EntryStatistics) &&
2308  options->EntryStatistics && !should_record_bridge_info(options)) {
2309  /* If we get here, we've started recording bridge info when we didn't
2310  * do so before. Note that "should_record_bridge_info()" will
2311  * always be false at this point, because of the earlier block
2312  * that cleared EntryStatistics when public_server_mode() was false.
2313  * We're leaving it in as defensive programming. */
2314  if (geoip_is_loaded(AF_INET) || geoip_is_loaded(AF_INET6)) {
2316  print_notice = 1;
2317  } else {
2318  options->EntryStatistics = 0;
2319  log_notice(LD_CONFIG, "Configured to measure entry node "
2320  "statistics, but no GeoIP database found. "
2321  "Please specify a GeoIP database using the "
2322  "GeoIPFile option.");
2323  }
2324  }
2325  if ((!old_options || !old_options->ExitPortStatistics) &&
2326  options->ExitPortStatistics) {
2328  print_notice = 1;
2329  }
2330  if ((!old_options || !old_options->ConnDirectionStatistics) &&
2331  options->ConnDirectionStatistics) {
2333  }
2334  if ((!old_options || !old_options->HiddenServiceStatistics) &&
2335  options->HiddenServiceStatistics) {
2336  log_info(LD_CONFIG, "Configured to measure hidden service statistics.");
2338  }
2339  if ((!old_options || !old_options->BridgeAuthoritativeDir) &&
2340  options->BridgeAuthoritativeDir) {
2342  print_notice = 1;
2343  }
2344  if (print_notice)
2345  log_notice(LD_CONFIG, "Configured to measure statistics. Look for "
2346  "the *-stats files that will first be written to the "
2347  "data directory in 24 hours from now.");
2348  }
2349 
2350  /* If we used to have statistics enabled but we just disabled them,
2351  stop gathering them. */
2352  if (old_options && old_options->CellStatistics &&
2353  !options->CellStatistics)
2355  if (old_options && old_options->DirReqStatistics &&
2356  !options->DirReqStatistics)
2358  if (old_options && old_options->EntryStatistics &&
2359  !options->EntryStatistics)
2361  if (old_options && old_options->HiddenServiceStatistics &&
2362  !options->HiddenServiceStatistics)
2364  if (old_options && old_options->ExitPortStatistics &&
2365  !options->ExitPortStatistics)
2367  if (old_options && old_options->ConnDirectionStatistics &&
2368  !options->ConnDirectionStatistics)
2370  if (old_options && old_options->BridgeAuthoritativeDir &&
2371  !options->BridgeAuthoritativeDir)
2373 
2374  /* Since our options changed, we might need to regenerate and upload our
2375  * server descriptor.
2376  */
2377  if (!old_options ||
2378  options_transition_affects_descriptor(old_options, options))
2379  mark_my_descriptor_dirty("config change");
2380 
2381  /* We may need to reschedule some directory stuff if our status changed. */
2382  if (old_options) {
2383  if (options_transition_affects_dirauth_timing(old_options, options)) {
2384  voting_schedule_recalculate_timing(options, time(NULL));
2385  reschedule_dirvote(options);
2386  }
2388  directory_fetches_dir_info_early(old_options)) ||
2390  directory_fetches_dir_info_later(old_options))) {
2391  /* Make sure update_router_have_minimum_dir_info() gets called. */
2393  /* We might need to download a new consensus status later or sooner than
2394  * we had expected. */
2396  }
2397  }
2398 
2399  /* DoS mitigation subsystem only applies to public relay. */
2400  if (public_server_mode(options)) {
2401  /* If we are configured as a relay, initialize the subsystem. Even on HUP,
2402  * this is safe to call as it will load data from the current options
2403  * or/and the consensus. */
2404  dos_init();
2405  } else if (old_options && public_server_mode(old_options)) {
2406  /* Going from relay to non relay, clean it up. */
2407  dos_free_all();
2408  }
2409 
2410  /* Load the webpage we're going to serve every time someone asks for '/' on
2411  our DirPort. */
2413  if (options->DirPortFrontPage) {
2415  read_file_to_str(options->DirPortFrontPage, 0, NULL);
2417  log_warn(LD_CONFIG,
2418  "DirPortFrontPage file '%s' not found. Continuing anyway.",
2419  options->DirPortFrontPage);
2420  }
2421  }
2422 
2423  return 0;
2424 }
2425 
2426 typedef enum {
2427  TAKES_NO_ARGUMENT = 0,
2428  ARGUMENT_NECESSARY = 1,
2429  ARGUMENT_OPTIONAL = 2
2430 } takes_argument_t;
2431 
2432 static const struct {
2433  const char *name;
2434  takes_argument_t takes_argument;
2435 } CMDLINE_ONLY_OPTIONS[] = {
2436  { "-f", ARGUMENT_NECESSARY },
2437  { "--allow-missing-torrc", TAKES_NO_ARGUMENT },
2438  { "--defaults-torrc", ARGUMENT_NECESSARY },
2439  { "--hash-password", ARGUMENT_NECESSARY },
2440  { "--dump-config", ARGUMENT_OPTIONAL },
2441  { "--list-fingerprint", TAKES_NO_ARGUMENT },
2442  { "--keygen", TAKES_NO_ARGUMENT },
2443  { "--key-expiration", ARGUMENT_OPTIONAL },
2444  { "--newpass", TAKES_NO_ARGUMENT },
2445  { "--no-passphrase", TAKES_NO_ARGUMENT },
2446  { "--passphrase-fd", ARGUMENT_NECESSARY },
2447  { "--verify-config", TAKES_NO_ARGUMENT },
2448  { "--ignore-missing-torrc", TAKES_NO_ARGUMENT },
2449  { "--quiet", TAKES_NO_ARGUMENT },
2450  { "--hush", TAKES_NO_ARGUMENT },
2451  { "--version", TAKES_NO_ARGUMENT },
2452  { "--list-modules", TAKES_NO_ARGUMENT },
2453  { "--library-versions", TAKES_NO_ARGUMENT },
2454  { "-h", TAKES_NO_ARGUMENT },
2455  { "--help", TAKES_NO_ARGUMENT },
2456  { "--list-torrc-options", TAKES_NO_ARGUMENT },
2457  { "--list-deprecated-options",TAKES_NO_ARGUMENT },
2458  { "--nt-service", TAKES_NO_ARGUMENT },
2459  { "-nt-service", TAKES_NO_ARGUMENT },
2460  { NULL, 0 },
2461 };
2462 
2468 int
2469 config_parse_commandline(int argc, char **argv, int ignore_errors,
2470  config_line_t **result,
2471  config_line_t **cmdline_result)
2472 {
2473  config_line_t *param = NULL;
2474 
2475  config_line_t *front = NULL;
2476  config_line_t **new = &front;
2477 
2478  config_line_t *front_cmdline = NULL;
2479  config_line_t **new_cmdline = &front_cmdline;
2480 
2481  char *s, *arg;
2482  int i = 1;
2483 
2484  while (i < argc) {
2485  unsigned command = CONFIG_LINE_NORMAL;
2486  takes_argument_t want_arg = ARGUMENT_NECESSARY;
2487  int is_cmdline = 0;
2488  int j;
2489 
2490  for (j = 0; CMDLINE_ONLY_OPTIONS[j].name != NULL; ++j) {
2491  if (!strcmp(argv[i], CMDLINE_ONLY_OPTIONS[j].name)) {
2492  is_cmdline = 1;
2493  want_arg = CMDLINE_ONLY_OPTIONS[j].takes_argument;
2494  break;
2495  }
2496  }
2497 
2498  s = argv[i];
2499 
2500  /* Each keyword may be prefixed with one or two dashes. */
2501  if (*s == '-')
2502  s++;
2503  if (*s == '-')
2504  s++;
2505  /* Figure out the command, if any. */
2506  if (*s == '+') {
2507  s++;
2508  command = CONFIG_LINE_APPEND;
2509  } else if (*s == '/') {
2510  s++;
2511  command = CONFIG_LINE_CLEAR;
2512  /* A 'clear' command has no argument. */
2513  want_arg = 0;
2514  }
2515 
2516  const int is_last = (i == argc-1);
2517 
2518  if (want_arg == ARGUMENT_NECESSARY && is_last) {
2519  if (ignore_errors) {
2520  arg = tor_strdup("");
2521  } else {
2522  log_warn(LD_CONFIG,"Command-line option '%s' with no value. Failing.",
2523  argv[i]);
2524  config_free_lines(front);
2525  config_free_lines(front_cmdline);
2526  return -1;
2527  }
2528  } else if (want_arg == ARGUMENT_OPTIONAL && is_last) {
2529  arg = tor_strdup("");
2530  } else {
2531  arg = (want_arg != TAKES_NO_ARGUMENT) ? tor_strdup(argv[i+1]) :
2532  tor_strdup("");
2533  }
2534 
2535  param = tor_malloc_zero(sizeof(config_line_t));
2536  param->key = is_cmdline ? tor_strdup(argv[i]) :
2537  tor_strdup(config_expand_abbrev(&options_format, s, 1, 1));
2538  param->value = arg;
2539  param->command = command;
2540  param->next = NULL;
2541  log_debug(LD_CONFIG, "command line: parsed keyword '%s', value '%s'",
2542  param->key, param->value);
2543 
2544  if (is_cmdline) {
2545  *new_cmdline = param;
2546  new_cmdline = &((*new_cmdline)->next);
2547  } else {
2548  *new = param;
2549  new = &((*new)->next);
2550  }
2551 
2552  i += want_arg ? 2 : 1;
2553  }
2554  *cmdline_result = front_cmdline;
2555  *result = front;
2556  return 0;
2557 }
2558 
2560 int
2561 option_is_recognized(const char *key)
2562 {
2563  const config_var_t *var = config_find_option(&options_format, key);
2564  return (var != NULL);
2565 }
2566 
2569 const char *
2571 {
2572  const config_var_t *var = config_find_option(&options_format, key);
2573  return var ? var->name : NULL;
2574 }
2575 
2578 config_line_t *
2579 option_get_assignment(const or_options_t *options, const char *key)
2580 {
2581  return config_get_assigned_option(&options_format, options, key, 1);
2582 }
2583 
2594 options_trial_assign(config_line_t *list, unsigned flags, char **msg)
2595 {
2596  int r;
2597  or_options_t *trial_options = config_dup(&options_format, get_options());
2598 
2599  if ((r=config_assign(&options_format, trial_options,
2600  list, flags, msg)) < 0) {
2601  or_options_free(trial_options);
2602  return r;
2603  }
2604 
2605  setopt_err_t rv;
2606  or_options_t *cur_options = get_options_mutable();
2607 
2609 
2610  if (options_validate(cur_options, trial_options,
2611  global_default_options, 1, msg) < 0) {
2612  or_options_free(trial_options);
2613  rv = SETOPT_ERR_PARSE; /*XXX make this a separate return value. */
2614  goto done;
2615  }
2616 
2617  if (options_transition_allowed(cur_options, trial_options, msg) < 0) {
2618  or_options_free(trial_options);
2619  rv = SETOPT_ERR_TRANSITION;
2620  goto done;
2621  }
2623 
2624  if (set_options(trial_options, msg)<0) {
2625  or_options_free(trial_options);
2626  rv = SETOPT_ERR_SETTING;
2627  goto done;
2628  }
2629 
2630  /* we liked it. put it in place. */
2631  rv = SETOPT_OK;
2632  done:
2634  return rv;
2635 }
2636 
2638 static void
2640 {
2641  printf(
2642 "Copyright (c) 2001-2004, Roger Dingledine\n"
2643 "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
2644 "Copyright (c) 2007-2019, The Tor Project, Inc.\n\n"
2645 "tor -f <torrc> [args]\n"
2646 "See man page for options, or https://www.torproject.org/ for "
2647 "documentation.\n");
2648 }
2649 
2651 static void
2653 {
2654  int i;
2655  for (i = 0; option_vars_[i].name; ++i) {
2656  const config_var_t *var = &option_vars_[i];
2657  if (var->type == CONFIG_TYPE_OBSOLETE ||
2658  var->type == CONFIG_TYPE_LINELIST_V)
2659  continue;
2660  printf("%s\n", var->name);
2661  }
2662 }
2663 
2665 static void
2667 {
2668  const config_deprecation_t *d;
2669  for (d = option_deprecation_notes_; d->name; ++d) {
2670  printf("%s\n", d->name);
2671  }
2672 }
2673 
2675 static void
2677 {
2678  printf("%s: %s\n", "dirauth", have_module_dirauth() ? "yes" : "no");
2679 }
2680 
2682 static uint32_t last_resolved_addr = 0;
2683 
2685 uint32_t
2687 {
2688  return last_resolved_addr;
2689 }
2690 
2692 void
2694 {
2695  last_resolved_addr = 0;
2696 }
2697 
2698 /* Return true if <b>options</b> is using the default authorities, and false
2699  * if any authority-related option has been overridden. */
2700 int
2701 using_default_dir_authorities(const or_options_t *options)
2702 {
2703  return (!options->DirAuthorities && !options->AlternateDirAuthority);
2704 }
2705 
2754 int
2755 resolve_my_address(int warn_severity, const or_options_t *options,
2756  uint32_t *addr_out,
2757  const char **method_out, char **hostname_out)
2758 {
2759  struct in_addr in;
2760  uint32_t addr; /* host order */
2761  char hostname[256];
2762  const char *method_used;
2763  const char *hostname_used;
2764  int explicit_ip=1;
2765  int explicit_hostname=1;
2766  int from_interface=0;
2767  char *addr_string = NULL;
2768  const char *address = options->Address;
2769  int notice_severity = warn_severity <= LOG_NOTICE ?
2770  LOG_NOTICE : warn_severity;
2771 
2772  tor_addr_t myaddr;
2773  tor_assert(addr_out);
2774 
2775  /*
2776  * Step one: Fill in 'hostname' to be our best guess.
2777  */
2778 
2779  if (address && *address) {
2780  strlcpy(hostname, address, sizeof(hostname));
2781  } else { /* then we need to guess our address */
2782  explicit_ip = 0; /* it's implicit */
2783  explicit_hostname = 0; /* it's implicit */
2784 
2785  if (tor_gethostname(hostname, sizeof(hostname)) < 0) {
2786  log_fn(warn_severity, LD_NET,"Error obtaining local hostname");
2787  return -1;
2788  }
2789  log_debug(LD_CONFIG, "Guessed local host name as '%s'", hostname);
2790  }
2791 
2792  /*
2793  * Step two: Now that we know 'hostname', parse it or resolve it. If
2794  * it doesn't parse or resolve, look at the interface address. Set 'addr'
2795  * to be our (host-order) 32-bit answer.
2796  */
2797 
2798  if (tor_inet_aton(hostname, &in) == 0) {
2799  /* then we have to resolve it */
2800  explicit_ip = 0;
2801  if (tor_lookup_hostname(hostname, &addr)) { /* failed to resolve */
2802  uint32_t interface_ip; /* host order */
2803 
2804  if (explicit_hostname) {
2805  log_fn(warn_severity, LD_CONFIG,
2806  "Could not resolve local Address '%s'. Failing.", hostname);
2807  return -1;
2808  }
2809  log_fn(notice_severity, LD_CONFIG,
2810  "Could not resolve guessed local hostname '%s'. "
2811  "Trying something else.", hostname);
2812  if (get_interface_address(warn_severity, &interface_ip)) {
2813  log_fn(warn_severity, LD_CONFIG,
2814  "Could not get local interface IP address. Failing.");
2815  return -1;
2816  }
2817  from_interface = 1;
2818  addr = interface_ip;
2819  log_fn(notice_severity, LD_CONFIG, "Learned IP address '%s' for "
2820  "local interface. Using that.", fmt_addr32(addr));
2821  strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2822  } else { /* resolved hostname into addr */
2823  tor_addr_from_ipv4h(&myaddr, addr);
2824 
2825  if (!explicit_hostname &&
2826  tor_addr_is_internal(&myaddr, 0)) {
2827  tor_addr_t interface_ip;
2828 
2829  log_fn(notice_severity, LD_CONFIG, "Guessed local hostname '%s' "
2830  "resolves to a private IP address (%s). Trying something "
2831  "else.", hostname, fmt_addr32(addr));
2832 
2833  if (get_interface_address6(warn_severity, AF_INET, &interface_ip)<0) {
2834  log_fn(warn_severity, LD_CONFIG,
2835  "Could not get local interface IP address. Too bad.");
2836  } else if (tor_addr_is_internal(&interface_ip, 0)) {
2837  log_fn(notice_severity, LD_CONFIG,
2838  "Interface IP address '%s' is a private address too. "
2839  "Ignoring.", fmt_addr(&interface_ip));
2840  } else {
2841  from_interface = 1;
2842  addr = tor_addr_to_ipv4h(&interface_ip);
2843  log_fn(notice_severity, LD_CONFIG,
2844  "Learned IP address '%s' for local interface."
2845  " Using that.", fmt_addr32(addr));
2846  strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2847  }
2848  }
2849  }
2850  } else {
2851  addr = ntohl(in.s_addr); /* set addr so that addr_string is not
2852  * illformed */
2853  }
2854 
2855  /*
2856  * Step three: Check whether 'addr' is an internal IP address, and error
2857  * out if it is and we don't want that.
2858  */
2859 
2860  tor_addr_from_ipv4h(&myaddr,addr);
2861 
2862  addr_string = tor_dup_ip(addr);
2863  if (tor_addr_is_internal(&myaddr, 0)) {
2864  /* make sure we're ok with publishing an internal IP */
2865  if (using_default_dir_authorities(options)) {
2866  /* if they are using the default authorities, disallow internal IPs
2867  * always. */
2868  log_fn(warn_severity, LD_CONFIG,
2869  "Address '%s' resolves to private IP address '%s'. "
2870  "Tor servers that use the default DirAuthorities must have "
2871  "public IP addresses.", hostname, addr_string);
2872  tor_free(addr_string);
2873  return -1;
2874  }
2875  if (!explicit_ip) {
2876  /* even if they've set their own authorities, require an explicit IP if
2877  * they're using an internal address. */
2878  log_fn(warn_severity, LD_CONFIG, "Address '%s' resolves to private "
2879  "IP address '%s'. Please set the Address config option to be "
2880  "the IP address you want to use.", hostname, addr_string);
2881  tor_free(addr_string);
2882  return -1;
2883  }
2884  }
2885 
2886  /*
2887  * Step four: We have a winner! 'addr' is our answer for sure, and
2888  * 'addr_string' is its string form. Fill out the various fields to
2889  * say how we decided it.
2890  */
2891 
2892  log_debug(LD_CONFIG, "Resolved Address to '%s'.", addr_string);
2893 
2894  if (explicit_ip) {
2895  method_used = "CONFIGURED";
2896  hostname_used = NULL;
2897  } else if (explicit_hostname) {
2898  method_used = "RESOLVED";
2899  hostname_used = hostname;
2900  } else if (from_interface) {
2901  method_used = "INTERFACE";
2902  hostname_used = NULL;
2903  } else {
2904  method_used = "GETHOSTNAME";
2905  hostname_used = hostname;
2906  }
2907 
2908  *addr_out = addr;
2909  if (method_out)
2910  *method_out = method_used;
2911  if (hostname_out)
2912  *hostname_out = hostname_used ? tor_strdup(hostname_used) : NULL;
2913 
2914  /*
2915  * Step five: Check if the answer has changed since last time (or if
2916  * there was no last time), and if so call various functions to keep
2917  * us up-to-date.
2918  */
2919 
2920  if (last_resolved_addr && last_resolved_addr != *addr_out) {
2921  /* Leave this as a notice, regardless of the requested severity,
2922  * at least until dynamic IP address support becomes bulletproof. */
2923  log_notice(LD_NET,
2924  "Your IP address seems to have changed to %s "
2925  "(METHOD=%s%s%s). Updating.",
2926  addr_string, method_used,
2927  hostname_used ? " HOSTNAME=" : "",
2928  hostname_used ? hostname_used : "");
2929  ip_address_changed(0);
2930  }
2931 
2932  if (last_resolved_addr != *addr_out) {
2934  "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s%s%s",
2935  addr_string, method_used,
2936  hostname_used ? " HOSTNAME=" : "",
2937  hostname_used ? hostname_used : "");
2938  }
2939  last_resolved_addr = *addr_out;
2940 
2941  /*
2942  * And finally, clean up and return success.
2943  */
2944 
2945  tor_free(addr_string);
2946  return 0;
2947 }
2948 
2953 is_local_addr, (const tor_addr_t *addr))
2954 {
2955  if (tor_addr_is_internal(addr, 0))
2956  return 1;
2957  /* Check whether ip is on the same /24 as we are. */
2958  if (get_options()->EnforceDistinctSubnets == 0)
2959  return 0;
2960  if (tor_addr_family(addr) == AF_INET) {
2961  uint32_t ip = tor_addr_to_ipv4h(addr);
2962 
2963  /* It's possible that this next check will hit before the first time
2964  * resolve_my_address actually succeeds. (For clients, it is likely that
2965  * resolve_my_address will never be called at all). In those cases,
2966  * last_resolved_addr will be 0, and so checking to see whether ip is on
2967  * the same /24 as last_resolved_addr will be the same as checking whether
2968  * it was on net 0, which is already done by tor_addr_is_internal.
2969  */
2970  if ((last_resolved_addr & (uint32_t)0xffffff00ul)
2971  == (ip & (uint32_t)0xffffff00ul))
2972  return 1;
2973  }
2974  return 0;
2975 }
2976 
2978 or_options_t *
2980 {
2981  return config_new(&options_format);
2982 }
2983 
2986 void
2988 {
2989  config_init(&options_format, options);
2990 }
2991 
2996 char *
2997 options_dump(const or_options_t *options, int how_to_dump)
2998 {
2999  const or_options_t *use_defaults;
3000  int minimal;
3001  switch (how_to_dump) {
3002  case OPTIONS_DUMP_MINIMAL:
3003  use_defaults = global_default_options;
3004  minimal = 1;
3005  break;
3006  case OPTIONS_DUMP_DEFAULTS:
3007  use_defaults = NULL;
3008  minimal = 1;
3009  break;
3010  case OPTIONS_DUMP_ALL:
3011  use_defaults = NULL;
3012  minimal = 0;
3013  break;
3014  default:
3015  log_warn(LD_BUG, "Bogus value for how_to_dump==%d", how_to_dump);
3016  return NULL;
3017  }
3018 
3019  return config_dump(&options_format, use_defaults, options, minimal, 0);
3020 }
3021 
3025 static int
3026 validate_ports_csv(smartlist_t *sl, const char *name, char **msg)
3027 {
3028  int i;
3029  tor_assert(name);
3030 
3031  if (!sl)
3032  return 0;
3033 
3034  SMARTLIST_FOREACH(sl, const char *, cp,
3035  {
3036  i = atoi(cp);
3037  if (i < 1 || i > 65535) {
3038  tor_asprintf(msg, "Port '%s' out of range in %s", cp, name);
3039  return -1;
3040  }
3041  });
3042  return 0;
3043 }
3044 
3049 static int
3050 ensure_bandwidth_cap(uint64_t *value, const char *desc, char **msg)
3051 {
3052  if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
3053  /* This handles an understandable special case where somebody says "2gb"
3054  * whereas our actual maximum is 2gb-1 (INT_MAX) */
3055  --*value;
3056  }
3057  if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
3058  tor_asprintf(msg, "%s (%"PRIu64") must be at most %d",
3059  desc, (*value),
3060  ROUTER_MAX_DECLARED_BANDWIDTH);
3061  return -1;
3062  }
3063  return 0;
3064 }
3065 
3072 static int
3074 {
3075  smartlist_t *list = options->PublishServerDescriptor;
3076  dirinfo_type_t *auth = &options->PublishServerDescriptor_;
3077  *auth = NO_DIRINFO;
3078  if (!list) /* empty list, answer is none */
3079  return 0;
3080  SMARTLIST_FOREACH_BEGIN(list, const char *, string) {
3081  if (!strcasecmp(string, "v1"))
3082  log_warn(LD_CONFIG, "PublishServerDescriptor v1 has no effect, because "
3083  "there are no v1 directory authorities anymore.");
3084  else if (!strcmp(string, "1"))
3085  if (options->BridgeRelay)
3086  *auth |= BRIDGE_DIRINFO;
3087  else
3088  *auth |= V3_DIRINFO;
3089  else if (!strcasecmp(string, "v2"))
3090  log_warn(LD_CONFIG, "PublishServerDescriptor v2 has no effect, because "
3091  "there are no v2 directory authorities anymore.");
3092  else if (!strcasecmp(string, "v3"))
3093  *auth |= V3_DIRINFO;
3094  else if (!strcasecmp(string, "bridge"))
3095  *auth |= BRIDGE_DIRINFO;
3096  else if (!strcasecmp(string, "hidserv"))
3097  log_warn(LD_CONFIG,
3098  "PublishServerDescriptor hidserv is invalid. See "
3099  "PublishHidServDescriptors.");
3100  else if (!strcasecmp(string, "") || !strcmp(string, "0"))
3101  /* no authority */;
3102  else
3103  return -1;
3104  } SMARTLIST_FOREACH_END(string);
3105  return 0;
3106 }
3107 
3110 #define MIN_REND_POST_PERIOD (10*60)
3111 #define MIN_REND_POST_PERIOD_TESTING (5)
3112 
3116 #define MAX_CIRCS_AVAILABLE_TIME (24*60*60)
3117 
3119 #define MAX_DIR_PERIOD ((7*24*60*60)/2)
3120 
3123 #define MIN_MAX_CIRCUIT_DIRTINESS 10
3124 
3127 #define MAX_MAX_CIRCUIT_DIRTINESS (30*24*60*60)
3128 
3131 #define MIN_CIRCUIT_STREAM_TIMEOUT 10
3132 
3138 #define RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT (10)
3139 
3140 static int
3141 options_validate_cb(void *old_options, void *options, void *default_options,
3142  int from_setconf, char **msg)
3143 {
3145  int rv = options_validate(old_options, options, default_options,
3146  from_setconf, msg);
3148  return rv;
3149 }
3150 
3152 static void
3153 options_free_cb(void *options)
3154 {
3155  or_options_free_(options);
3156 }
3157 
3158 #define REJECT(arg) \
3159  STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
3160 #if defined(__GNUC__) && __GNUC__ <= 3
3161 #define COMPLAIN(args...) \
3162  STMT_BEGIN log_warn(LD_CONFIG, args); STMT_END
3163 #else
3164 #define COMPLAIN(args, ...) \
3165  STMT_BEGIN log_warn(LD_CONFIG, args, ##__VA_ARGS__); STMT_END
3166 #endif /* defined(__GNUC__) && __GNUC__ <= 3 */
3167 
3176 static int
3178  char *filepath)
3179 {
3180  if (filepath && path_is_relative(filepath)) {
3181  char *abs_path = make_path_absolute(filepath);
3182  COMPLAIN("Path for %s (%s) is relative and will resolve to %s."
3183  " Is this what you wanted?", option, filepath, abs_path);
3184  tor_free(abs_path);
3185  return 1;
3186  }
3187  return 0;
3188 }
3189 
3195 static int
3197 {
3198  tor_assert(options);
3199  int n = 0;
3200 
3201  n += warn_if_option_path_is_relative("CookieAuthFile",
3202  options->CookieAuthFile);
3203  n += warn_if_option_path_is_relative("ExtORPortCookieAuthFile",
3204  options->ExtORPortCookieAuthFile);
3205  n += warn_if_option_path_is_relative("DirPortFrontPage",
3206  options->DirPortFrontPage);
3207  n += warn_if_option_path_is_relative("V3BandwidthsFile",
3208  options->V3BandwidthsFile);
3209  n += warn_if_option_path_is_relative("ControlPortWriteToFile",
3210  options->ControlPortWriteToFile);
3211  n += warn_if_option_path_is_relative("GeoIPFile",options->GeoIPFile);
3212  n += warn_if_option_path_is_relative("GeoIPv6File",options->GeoIPv6File);
3213  n += warn_if_option_path_is_relative("Log",options->DebugLogFile);
3214  n += warn_if_option_path_is_relative("AccelDir",options->AccelDir);
3215  n += warn_if_option_path_is_relative("DataDirectory",options->DataDirectory);
3216  n += warn_if_option_path_is_relative("PidFile",options->PidFile);
3217  n += warn_if_option_path_is_relative("ClientOnionAuthDir",
3218  options->ClientOnionAuthDir);
3219 
3220  for (config_line_t *hs_line = options->RendConfigLines; hs_line;
3221  hs_line = hs_line->next) {
3222  if (!strcasecmp(hs_line->key, "HiddenServiceDir"))
3223  n += warn_if_option_path_is_relative("HiddenServiceDir",hs_line->value);
3224  }
3225  return n != 0;
3226 }
3227 
3228 /* Validate options related to the scheduler. From the Schedulers list, the
3229  * SchedulerTypes_ list is created with int values so once we select the
3230  * scheduler, which can happen anytime at runtime, we don't have to parse
3231  * strings and thus be quick.
3232  *
3233  * Return 0 on success else -1 and msg is set with an error message. */
3234 static int
3235 options_validate_scheduler(or_options_t *options, char **msg)
3236 {
3237  tor_assert(options);
3238  tor_assert(msg);
3239 
3240  if (!options->Schedulers || smartlist_len(options->Schedulers) == 0) {
3241  REJECT("Empty Schedulers list. Either remove the option so the defaults "
3242  "can be used or set at least one value.");
3243  }
3244  /* Ok, we do have scheduler types, validate them. */
3245  options->SchedulerTypes_ = smartlist_new();
3246  SMARTLIST_FOREACH_BEGIN(options->Schedulers, const char *, type) {
3247  int *sched_type;
3248  if (!strcasecmp("KISTLite", type)) {
3249  sched_type = tor_malloc_zero(sizeof(int));
3250  *sched_type = SCHEDULER_KIST_LITE;
3251  smartlist_add(options->SchedulerTypes_, sched_type);
3252  } else if (!strcasecmp("KIST", type)) {
3253  sched_type = tor_malloc_zero(sizeof(int));
3254  *sched_type = SCHEDULER_KIST;
3255  smartlist_add(options->SchedulerTypes_, sched_type);
3256  } else if (!strcasecmp("Vanilla", type)) {
3257  sched_type = tor_malloc_zero(sizeof(int));
3258  *sched_type = SCHEDULER_VANILLA;
3259  smartlist_add(options->SchedulerTypes_, sched_type);
3260  } else {
3261  tor_asprintf(msg, "Unknown type %s in option Schedulers. "
3262  "Possible values are KIST, KISTLite and Vanilla.",
3263  escaped(type));
3264  return -1;
3265  }
3266  } SMARTLIST_FOREACH_END(type);
3267 
3268  if (options->KISTSockBufSizeFactor < 0) {
3269  REJECT("KISTSockBufSizeFactor must be at least 0");
3270  }
3271 
3272  /* Don't need to validate that the Interval is less than anything because
3273  * zero is valid and all negative values are valid. */
3274  if (options->KISTSchedRunInterval > KIST_SCHED_RUN_INTERVAL_MAX) {
3275  tor_asprintf(msg, "KISTSchedRunInterval must not be more than %d (ms)",
3276  KIST_SCHED_RUN_INTERVAL_MAX);
3277  return -1;
3278  }
3279 
3280  return 0;
3281 }
3282 
3283 /* Validate options related to single onion services.
3284  * Modifies some options that are incompatible with single onion services.
3285  * On failure returns -1, and sets *msg to an error string.
3286  * Returns 0 on success. */
3287 STATIC int
3288 options_validate_single_onion(or_options_t *options, char **msg)
3289 {
3290  /* The two single onion service options must have matching values. */
3291  if (options->HiddenServiceSingleHopMode &&
3292  !options->HiddenServiceNonAnonymousMode) {
3293  REJECT("HiddenServiceSingleHopMode does not provide any server anonymity. "
3294  "It must be used with HiddenServiceNonAnonymousMode set to 1.");
3295  }
3296  if (options->HiddenServiceNonAnonymousMode &&
3297  !options->HiddenServiceSingleHopMode) {
3298  REJECT("HiddenServiceNonAnonymousMode does not provide any server "
3299  "anonymity. It must be used with HiddenServiceSingleHopMode set to "
3300  "1.");
3301  }
3302 
3303  /* Now that we've checked that the two options are consistent, we can safely
3304  * call the rend_service_* functions that abstract these options. */
3305 
3306  /* If you run an anonymous client with an active Single Onion service, the
3307  * client loses anonymity. */
3308  const int client_port_set = (options->SocksPort_set ||
3309  options->TransPort_set ||
3310  options->NATDPort_set ||
3311  options->DNSPort_set ||
3312  options->HTTPTunnelPort_set);
3313  if (rend_service_non_anonymous_mode_enabled(options) && client_port_set) {
3314  REJECT("HiddenServiceNonAnonymousMode is incompatible with using Tor as "
3315  "an anonymous client. Please set Socks/Trans/NATD/DNSPort to 0, or "
3316  "revert HiddenServiceNonAnonymousMode to 0.");
3317  }
3318 
3319  if (rend_service_allow_non_anonymous_connection(options)
3320  && options->UseEntryGuards) {
3321  /* Single Onion services only use entry guards when uploading descriptors;
3322  * all other connections are one-hop. Further, Single Onions causes the
3323  * hidden service code to do things which break the path bias
3324  * detector, and it's far easier to turn off entry guards (and
3325  * thus the path bias detector with it) than to figure out how to
3326  * make path bias compatible with single onions.
3327  */
3328  log_notice(LD_CONFIG,
3329  "HiddenServiceSingleHopMode is enabled; disabling "
3330  "UseEntryGuards.");
3331  options->UseEntryGuards = 0;
3332  }
3333 
3334  return 0;
3335 }
3336 
3350 STATIC int
3352  or_options_t *default_options, int from_setconf, char **msg)
3353 {
3354  config_line_t *cl;
3355  const char *uname = get_uname();
3356  int n_ports=0;
3357  int world_writable_control_socket=0;
3358 
3359  tor_assert(msg);
3360  *msg = NULL;
3361 
3362  if (parse_ports(options, 1, msg, &n_ports,
3363  &world_writable_control_socket) < 0)
3364  return -1;
3365 
3366  /* Set UseEntryGuards from the configured value, before we check it below.
3367  * We change UseEntryGuards when it's incompatible with other options,
3368  * but leave UseEntryGuards_option with the original value.
3369  * Always use the value of UseEntryGuards, not UseEntryGuards_option. */
3370  options->UseEntryGuards = options->UseEntryGuards_option;
3371 
3372  if (server_mode(options) &&
3373  (!strcmpstart(uname, "Windows 95") ||
3374  !strcmpstart(uname, "Windows 98") ||
3375  !strcmpstart(uname, "Windows Me"))) {
3376  log_warn(LD_CONFIG, "Tor is running as a server, but you are "
3377  "running %s; this probably won't work. See "
3378  "https://www.torproject.org/docs/faq.html#BestOSForRelay "
3379  "for details.", uname);
3380  }
3381 
3382  if (parse_outbound_addresses(options, 1, msg) < 0)
3383  return -1;
3384 
3385  if (validate_data_directories(options)<0)
3386  REJECT("Invalid DataDirectory");
3387 
3388  /* need to check for relative paths after we populate
3389  * options->DataDirectory (just above). */
3390  if (warn_about_relative_paths(options) && options->RunAsDaemon) {
3391  REJECT("You have specified at least one relative path (see above) "
3392  "with the RunAsDaemon option. RunAsDaemon is not compatible "
3393  "with relative paths.");
3394  }
3395 
3396  if (options->Nickname == NULL) {
3397  if (server_mode(options)) {
3398  options->Nickname = tor_strdup(UNNAMED_ROUTER_NICKNAME);
3399  }
3400  } else {
3401  if (!is_legal_nickname(options->Nickname)) {
3402  tor_asprintf(msg,
3403  "Nickname '%s', nicknames must be between 1 and 19 characters "
3404  "inclusive, and must contain only the characters [a-zA-Z0-9].",
3405  options->Nickname);
3406  return -1;
3407  }
3408  }
3409 
3410  if (server_mode(options) && !options->ContactInfo)
3411  log_notice(LD_CONFIG, "Your ContactInfo config option is not set. "
3412  "Please consider setting it, so we can contact you if your server is "
3413  "misconfigured or something else goes wrong.");
3414  const char *ContactInfo = options->ContactInfo;
3415  if (ContactInfo && !string_is_utf8(ContactInfo, strlen(ContactInfo)))
3416  REJECT("ContactInfo config option must be UTF-8.");
3417 
3418  check_network_configuration(server_mode(options));
3419 
3420  /* Special case on first boot if no Log options are given. */
3421  if (!options->Logs && !options->RunAsDaemon && !from_setconf) {
3422  if (quiet_level == 0)
3423  config_line_append(&options->Logs, "Log", "notice stdout");
3424  else if (quiet_level == 1)
3425  config_line_append(&options->Logs, "Log", "warn stdout");
3426  }
3427 
3428  /* Validate the tor_log(s) */
3429  if (options_init_logs(old_options, options, 1)<0)
3430  REJECT("Failed to validate Log options. See logs for details.");
3431 
3432  if (authdir_mode(options)) {
3433  /* confirm that our address isn't broken, so we can complain now */
3434  uint32_t tmp;
3435  if (resolve_my_address(LOG_WARN, options, &tmp, NULL, NULL) < 0)
3436  REJECT("Failed to resolve/guess local address. See logs for details.");
3437  }
3438 
3439  if (server_mode(options) && options->RendConfigLines)
3440  log_warn(LD_CONFIG,
3441  "Tor is currently configured as a relay and a hidden service. "
3442  "That's not very secure: you should probably run your hidden service "
3443  "in a separate Tor process, at least -- see "
3444  "https://trac.torproject.org/8742");
3445 
3446  /* XXXX require that the only port not be DirPort? */
3447  /* XXXX require that at least one port be listened-upon. */
3448  if (n_ports == 0 && !options->RendConfigLines)
3449  log_warn(LD_CONFIG,
3450  "SocksPort, TransPort, NATDPort, DNSPort, and ORPort are all "
3451  "undefined, and there aren't any hidden services configured. "
3452  "Tor will still run, but probably won't do anything.");
3453 
3454  options->TransProxyType_parsed = TPT_DEFAULT;
3455 #ifdef USE_TRANSPARENT
3456  if (options->TransProxyType) {
3457  if (!strcasecmp(options->TransProxyType, "default")) {
3458  options->TransProxyType_parsed = TPT_DEFAULT;
3459  } else if (!strcasecmp(options->TransProxyType, "pf-divert")) {
3460 #if !defined(OpenBSD) && !defined( DARWIN )
3461  /* Later versions of OS X have pf */
3462  REJECT("pf-divert is a OpenBSD-specific "
3463  "and OS X/Darwin-specific feature.");
3464 #else
3465  options->TransProxyType_parsed = TPT_PF_DIVERT;
3466 #endif /* !defined(OpenBSD) && !defined( DARWIN ) */
3467  } else if (!strcasecmp(options->TransProxyType, "tproxy")) {
3468 #if !defined(__linux__)
3469  REJECT("TPROXY is a Linux-specific feature.");
3470 #else
3471  options->TransProxyType_parsed = TPT_TPROXY;
3472 #endif
3473  } else if (!strcasecmp(options->TransProxyType, "ipfw")) {
3474 #ifndef KERNEL_MAY_SUPPORT_IPFW
3475  /* Earlier versions of OS X have ipfw */
3476  REJECT("ipfw is a FreeBSD-specific "
3477  "and OS X/Darwin-specific feature.");
3478 #else
3479  options->TransProxyType_parsed = TPT_IPFW;
3480 #endif /* !defined(KERNEL_MAY_SUPPORT_IPFW) */
3481  } else {
3482  REJECT("Unrecognized value for TransProxyType");
3483  }
3484 
3485  if (strcasecmp(options->TransProxyType, "default") &&
3486  !options->TransPort_set) {
3487  REJECT("Cannot use TransProxyType without any valid TransPort.");
3488  }
3489  }
3490 #else /* !(defined(USE_TRANSPARENT)) */
3491  if (options->TransPort_set)
3492  REJECT("TransPort is disabled in this build.");
3493 #endif /* defined(USE_TRANSPARENT) */
3494 
3495  if (options->TokenBucketRefillInterval <= 0
3496  || options->TokenBucketRefillInterval > 1000) {
3497  REJECT("TokenBucketRefillInterval must be between 1 and 1000 inclusive.");
3498  }
3499 
3500  if (options->ExcludeExitNodes || options->ExcludeNodes) {
3504  }
3505 
3506  if (options->NodeFamilies) {
3507  options->NodeFamilySets = smartlist_new();
3508  for (cl = options->NodeFamilies; cl; cl = cl->next) {
3509  routerset_t *rs = routerset_new();
3510  if (routerset_parse(rs, cl->value, cl->key) == 0) {
3511  smartlist_add(options->NodeFamilySets, rs);
3512  } else {
3513  routerset_free(rs);
3514  }
3515  }
3516  }
3517 
3518  if (options->ExcludeNodes && options->StrictNodes) {
3519  COMPLAIN("You have asked to exclude certain relays from all positions "
3520  "in your circuits. Expect hidden services and other Tor "
3521  "features to be broken in unpredictable ways.");
3522  }
3523 
3524  for (cl = options->RecommendedPackages; cl; cl = cl->next) {
3525  if (! validate_recommended_package_line(cl->value)) {
3526  log_warn(LD_CONFIG, "Invalid RecommendedPackage line %s will be ignored",
3527  escaped(cl->value));
3528  }
3529  }
3530 
3531  if (options->AuthoritativeDir) {
3532  if (!options->ContactInfo && !options->TestingTorNetwork)
3533  REJECT("Authoritative directory servers must set ContactInfo");
3534  if (!options->RecommendedClientVersions)
3535  options->RecommendedClientVersions =
3537  if (!options->RecommendedServerVersions)
3538  options->RecommendedServerVersions =
3540  if (options->VersioningAuthoritativeDir &&
3541  (!options->RecommendedClientVersions ||
3542  !options->RecommendedServerVersions))
3543  REJECT("Versioning authoritative dir servers must set "
3544  "Recommended*Versions.");
3545 
3546 #ifdef HAVE_MODULE_DIRAUTH
3547  char *t;
3548  /* Call these functions to produce warnings only. */
3549  t = format_recommended_version_list(options->RecommendedClientVersions, 1);
3550  tor_free(t);
3551  t = format_recommended_version_list(options->RecommendedServerVersions, 1);
3552  tor_free(t);
3553 #endif
3554 
3555  if (options->UseEntryGuards) {
3556  log_info(LD_CONFIG, "Authoritative directory servers can't set "
3557  "UseEntryGuards. Disabling.");
3558  options->UseEntryGuards = 0;
3559  }
3560  if (!options->DownloadExtraInfo && authdir_mode_v3(options)) {
3561  log_info(LD_CONFIG, "Authoritative directories always try to download "
3562  "extra-info documents. Setting DownloadExtraInfo.");
3563  options->DownloadExtraInfo = 1;
3564  }
3565  if (!(options->BridgeAuthoritativeDir ||
3566  options->V3AuthoritativeDir))
3567  REJECT("AuthoritativeDir is set, but none of "
3568  "(Bridge/V3)AuthoritativeDir is set.");
3569 #ifdef HAVE_MODULE_DIRAUTH
3570  /* If we have a v3bandwidthsfile and it's broken, complain on startup */
3571  if (options->V3BandwidthsFile && !old_options) {
3573  NULL);
3574  }
3575  /* same for guardfraction file */
3576  if (options->GuardfractionFile && !old_options) {
3578  }
3579 #endif
3580  }
3581 
3582  if (options->AuthoritativeDir && !options->DirPort_set)
3583  REJECT("Running as authoritative directory, but no DirPort set.");
3584 
3585  if (options->AuthoritativeDir && !options->ORPort_set)
3586  REJECT("Running as authoritative directory, but no ORPort set.");
3587 
3588  if (options->AuthoritativeDir && options->ClientOnly)
3589  REJECT("Running as authoritative directory, but ClientOnly also set.");
3590 
3591  if (options->FetchDirInfoExtraEarly && !options->FetchDirInfoEarly)
3592  REJECT("FetchDirInfoExtraEarly requires that you also set "
3593  "FetchDirInfoEarly");
3594 
3595  if (options->ConnLimit <= 0) {
3596  tor_asprintf(msg,
3597  "ConnLimit must be greater than 0, but was set to %d",
3598  options->ConnLimit);
3599  return -1;
3600  }
3601 
3602  if (options->PathsNeededToBuildCircuits >= 0.0) {
3603  if (options->PathsNeededToBuildCircuits < 0.25) {
3604  log_warn(LD_CONFIG, "PathsNeededToBuildCircuits is too low. Increasing "
3605  "to 0.25");
3606  options->PathsNeededToBuildCircuits = 0.25;
3607  } else if (options->PathsNeededToBuildCircuits > 0.95) {
3608  log_warn(LD_CONFIG, "PathsNeededToBuildCircuits is too high. Decreasing "
3609  "to 0.95");
3610  options->PathsNeededToBuildCircuits = 0.95;
3611  }
3612  }
3613 
3614  if (options->MaxClientCircuitsPending <= 0 ||
3615  options->MaxClientCircuitsPending > MAX_MAX_CLIENT_CIRCUITS_PENDING) {
3616  tor_asprintf(msg,
3617  "MaxClientCircuitsPending must be between 1 and %d, but "
3618  "was set to %d", MAX_MAX_CLIENT_CIRCUITS_PENDING,
3619  options->MaxClientCircuitsPending);
3620  return -1;
3621  }
3622 
3623  if (validate_ports_csv(options->FirewallPorts, "FirewallPorts", msg) < 0)
3624  return -1;
3625 
3626  if (validate_ports_csv(options->LongLivedPorts, "LongLivedPorts", msg) < 0)
3627  return -1;
3628 
3630  "RejectPlaintextPorts", msg) < 0)
3631  return -1;
3632 
3634  "WarnPlaintextPorts", msg) < 0)
3635  return -1;
3636 
3637  if (options->FascistFirewall && !options->ReachableAddresses) {
3638  if (options->FirewallPorts && smartlist_len(options->FirewallPorts)) {
3639  /* We already have firewall ports set, so migrate them to
3640  * ReachableAddresses, which will set ReachableORAddresses and
3641  * ReachableDirAddresses if they aren't set explicitly. */
3642  smartlist_t *instead = smartlist_new();
3643  config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3644  new_line->key = tor_strdup("ReachableAddresses");
3645  /* If we're configured with the old format, we need to prepend some
3646  * open ports. */
3647  SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
3648  {
3649  int p = atoi(portno);
3650  if (p<0) continue;
3651  smartlist_add_asprintf(instead, "*:%d", p);
3652  });
3653  new_line->value = smartlist_join_strings(instead,",",0,NULL);
3654  /* These have been deprecated since 0.1.1.5-alpha-cvs */
3655  log_notice(LD_CONFIG,
3656  "Converting FascistFirewall and FirewallPorts "
3657  "config options to new format: \"ReachableAddresses %s\"",
3658  new_line->value);
3659  options->ReachableAddresses = new_line;
3660  SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
3661  smartlist_free(instead);
3662  } else {
3663  /* We do not have FirewallPorts set, so add 80 to
3664  * ReachableDirAddresses, and 443 to ReachableORAddresses. */
3665  if (!options->ReachableDirAddresses) {
3666  config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3667  new_line->key = tor_strdup("ReachableDirAddresses");
3668  new_line->value = tor_strdup("*:80");
3669  options->ReachableDirAddresses = new_line;
3670  log_notice(LD_CONFIG, "Converting FascistFirewall config option "
3671  "to new format: \"ReachableDirAddresses *:80\"");
3672  }
3673  if (!options->ReachableORAddresses) {
3674  config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3675  new_line->key = tor_strdup("ReachableORAddresses");
3676  new_line->value = tor_strdup("*:443");
3677  options->ReachableORAddresses = new_line;
3678  log_notice(LD_CONFIG, "Converting FascistFirewall config option "
3679  "to new format: \"ReachableORAddresses *:443\"");
3680  }
3681  }
3682  }
3683 
3684  if ((options->ReachableAddresses ||
3685  options->ReachableORAddresses ||
3686  options->ReachableDirAddresses ||
3687  options->ClientUseIPv4 == 0) &&
3688  server_mode(options))
3689  REJECT("Servers must be able to freely connect to the rest "
3690  "of the Internet, so they must not set Reachable*Addresses "
3691  "or FascistFirewall or FirewallPorts or ClientUseIPv4 0.");
3692 
3693  if (options->UseBridges &&
3694  server_mode(options))
3695  REJECT("Servers must be able to freely connect to the rest "
3696  "of the Internet, so they must not set UseBridges.");
3697 
3698  /* If both of these are set, we'll end up with funny behavior where we
3699  * demand enough entrynodes be up and running else we won't build
3700  * circuits, yet we never actually use them. */
3701  if (options->UseBridges && options->EntryNodes)
3702  REJECT("You cannot set both UseBridges and EntryNodes.");
3703 
3704  /* If we have UseBridges as 1 and UseEntryGuards as 0, we end up bypassing
3705  * the use of bridges */
3706  if (options->UseBridges && !options->UseEntryGuards)
3707  REJECT("Setting UseBridges requires also setting UseEntryGuards.");
3708 
3709  options->MaxMemInQueues =
3710  compute_real_max_mem_in_queues(options->MaxMemInQueues_raw,
3711  server_mode(options));
3712  options->MaxMemInQueues_low_threshold = (options->MaxMemInQueues / 4) * 3;
3713 
3714  if (!options->SafeLogging ||
3715  !strcasecmp(options->SafeLogging, "0")) {
3716  options->SafeLogging_ = SAFELOG_SCRUB_NONE;
3717  } else if (!strcasecmp(options->SafeLogging, "relay")) {
3718  options->SafeLogging_ = SAFELOG_SCRUB_RELAY;
3719  } else if (!strcasecmp(options->SafeLogging, "1")) {
3720  options->SafeLogging_ = SAFELOG_SCRUB_ALL;
3721  } else {
3722  tor_asprintf(msg,
3723  "Unrecognized value '%s' in SafeLogging",
3724  escaped(options->SafeLogging));
3725  return -1;
3726  }
3727 
3728  if (compute_publishserverdescriptor(options) < 0) {
3729  tor_asprintf(msg, "Unrecognized value in PublishServerDescriptor");
3730  return -1;
3731  }
3732 
3733  if ((options->BridgeRelay
3735  && (options->PublishServerDescriptor_ & V3_DIRINFO)) {
3736  REJECT("Bridges are not supposed to publish router descriptors to the "
3737  "directory authorities. Please correct your "
3738  "PublishServerDescriptor line.");
3739  }
3740 
3741  if (options->BridgeRelay && options->DirPort_set) {
3742  log_warn(LD_CONFIG, "Can't set a DirPort on a bridge relay; disabling "
3743  "DirPort");
3744  config_free_lines(options->DirPort_lines);
3745  options->DirPort_lines = NULL;
3746  options->DirPort_set = 0;
3747  }
3748 
3749  if (server_mode(options) && options->ConnectionPadding != -1) {
3750  REJECT("Relays must use 'auto' for the ConnectionPadding setting.");
3751  }
3752 
3753  if (server_mode(options) && options->ReducedConnectionPadding != 0) {
3754  REJECT("Relays cannot set ReducedConnectionPadding. ");
3755  }
3756 
3757  if (server_mode(options) && options->CircuitPadding == 0) {
3758  REJECT("Relays cannot set CircuitPadding to 0. ");
3759  }
3760 
3761  if (server_mode(options) && options->ReducedCircuitPadding == 1) {
3762  REJECT("Relays cannot set ReducedCircuitPadding. ");
3763  }
3764 
3765  if (options->BridgeDistribution) {
3766  if (!options->BridgeRelay) {
3767  REJECT("You set BridgeDistribution, but you didn't set BridgeRelay!");
3768  }
3770  REJECT("Invalid BridgeDistribution value.");
3771  }
3772  }
3773 
3774  if (options->MinUptimeHidServDirectoryV2 < 0) {
3775  log_warn(LD_CONFIG, "MinUptimeHidServDirectoryV2 option must be at "
3776  "least 0 seconds. Changing to 0.");
3777  options->MinUptimeHidServDirectoryV2 = 0;
3778  }
3779 
3780  const int min_rendpostperiod =
3781  options->TestingTorNetwork ?
3782  MIN_REND_POST_PERIOD_TESTING : MIN_REND_POST_PERIOD;
3783  if (options->RendPostPeriod < min_rendpostperiod) {
3784  log_warn(LD_CONFIG, "RendPostPeriod option is too short; "
3785  "raising to %d seconds.", min_rendpostperiod);
3786  options->RendPostPeriod = min_rendpostperiod;
3787  }
3788 
3789  if (options->RendPostPeriod > MAX_DIR_PERIOD) {
3790  log_warn(LD_CONFIG, "RendPostPeriod is too large; clipping to %ds.",
3791  MAX_DIR_PERIOD);
3792  options->RendPostPeriod = MAX_DIR_PERIOD;
3793  }
3794 
3795  /* Check the Single Onion Service options */
3796  if (options_validate_single_onion(options, msg) < 0)
3797  return -1;
3798 
3800  // options_t is immutable for new code (the above code is older),
3801  // so just make the user fix the value themselves rather than
3802  // silently keep a shadow value lower than what they asked for.
3803  REJECT("CircuitsAvailableTimeout is too large. Max is 24 hours.");
3804  }
3805 
3806  if (options->EntryNodes && !options->UseEntryGuards) {
3807  REJECT("If EntryNodes is set, UseEntryGuards must be enabled.");
3808  }
3809 
3810  if (!(options->UseEntryGuards) &&
3811  (options->RendConfigLines != NULL) &&
3812  !rend_service_allow_non_anonymous_connection(options)) {
3813  log_warn(LD_CONFIG,
3814  "UseEntryGuards is disabled, but you have configured one or more "
3815  "hidden services on this Tor instance. Your hidden services "
3816  "will be very easy to locate using a well-known attack -- see "
3817  "http://freehaven.net/anonbib/#hs-attack06 for details.");
3818  }
3819 
3820  if (options->NumPrimaryGuards && options->NumEntryGuards &&
3821  options->NumEntryGuards > options->NumPrimaryGuards) {
3822  REJECT("NumEntryGuards must not be greater than NumPrimaryGuards.");
3823  }
3824 
3825  if (options->EntryNodes &&
3826  routerset_is_list(options->EntryNodes) &&
3827  (routerset_len(options->EntryNodes) == 1) &&
3828  (options->RendConfigLines != NULL)) {
3829  tor_asprintf(msg,
3830  "You have one single EntryNodes and at least one hidden service "
3831  "configured. This is bad because it's very easy to locate your "
3832  "entry guard which can then lead to the deanonymization of your "
3833  "hidden service -- for more details, see "
3834  "https://trac.torproject.org/projects/tor/ticket/14917. "
3835  "For this reason, the use of one EntryNodes with an hidden "
3836  "service is prohibited until a better solution is found.");
3837  return -1;
3838  }
3839 
3840  /* Inform the hidden service operator that pinning EntryNodes can possibly
3841  * be harmful for the service anonymity. */
3842  if (options->EntryNodes &&
3843  routerset_is_list(options->EntryNodes) &&
3844  (options->RendConfigLines != NULL)) {
3845  log_warn(LD_CONFIG,
3846  "EntryNodes is set with multiple entries and at least one "
3847  "hidden service is configured. Pinning entry nodes can possibly "
3848  "be harmful to the service anonymity. Because of this, we "
3849  "recommend you either don't do that or make sure you know what "
3850  "you are doing. For more details, please look at "
3851  "https://trac.torproject.org/projects/tor/ticket/21155.");
3852  }
3853 
3854  /* Single Onion Services: non-anonymous hidden services */
3855  if (rend_service_non_anonymous_mode_enabled(options)) {
3856  log_warn(LD_CONFIG,
3857  "HiddenServiceNonAnonymousMode is set. Every hidden service on "
3858  "this tor instance is NON-ANONYMOUS. If "
3859  "the HiddenServiceNonAnonymousMode option is changed, Tor will "
3860  "refuse to launch hidden services from the same directories, to "
3861  "protect your anonymity against config errors. This setting is "
3862  "for experimental use only.");
3863  }
3864 
3865  if (!options->LearnCircuitBuildTimeout && options->CircuitBuildTimeout &&
3867  log_warn(LD_CONFIG,
3868  "CircuitBuildTimeout is shorter (%d seconds) than the recommended "
3869  "minimum (%d seconds), and LearnCircuitBuildTimeout is disabled. "
3870  "If tor isn't working, raise this value or enable "
3871  "LearnCircuitBuildTimeout.",
3872  options->CircuitBuildTimeout,
3874  } else if (!options->LearnCircuitBuildTimeout &&
3875  !options->CircuitBuildTimeout) {
3876  int severity = LOG_NOTICE;
3877  /* Be a little quieter if we've deliberately disabled
3878  * LearnCircuitBuildTimeout. */
3879  if (circuit_build_times_disabled_(options, 1)) {
3880  severity = LOG_INFO;
3881  }
3882  log_fn(severity, LD_CONFIG, "You disabled LearnCircuitBuildTimeout, but "
3883  "didn't specify a CircuitBuildTimeout. I'll pick a plausible "
3884  "default.");
3885  }
3886 
3887  if (options->DormantClientTimeout < 10*60 && !options->TestingTorNetwork) {
3888  REJECT("DormantClientTimeout is too low. It must be at least 10 minutes.");
3889  }
3890 
3891  if (options->PathBiasNoticeRate > 1.0) {
3892  tor_asprintf(msg,
3893  "PathBiasNoticeRate is too high. "
3894  "It must be between 0 and 1.0");
3895  return -1;
3896  }
3897  if (options->PathBiasWarnRate > 1.0) {
3898  tor_asprintf(msg,
3899  "PathBiasWarnRate is too high. "
3900  "It must be between 0 and 1.0");
3901  return -1;
3902  }
3903  if (options->PathBiasExtremeRate > 1.0) {
3904  tor_asprintf(msg,
3905  "PathBiasExtremeRate is too high. "
3906  "It must be between 0 and 1.0");
3907  return -1;
3908  }
3909  if (options->PathBiasNoticeUseRate > 1.0) {
3910  tor_asprintf(msg,
3911  "PathBiasNoticeUseRate is too high. "
3912  "It must be between 0 and 1.0");
3913  return -1;
3914  }
3915  if (options->PathBiasExtremeUseRate > 1.0) {
3916  tor_asprintf(msg,
3917  "PathBiasExtremeUseRate is too high. "
3918  "It must be between 0 and 1.0");
3919  return -1;
3920  }
3921 
3923  log_warn(LD_CONFIG, "MaxCircuitDirtiness option is too short; "
3924  "raising to %d seconds.", MIN_MAX_CIRCUIT_DIRTINESS);
3926  }
3927 
3929  log_warn(LD_CONFIG, "MaxCircuitDirtiness option is too high; "
3930  "setting to %d days.", MAX_MAX_CIRCUIT_DIRTINESS/86400);
3932  }
3933 
3934  if (options->CircuitStreamTimeout &&
3936  log_warn(LD_CONFIG, "CircuitStreamTimeout option is too short; "
3937  "raising to %d seconds.", MIN_CIRCUIT_STREAM_TIMEOUT);
3939  }
3940 
3941  if (options->HeartbeatPeriod &&
3943  !options->TestingTorNetwork) {
3944  log_warn(LD_CONFIG, "HeartbeatPeriod option is too short; "
3945  "raising to %d seconds.", MIN_HEARTBEAT_PERIOD);
3947  }
3948 
3949  if (options->KeepalivePeriod < 1)
3950  REJECT("KeepalivePeriod option must be positive.");
3951 
3952  if (ensure_bandwidth_cap(&options->BandwidthRate,
3953  "BandwidthRate", msg) < 0)
3954  return -1;
3955  if (ensure_bandwidth_cap(&options->BandwidthBurst,
3956  "BandwidthBurst", msg) < 0)
3957  return -1;
3959  "MaxAdvertisedBandwidth", msg) < 0)
3960  return -1;
3962  "RelayBandwidthRate", msg) < 0)
3963  return -1;
3965  "RelayBandwidthBurst", msg) < 0)
3966  return -1;
3967  if (ensure_bandwidth_cap(&options->PerConnBWRate,
3968  "PerConnBWRate", msg) < 0)
3969  return -1;
3970  if (ensure_bandwidth_cap(&options->PerConnBWBurst,
3971  "PerConnBWBurst", msg) < 0)
3972  return -1;
3974  "AuthDirFastGuarantee", msg) < 0)
3975  return -1;
3977  "AuthDirGuardBWGuarantee", msg) < 0)
3978  return -1;
3979 
3980  if (options->RelayBandwidthRate && !options->RelayBandwidthBurst)
3981  options->RelayBandwidthBurst = options->RelayBandwidthRate;
3982  if (options->RelayBandwidthBurst && !options->RelayBandwidthRate)
3983  options->RelayBandwidthRate = options->RelayBandwidthBurst;
3984 
3985  if (server_mode(options)) {
3986  const unsigned required_min_bw =
3987  public_server_mode(options) ?
3988  RELAY_REQUIRED_MIN_BANDWIDTH : BRIDGE_REQUIRED_MIN_BANDWIDTH;
3989  const char * const optbridge =
3990  public_server_mode(options) ? "" : "bridge ";
3991  if (options->BandwidthRate < required_min_bw) {
3992  tor_asprintf(msg,
3993  "BandwidthRate is set to %d bytes/second. "
3994  "For %sservers, it must be at least %u.",
3995  (int)options->BandwidthRate, optbridge,
3996  required_min_bw);
3997  return -1;
3998  } else if (options->MaxAdvertisedBandwidth <
3999  required_min_bw/2) {
4000  tor_asprintf(msg,
4001  "MaxAdvertisedBandwidth is set to %d bytes/second. "
4002  "For %sservers, it must be at least %u.",
4003  (int)options->MaxAdvertisedBandwidth, optbridge,
4004  required_min_bw/2);
4005  return -1;
4006  }
4007  if (options->RelayBandwidthRate &&
4008  options->RelayBandwidthRate < required_min_bw) {
4009  tor_asprintf(msg,
4010  "RelayBandwidthRate is set to %d bytes/second. "
4011  "For %sservers, it must be at least %u.",
4012  (int)options->RelayBandwidthRate, optbridge,
4013  required_min_bw);
4014  return -1;
4015  }
4016  }
4017 
4018  if (options->RelayBandwidthRate > options->RelayBandwidthBurst)
4019  REJECT("RelayBandwidthBurst must be at least equal "
4020  "to RelayBandwidthRate.");
4021 
4022  if (options->BandwidthRate > options->BandwidthBurst)
4023  REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
4024 
4025  /* if they set relaybandwidth* really high but left bandwidth*
4026  * at the default, raise the defaults. */
4027  if (options->RelayBandwidthRate > options->BandwidthRate)
4028  options->BandwidthRate = options->RelayBandwidthRate;
4029  if (options->RelayBandwidthBurst > options->BandwidthBurst)
4030  options->BandwidthBurst = options->RelayBandwidthBurst;
4031 
4032  if (accounting_parse_options(options, 1)<0)
4033  REJECT("Failed to parse accounting options. See logs for details.");
4034 
4035  if (options->AccountingMax) {
4036  if (options->RendConfigLines && server_mode(options)) {
4037  log_warn(LD_CONFIG, "Using accounting with a hidden service and an "
4038  "ORPort is risky: your hidden service(s) and your public "
4039  "address will all turn off at the same time, which may alert "
4040  "observers that they are being run by the same party.");
4041  } else if (config_count_key(options->RendConfigLines,
4042  "HiddenServiceDir") > 1) {
4043  log_warn(LD_CONFIG, "Using accounting with multiple hidden services is "
4044  "risky: they will all turn off at the same time, which may "
4045  "alert observers that they are being run by the same party.");
4046  }
4047  }
4048 
4049  options->AccountingRule = ACCT_MAX;
4050  if (options->AccountingRule_option) {
4051  if (!strcmp(options->AccountingRule_option, "sum"))
4052  options->AccountingRule = ACCT_SUM;
4053  else if (!strcmp(options->AccountingRule_option, "max"))
4054  options->AccountingRule = ACCT_MAX;
4055  else if (!strcmp(options->AccountingRule_option, "in"))
4056  options->AccountingRule = ACCT_IN;
4057  else if (!strcmp(options->AccountingRule_option, "out"))
4058  options->AccountingRule = ACCT_OUT;
4059  else
4060  REJECT("AccountingRule must be 'sum', 'max', 'in', or 'out'");
4061  }
4062 
4063  if (options->DirPort_set && !options->DirCache) {
4064  REJECT("DirPort configured but DirCache disabled. DirPort requires "
4065  "DirCache.");
4066  }
4067 
4068  if (options->BridgeRelay && !options->DirCache) {
4069  REJECT("We're a bridge but DirCache is disabled. BridgeRelay requires "
4070  "DirCache.");
4071  }
4072 
4073  if (server_mode(options)) {
4074  char *dircache_msg = NULL;
4075  if (have_enough_mem_for_dircache(options, 0, &dircache_msg)) {
4076  log_warn(LD_CONFIG, "%s", dircache_msg);
4077  tor_free(dircache_msg);
4078  }
4079  }
4080 
4081  if (options->HTTPProxy) { /* parse it now */
4082  if (tor_addr_port_lookup(options->HTTPProxy,
4083  &options->HTTPProxyAddr, &options->HTTPProxyPort) < 0)
4084  REJECT("HTTPProxy failed to parse or resolve. Please fix.");
4085  if (options->HTTPProxyPort == 0) { /* give it a default */
4086  options->HTTPProxyPort = 80;
4087  }
4088  }
4089 
4090  if (options->HTTPProxyAuthenticator) {
4091  if (strlen(options->HTTPProxyAuthenticator) >= 512)
4092  REJECT("HTTPProxyAuthenticator is too long (>= 512 chars).");
4093  }
4094 
4095  if (options->HTTPSProxy) { /* parse it now */
4096  if (tor_addr_port_lookup(options->HTTPSProxy,
4097  &options->HTTPSProxyAddr, &options->HTTPSProxyPort) <0)
4098  REJECT("HTTPSProxy failed to parse or resolve. Please fix.");
4099  if (options->HTTPSProxyPort == 0) { /* give it a default */
4100  options->HTTPSProxyPort = 443;
4101  }
4102  }
4103 
4104  if (options->HTTPSProxyAuthenticator) {
4105  if (strlen(options->HTTPSProxyAuthenticator) >= 512)
4106  REJECT("HTTPSProxyAuthenticator is too long (>= 512 chars).");
4107  }
4108 
4109  if (options->Socks4Proxy) { /* parse it now */
4110  if (tor_addr_port_lookup(options->Socks4Proxy,
4111  &options->Socks4ProxyAddr,
4112  &options->Socks4ProxyPort) <0)
4113  REJECT("Socks4Proxy failed to parse or resolve. Please fix.");
4114  if (options->Socks4ProxyPort == 0) { /* give it a default */
4115  options->Socks4ProxyPort = 1080;
4116  }
4117  }
4118 
4119  if (options->Socks5Proxy) { /* parse it now */
4120  if (tor_addr_port_lookup(options->Socks5Proxy,
4121  &options->Socks5ProxyAddr,
4122  &options->Socks5ProxyPort) <0)
4123  REJECT("Socks5Proxy failed to parse or resolve. Please fix.");
4124  if (options->Socks5ProxyPort == 0) { /* give it a default */
4125  options->Socks5ProxyPort = 1080;
4126  }
4127  }
4128 
4129  /* Check if more than one exclusive proxy type has been enabled. */
4130  if (!!options->Socks4Proxy + !!options->Socks5Proxy +
4131  !!options->HTTPSProxy > 1)
4132  REJECT("You have configured more than one proxy type. "
4133  "(Socks4Proxy|Socks5Proxy|HTTPSProxy)");
4134 
4135  /* Check if the proxies will give surprising behavior. */
4136  if (options->HTTPProxy && !(options->Socks4Proxy ||
4137  options->Socks5Proxy ||
4138  options->HTTPSProxy)) {
4139  log_warn(LD_CONFIG, "HTTPProxy configured, but no SOCKS proxy or "
4140  "HTTPS proxy configured. Watch out: this configuration will "
4141  "proxy unencrypted directory connections only.");
4142  }
4143 
4144  if (options->Socks5ProxyUsername) {
4145  size_t len;
4146 
4147  len = strlen(options->Socks5ProxyUsername);
4148  if (len < 1 || len > MAX_SOCKS5_AUTH_FIELD_SIZE)
4149  REJECT("Socks5ProxyUsername must be between 1 and 255 characters.");
4150 
4151  if (!options->Socks5ProxyPassword)
4152  REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
4153 
4154  len = strlen(options->Socks5ProxyPassword);
4155  if (len < 1 || len > MAX_SOCKS5_AUTH_FIELD_SIZE)
4156  REJECT("Socks5ProxyPassword must be between 1 and 255 characters.");
4157  } else if (options->Socks5ProxyPassword)
4158  REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
4159 
4160  if (options->HashedControlPassword) {
4162  if (!sl) {
4163  REJECT("Bad HashedControlPassword: wrong length or bad encoding");
4164  } else {
4165  SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
4166  smartlist_free(sl);
4167  }
4168  }
4169 
4170  if (options->HashedControlSessionPassword) {
4172  options->HashedControlSessionPassword);
4173  if (!sl) {
4174  REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
4175  } else {
4176  SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
4177  smartlist_free(sl);
4178  }
4179  }
4180 
4181  if (options->OwningControllerProcess) {
4182  const char *validate_pspec_msg = NULL;
4184  &validate_pspec_msg)) {
4185  tor_asprintf(msg, "Bad OwningControllerProcess: %s",
4186  validate_pspec_msg);
4187  return -1;
4188  }
4189  }
4190 
4191  if ((options->ControlPort_set || world_writable_control_socket) &&
4192  !options->HashedControlPassword &&
4193  !options->HashedControlSessionPassword &&
4194  !options->CookieAuthentication) {
4195  log_warn(LD_CONFIG, "Control%s is %s, but no authentication method "
4196  "has been configured. This means that any program on your "
4197  "computer can reconfigure your Tor. That's bad! You should "
4198  "upgrade your Tor controller as soon as possible.",
4199  options->ControlPort_set ? "Port" : "Socket",
4200  options->ControlPort_set ? "open" : "world writable");
4201  }
4202 
4203  if (options->CookieAuthFileGroupReadable && !options->CookieAuthFile) {
4204  log_warn(LD_CONFIG, "CookieAuthFileGroupReadable is set, but will have "
4205  "no effect: you must specify an explicit CookieAuthFile to "
4206  "have it group-readable.");
4207  }
4208 
4209  if (options->MyFamily_lines && options->BridgeRelay) {
4210  log_warn(LD_CONFIG, "Listing a family for a bridge relay is not "
4211  "supported: it can reveal bridge fingerprints to censors. "
4212  "You should also make sure you aren't listing this bridge's "
4213  "fingerprint in any other MyFamily.");
4214  }
4215  if (options->MyFamily_lines && !options->ContactInfo) {
4216  log_warn(LD_CONFIG, "MyFamily is set but ContactInfo is not configured. "
4217  "ContactInfo should always be set when MyFamily option is too.");
4218  }
4219  if (normalize_nickname_list(&options->MyFamily,
4220  options->MyFamily_lines, "MyFamily", msg))
4221  return -1;
4222  for (cl = options->NodeFamilies; cl; cl = cl->next) {
4223  routerset_t *rs = routerset_new();
4224  if (routerset_parse(rs, cl->value, cl->key)) {
4225  routerset_free(rs);
4226  return -1;
4227  }
4228  routerset_free(rs);
4229  }
4230 
4231  if (validate_addr_policies(options, msg) < 0)
4232  return -1;
4233 
4234  /* If FallbackDir is set, we don't UseDefaultFallbackDirs */
4235  if (options->UseDefaultFallbackDirs && options->FallbackDir) {
4236  log_info(LD_CONFIG, "You have set UseDefaultFallbackDirs 1 and "
4237  "FallbackDir(s). Ignoring UseDefaultFallbackDirs, and "
4238  "using the FallbackDir(s) you have set.");
4239  }
4240 
4241  if (validate_dir_servers(options, old_options) < 0)
4242  REJECT("Directory authority/fallback line did not parse. See logs "
4243  "for details.");
4244 
4245  if (options->UseBridges && !options->Bridges)
4246  REJECT("If you set UseBridges, you must specify at least one bridge.");
4247 
4248  for (cl = options->Bridges; cl; cl = cl->next) {
4249  bridge_line_t *bridge_line = parse_bridge_line(cl->value);
4250  if (!bridge_line)
4251  REJECT("Bridge line did not parse. See logs for details.");
4252  bridge_line_free(bridge_line);
4253  }
4254 
4255  for (cl = options->ClientTransportPlugin; cl; cl = cl->next) {
4256  if (parse_transport_line(options, cl->value, 1, 0) < 0)
4257  REJECT("Invalid client transport line. See logs for details.");
4258  }
4259 
4260  for (cl = options->ServerTransportPlugin; cl; cl = cl->next) {
4261  if (parse_transport_line(options, cl->value, 1, 1) < 0)
4262  REJECT("Invalid server transport line. See logs for details.");
4263  }
4264 
4265  if (options->ServerTransportPlugin && !server_mode(options)) {
4266  log_notice(LD_GENERAL, "Tor is not configured as a relay but you specified"
4267  " a ServerTransportPlugin line (%s). The ServerTransportPlugin "
4268  "line will be ignored.",
4269  escaped(options->ServerTransportPlugin->value));
4270  }
4271 
4272  for (cl = options->ServerTransportListenAddr; cl; cl = cl->next) {
4276  char *bindaddr = get_bindaddr_from_transport_listen_line(cl->value, NULL);
4277  if (!bindaddr)
4278  REJECT("ServerTransportListenAddr did not parse. See logs for details.");
4279  tor_free(bindaddr);
4280  }
4281 
4282  if (options->ServerTransportListenAddr && !options->ServerTransportPlugin) {
4283  log_notice(LD_GENERAL, "You need at least a single managed-proxy to "
4284  "specify a transport listen address. The "
4285  "ServerTransportListenAddr line will be ignored.");
4286  }
4287 
4288  for (cl = options->ServerTransportOptions; cl; cl = cl->next) {
4292  smartlist_t *options_sl =
4293  get_options_from_transport_options_line(cl->value, NULL);
4294  if (!options_sl)
4295  REJECT("ServerTransportOptions did not parse. See logs for details.");
4296 
4297  SMARTLIST_FOREACH(options_sl, char *, cp, tor_free(cp));
4298  smartlist_free(options_sl);
4299  }
4300 
4301  if (options->ConstrainedSockets) {
4302  /* If the user wants to constrain socket buffer use, make sure the desired
4303  * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
4304  if (options->ConstrainedSockSize < MIN_CONSTRAINED_TCP_BUFFER ||
4305  options->ConstrainedSockSize > MAX_CONSTRAINED_TCP_BUFFER ||
4306  options->ConstrainedSockSize % 1024) {
4307  tor_asprintf(msg,
4308  "ConstrainedSockSize is invalid. Must be a value between %d and %d "
4309  "in 1024 byte increments.",
4310  MIN_CONSTRAINED_TCP_BUFFER, MAX_CONSTRAINED_TCP_BUFFER);
4311  return -1;
4312  }
4313  if (options->DirPort_set) {
4314  /* Providing cached directory entries while system TCP buffers are scarce
4315  * will exacerbate the socket errors. Suggest that this be disabled. */
4316  COMPLAIN("You have requested constrained socket buffers while also "
4317  "serving directory entries via DirPort. It is strongly "
4318  "suggested that you disable serving directory requests when "
4319  "system TCP buffer resources are scarce.");
4320  }
4321  }
4322 
4323  if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
4324  options->V3AuthVotingInterval/2) {
4325  /*
4326  This doesn't work, but it seems like it should:
4327  what code is preventing the interval being less than twice the lead-up?
4328  if (options->TestingTorNetwork) {
4329  if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
4330  options->V3AuthVotingInterval) {
4331  REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than "
4332  "V3AuthVotingInterval");
4333  } else {
4334  COMPLAIN("V3AuthVoteDelay plus V3AuthDistDelay is more than half "
4335  "V3AuthVotingInterval. This may lead to "
4336  "consensus instability, particularly if clocks drift.");
4337  }
4338  } else {
4339  */
4340  REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
4341  "V3AuthVotingInterval");
4342  /*
4343  }
4344  */
4345  }
4346 
4347  if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS) {
4348  if (options->TestingTorNetwork) {
4349  if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS_TESTING) {
4350  REJECT("V3AuthVoteDelay is way too low.");
4351  } else {
4352  COMPLAIN("V3AuthVoteDelay is very low. "
4353  "This may lead to failure to vote for a consensus.");
4354  }
4355  } else {
4356  REJECT("V3AuthVoteDelay is way too low.");
4357  }
4358  }
4359 
4360  if (options->V3AuthDistDelay < MIN_DIST_SECONDS) {
4361  if (options->TestingTorNetwork) {
4362  if (options->V3AuthDistDelay < MIN_DIST_SECONDS_TESTING) {
4363  REJECT("V3AuthDistDelay is way too low.");
4364  } else {
4365  COMPLAIN("V3AuthDistDelay is very low. "
4366  "This may lead to missing votes in a consensus.");
4367  }
4368  } else {
4369  REJECT("V3AuthDistDelay is way too low.");
4370  }
4371  }
4372 
4373  if (options->V3AuthNIntervalsValid < 2)
4374  REJECT("V3AuthNIntervalsValid must be at least 2.");
4375 
4376  if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL) {
4377  if (options->TestingTorNetwork) {
4379  REJECT("V3AuthVotingInterval is insanely low.");
4380  } else {
4381  COMPLAIN("V3AuthVotingInterval is very low. "
4382  "This may lead to failure to synchronise for a consensus.");
4383  }
4384  } else {
4385  REJECT("V3AuthVotingInterval is insanely low.");
4386  }
4387  } else if (options->V3AuthVotingInterval > 24*60*60) {
4388  REJECT("V3AuthVotingInterval is insanely high.");
4389  } else if (((24*60*60) % options->V3AuthVotingInterval) != 0) {
4390  COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
4391  }
4392 
4393  if (hs_config_service_all(options, 1) < 0)
4394  REJECT("Failed to configure rendezvous options. See logs for details.");
4395 
4396  /* Parse client-side authorization for hidden services. */
4397  if (hs_config_client_auth_all(options, 1) < 0)
4398  REJECT("Failed to configure client authorization for hidden services. "
4399  "See logs for details.");
4400 
4402  AF_INET, 1, msg)<0)
4403  return -1;
4405  AF_INET6, 1, msg)<0)
4406  return -1;
4407 
4408  if (options->TestingTorNetwork &&
4409  !(options->DirAuthorities ||
4410  (options->AlternateDirAuthority &&
4411  options->AlternateBridgeAuthority))) {
4412  REJECT("TestingTorNetwork may only be configured in combination with "
4413  "a non-default set of DirAuthority or both of "
4414  "AlternateDirAuthority and AlternateBridgeAuthority configured.");
4415  }
4416 
4417 #define CHECK_DEFAULT(arg) \
4418  STMT_BEGIN \
4419  if (!options->TestingTorNetwork && \
4420  !options->UsingTestNetworkDefaults_ && \
4421  !config_is_same(&options_format,options, \
4422  default_options,#arg)) { \
4423  REJECT(#arg " may only be changed in testing Tor " \
4424  "networks!"); \
4425  } STMT_END
4426  CHECK_DEFAULT(TestingV3AuthInitialVotingInterval);
4427  CHECK_DEFAULT(TestingV3AuthInitialVoteDelay);
4428  CHECK_DEFAULT(TestingV3AuthInitialDistDelay);
4429  CHECK_DEFAULT(TestingV3AuthVotingStartOffset);
4430  CHECK_DEFAULT(TestingAuthDirTimeToLearnReachability);
4431  CHECK_DEFAULT(TestingEstimatedDescriptorPropagationTime);
4432  CHECK_DEFAULT(TestingServerDownloadInitialDelay);
4433  CHECK_DEFAULT(TestingClientDownloadInitialDelay);
4434  CHECK_DEFAULT(TestingServerConsensusDownloadInitialDelay);
4435  CHECK_DEFAULT(TestingClientConsensusDownloadInitialDelay);
4436  CHECK_DEFAULT(TestingBridgeDownloadInitialDelay);
4437  CHECK_DEFAULT(TestingBridgeBootstrapDownloadInitialDelay);
4438  CHECK_DEFAULT(TestingClientMaxIntervalWithoutRequest);
4439  CHECK_DEFAULT(TestingDirConnectionMaxStall);
4440  CHECK_DEFAULT(TestingAuthKeyLifetime);
4441  CHECK_DEFAULT(TestingLinkCertLifetime);
4442  CHECK_DEFAULT(TestingSigningKeySlop);
4443  CHECK_DEFAULT(TestingAuthKeySlop);
4444  CHECK_DEFAULT(TestingLinkKeySlop);
4445 #undef CHECK_DEFAULT
4446 
4447  if (!options->ClientDNSRejectInternalAddresses &&
4448  !(options->DirAuthorities ||
4449  (options->AlternateDirAuthority && options->AlternateBridgeAuthority)))
4450  REJECT("ClientDNSRejectInternalAddresses used for default network.");
4451  if (options->SigningKeyLifetime < options->TestingSigningKeySlop*2)
4452  REJECT("SigningKeyLifetime is too short.");
4453  if (options->TestingLinkCertLifetime < options->TestingAuthKeySlop*2)
4454  REJECT("LinkCertLifetime is too short.");
4455  if (options->TestingAuthKeyLifetime < options->TestingLinkKeySlop*2)
4456  REJECT("TestingAuthKeyLifetime is too short.");
4457 
4459  < MIN_VOTE_INTERVAL_TESTING_INITIAL) {
4460  REJECT("TestingV3AuthInitialVotingInterval is insanely low.");
4461  } else if (((30*60) % options->TestingV3AuthInitialVotingInterval) != 0) {
4462  REJECT("TestingV3AuthInitialVotingInterval does not divide evenly into "
4463  "30 minutes.");
4464  }
4465 
4467  REJECT("TestingV3AuthInitialVoteDelay is way too low.");
4468  }
4469 
4471  REJECT("TestingV3AuthInitialDistDelay is way too low.");
4472  }
4473 
4474  if (options->TestingV3AuthInitialVoteDelay +
4475  options->TestingV3AuthInitialDistDelay >=
4477  REJECT("TestingV3AuthInitialVoteDelay plus TestingV3AuthInitialDistDelay "
4478  "must be less than TestingV3AuthInitialVotingInterval");
4479  }
4480 
4481  if (options->TestingV3AuthVotingStartOffset >
4483  options->V3AuthVotingInterval)) {
4484  REJECT("TestingV3AuthVotingStartOffset is higher than the voting "
4485  "interval.");
4486  } else if (options->TestingV3AuthVotingStartOffset < 0) {
4487  REJECT("TestingV3AuthVotingStartOffset must be non-negative.");
4488  }
4489 
4490  if (options->TestingAuthDirTimeToLearnReachability < 0) {
4491  REJECT("TestingAuthDirTimeToLearnReachability must be non-negative.");
4492  } else if (options->TestingAuthDirTimeToLearnReachability > 2*60*60) {
4493  COMPLAIN("TestingAuthDirTimeToLearnReachability is insanely high.");
4494  }
4495 
4496  if (options->TestingEstimatedDescriptorPropagationTime < 0) {
4497  REJECT("TestingEstimatedDescriptorPropagationTime must be non-negative.");
4498  } else if (options->TestingEstimatedDescriptorPropagationTime > 60*60) {
4499  COMPLAIN("TestingEstimatedDescriptorPropagationTime is insanely high.");
4500  }
4501 
4502  if (options->TestingClientMaxIntervalWithoutRequest < 1) {
4503  REJECT("TestingClientMaxIntervalWithoutRequest is way too low.");
4504  } else if (options->TestingClientMaxIntervalWithoutRequest > 3600) {
4505  COMPLAIN("TestingClientMaxIntervalWithoutRequest is insanely high.");
4506  }
4507 
4508  if (options->TestingDirConnectionMaxStall < 5) {
4509  REJECT("TestingDirConnectionMaxStall is way too low.");
4510  } else if (options->TestingDirConnectionMaxStall > 3600) {
4511  COMPLAIN("TestingDirConnectionMaxStall is insanely high.");
4512  }
4513 
4514  if (options->ClientBootstrapConsensusMaxInProgressTries < 1) {
4515  REJECT("ClientBootstrapConsensusMaxInProgressTries must be greater "
4516  "than 0.");
4517  } else if (options->ClientBootstrapConsensusMaxInProgressTries
4518  > 100) {
4519  COMPLAIN("ClientBootstrapConsensusMaxInProgressTries is insanely "
4520  "high.");
4521  }
4522 
4523  if (options->TestingEnableConnBwEvent &&
4524  !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
4525  REJECT("TestingEnableConnBwEvent may only be changed in testing "
4526  "Tor networks!");
4527  }
4528 
4529  if (options->TestingEnableCellStatsEvent &&
4530  !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
4531  REJECT("TestingEnableCellStatsEvent may only be changed in testing "
4532  "Tor networks!");
4533  }
4534 
4535  if (options->TestingTorNetwork) {
4536  log_warn(LD_CONFIG, "TestingTorNetwork is set. This will make your node "
4537  "almost unusable in the public Tor network, and is "
4538  "therefore only advised if you are building a "
4539  "testing Tor network!");
4540  }
4541 
4542  if (options->AccelName && !options->HardwareAccel)
4543  options->HardwareAccel = 1;
4544  if (options->AccelDir && !options->AccelName)
4545  REJECT("Can't use hardware crypto accelerator dir without engine name.");
4546 
4547  if (options->PublishServerDescriptor)
4548  SMARTLIST_FOREACH(options->PublishServerDescriptor, const char *, pubdes, {
4549  if (!strcmp(pubdes, "1") || !strcmp(pubdes, "0"))
4550  if (smartlist_len(options->PublishServerDescriptor) > 1) {
4551  COMPLAIN("You have passed a list of multiple arguments to the "
4552  "PublishServerDescriptor option that includes 0 or 1. "
4553  "0 or 1 should only be used as the sole argument. "
4554  "This configuration will be rejected in a future release.");
4555  break;
4556  }
4557  });
4558 
4559  if (options->BridgeRelay == 1 && ! options->ORPort_set)
4560  REJECT("BridgeRelay is 1, ORPort is not set. This is an invalid "
4561  "combination.");
4562 
4563  if (options_validate_scheduler(options, msg) < 0) {
4564  return -1;
4565  }
4566 
4567  return 0;
4568 }
4569 
4570 #undef REJECT
4571 #undef COMPLAIN
4572 
4573 /* Given the value that the user has set for MaxMemInQueues, compute the
4574  * actual maximum value. We clip this value if it's too low, and autodetect
4575  * it if it's set to 0. */
4576 STATIC uint64_t
4577 compute_real_max_mem_in_queues(const uint64_t val, int log_guess)
4578 {
4579  uint64_t result;
4580 
4581  if (val == 0) {
4582 #define ONE_GIGABYTE (UINT64_C(1) << 30)
4583 #define ONE_MEGABYTE (UINT64_C(1) << 20)
4584  /* The user didn't pick a memory limit. Choose a very large one
4585  * that is still smaller than the system memory */
4586  static int notice_sent = 0;
4587  size_t ram = 0;
4588  if (get_total_system_memory(&ram) < 0) {
4589  /* We couldn't determine our total system memory! */
4590 #if SIZEOF_VOID_P >= 8
4591  /* 64-bit system. Let's hope for 8 GB. */
4592  result = 8 * ONE_GIGABYTE;
4593 #else
4594  /* (presumably) 32-bit system. Let's hope for 1 GB. */
4595  result = ONE_GIGABYTE;
4596 #endif /* SIZEOF_VOID_P >= 8 */
4597  } else {
4598  /* We detected the amount of memory available. */
4599  uint64_t avail = 0;
4600 
4601 #if SIZEOF_SIZE_T > 4
4602 /* On a 64-bit platform, we consider 8GB "very large". */
4603 #define RAM_IS_VERY_LARGE(x) ((x) >= (8 * ONE_GIGABYTE))
4604 #else
4605 /* On a 32-bit platform, we can't have 8GB of ram. */
4606 #define RAM_IS_VERY_LARGE(x) (0)
4607 #endif
4608 
4609  if (RAM_IS_VERY_LARGE(ram)) {
4610  /* If we have 8 GB, or more, RAM available, we set the MaxMemInQueues
4611  * to 0.4 * RAM. The idea behind this value is that the amount of RAM
4612  * is more than enough for a single relay and should allow the relay
4613  * operator to run two relays if they have additional bandwidth
4614  * available.
4615  */
4616  avail = (ram / 5) * 2;
4617  } else {
4618  /* If we have less than 8 GB of RAM available, we use the "old" default
4619  * for MaxMemInQueues of 0.75 * RAM.
4620  */
4621  avail = (ram / 4) * 3;
4622  }
4623 
4624  /* Make sure it's in range from 0.25 GB to 8 GB for 64-bit and 0.25 to 2
4625  * GB for 32-bit. */
4626  if (avail > MAX_DEFAULT_MEMORY_QUEUE_SIZE) {
4627  /* If you want to use more than this much RAM, you need to configure
4628  it yourself */
4630  } else if (avail < ONE_GIGABYTE / 4) {
4631  result = ONE_GIGABYTE / 4;
4632  } else {
4633  result = avail;
4634  }
4635  }
4636  if (log_guess && ! notice_sent) {
4637  log_notice(LD_CONFIG, "%sMaxMemInQueues is set to %"PRIu64" MB. "
4638  "You can override this by setting MaxMemInQueues by hand.",
4639  ram ? "Based on detected system memory, " : "",
4640  (result / ONE_MEGABYTE));
4641  notice_sent = 1;
4642  }
4643  return result;
4644  } else if (val < ONE_GIGABYTE / 4) {
4645  log_warn(LD_CONFIG, "MaxMemInQueues must be at least 256 MB for now. "
4646  "Ideally, have it as large as you can afford.");
4647  return ONE_GIGABYTE / 4;
4648  } else {
4649  /* The value was fine all along */
4650  return val;
4651  }
4652 }
4653 
4654 /* If we have less than 300 MB suggest disabling dircache */
4655 #define DIRCACHE_MIN_MEM_MB 300
4656 #define DIRCACHE_MIN_MEM_BYTES (DIRCACHE_MIN_MEM_MB*ONE_MEGABYTE)
4657 #define STRINGIFY(val) #val
4658 
4662 STATIC int
4663 have_enough_mem_for_dircache(const or_options_t *options, size_t total_mem,
4664  char **msg)
4665 {
4666  *msg = NULL;
4667  /* XXX We should possibly be looking at MaxMemInQueues here
4668  * unconditionally. Or we should believe total_mem unconditionally. */
4669  if (total_mem == 0) {
4670  if (get_total_system_memory(&total_mem) < 0) {
4671  total_mem = options->MaxMemInQueues >= SIZE_MAX ?
4672  SIZE_MAX : (size_t)options->MaxMemInQueues;
4673  }
4674  }
4675  if (options->DirCache) {
4676  if (total_mem < DIRCACHE_MIN_MEM_BYTES) {
4677  if (options->BridgeRelay) {
4678  tor_asprintf(msg, "Running a Bridge with less than %d MB of memory "
4679  "is not recommended.", DIRCACHE_MIN_MEM_MB);
4680  } else {
4681  tor_asprintf(msg, "Being a directory cache (default) with less than "
4682  "%d MB of memory is not recommended and may consume "
4683  "most of the available resources. Consider disabling "
4684  "this functionality by setting the DirCache option "
4685  "to 0.", DIRCACHE_MIN_MEM_MB);
4686  }
4687  }
4688  } else {
4689  if (total_mem >= DIRCACHE_MIN_MEM_BYTES) {
4690  *msg = tor_strdup("DirCache is disabled and we are configured as a "
4691  "relay. We will not become a Guard.");
4692  }
4693  }
4694  return *msg == NULL ? 0 : -1;
4695 }
4696 #undef STRINGIFY
4697 
4700 static int
4701 opt_streq(const char *s1, const char *s2)
4702 {
4703  return 0 == strcmp_opt(s1, s2);
4704 }
4705 
4707 static int
4709  const or_options_t *new_val,
4710  char **msg)
4711 {
4712  if (!old)
4713  return 0;
4714 
4715 #define BAD_CHANGE_TO(opt, how) do { \
4716  *msg = tor_strdup("While Tor is running"how", changing " #opt \
4717  " is not allowed"); \
4718  return -1; \
4719  } while (0)
4720 
4721 #define NO_CHANGE_BOOL(opt) \
4722  if (! CFG_EQ_BOOL(old, new_val, opt)) BAD_CHANGE_TO(opt,"")
4723 #define NO_CHANGE_INT(opt) \
4724  if (! CFG_EQ_INT(old, new_val, opt)) BAD_CHANGE_TO(opt,"")
4725 #define NO_CHANGE_STRING(opt) \
4726  if (! CFG_EQ_STRING(old, new_val, opt)) BAD_CHANGE_TO(opt,"")
4727 
4728  NO_CHANGE_STRING(PidFile);
4729  NO_CHANGE_BOOL(RunAsDaemon);
4730  NO_CHANGE_BOOL(Sandbox);
4731  NO_CHANGE_STRING(DataDirectory);
4732  NO_CHANGE_STRING(KeyDirectory);
4733  NO_CHANGE_STRING(CacheDirectory);
4734  NO_CHANGE_STRING(User);
4735  NO_CHANGE_BOOL(KeepBindCapabilities);
4736  NO_CHANGE_STRING(SyslogIdentityTag);
4737  NO_CHANGE_STRING(AndroidIdentityTag);
4738  NO_CHANGE_BOOL(HardwareAccel);
4739  NO_CHANGE_STRING(AccelName);
4740  NO_CHANGE_STRING(AccelDir);
4741  NO_CHANGE_BOOL(TestingTorNetwork);
4742  NO_CHANGE_BOOL(DisableAllSwap);
4743  NO_CHANGE_INT(TokenBucketRefillInterval);
4744  NO_CHANGE_BOOL(HiddenServiceSingleHopMode);
4745  NO_CHANGE_BOOL(HiddenServiceNonAnonymousMode);
4746  NO_CHANGE_BOOL(DisableDebuggerAttachment);
4747  NO_CHANGE_BOOL(NoExec);
4748  NO_CHANGE_INT(OwningControllerFD);
4749  NO_CHANGE_BOOL(DisableSignalHandlers);
4750 
4751  if (sandbox_is_active()) {
4752 #define SB_NOCHANGE_STR(opt) \
4753  if (! CFG_EQ_STRING(old, new_val, opt)) \
4754  BAD_CHANGE_TO(opt," with Sandbox active")
4755 #define SB_NOCHANGE_LINELIST(opt) \
4756  if (! CFG_EQ_LINELIST(old, new_val, opt)) \
4757  BAD_CHANGE_TO(opt," with Sandbox active")
4758 #define SB_NOCHANGE_INT(opt) \
4759  if (! CFG_EQ_INT(old, new_val, opt)) \
4760  BAD_CHANGE_TO(opt," with Sandbox active")
4761 
4762  SB_NOCHANGE_STR(Address);
4763  SB_NOCHANGE_STR(ServerDNSResolvConfFile);
4764  SB_NOCHANGE_STR(DirPortFrontPage);
4765  SB_NOCHANGE_STR(CookieAuthFile);
4766  SB_NOCHANGE_STR(ExtORPortCookieAuthFile);
4767  SB_NOCHANGE_LINELIST(Logs);
4768  SB_NOCHANGE_INT(ConnLimit);
4769 
4770  if (server_mode(old) != server_mode(new_val)) {
4771  *msg = tor_strdup("Can't start/stop being a server while "
4772  "Sandbox is active");
4773  return -1;
4774  }
4775  }
4776 
4777 #undef SB_NOCHANGE_LINELIST
4778 #undef SB_NOCHANGE_STR
4779 #undef SB_NOCHANGE_INT
4780 #undef BAD_CHANGE_TO
4781 #undef NO_CHANGE_BOOL
4782 #undef NO_CHANGE_INT
4783 #undef NO_CHANGE_STRING
4784  return 0;
4785 }
4786 
4789 static int
4791  const or_options_t *new_options)
4792 {
4793  YES_IF_CHANGED_STRING(DataDirectory);
4794  YES_IF_CHANGED_INT(NumCPUs);
4795  YES_IF_CHANGED_LINELIST(ORPort_lines);
4796  YES_IF_CHANGED_BOOL(ServerDNSSearchDomains);
4797  YES_IF_CHANGED_BOOL(SafeLogging_);
4798  YES_IF_CHANGED_BOOL(ClientOnly);
4799  YES_IF_CHANGED_BOOL(LogMessageDomains);
4800  YES_IF_CHANGED_LINELIST(Logs);
4801 
4802  if (server_mode(old_options) != server_mode(new_options) ||
4803  public_server_mode(old_options) != public_server_mode(new_options) ||
4804  dir_server_mode(old_options) != dir_server_mode(new_options))
4805  return 1;
4806 
4807  /* Nothing that changed matters. */
4808  return 0;
4809 }
4810 
4813 static int
4815  const or_options_t *new_options)
4816 {
4817  /* XXX We can be smarter here. If your DirPort isn't being
4818  * published and you just turned it off, no need to republish. Etc. */
4819 
4820  YES_IF_CHANGED_STRING(DataDirectory);
4821  YES_IF_CHANGED_STRING(Nickname);
4822  YES_IF_CHANGED_STRING(Address);
4823  YES_IF_CHANGED_LINELIST(ExitPolicy);
4824  YES_IF_CHANGED_BOOL(ExitRelay);
4825  YES_IF_CHANGED_BOOL(ExitPolicyRejectPrivate);
4826  YES_IF_CHANGED_BOOL(ExitPolicyRejectLocalInterfaces);
4827  YES_IF_CHANGED_BOOL(IPv6Exit);
4828  YES_IF_CHANGED_LINELIST(ORPort_lines);
4829  YES_IF_CHANGED_LINELIST(DirPort_lines);
4830  YES_IF_CHANGED_LINELIST(DirPort_lines);
4831  YES_IF_CHANGED_BOOL(ClientOnly);
4832  YES_IF_CHANGED_BOOL(DisableNetwork);
4833  YES_IF_CHANGED_BOOL(PublishServerDescriptor_);
4834  YES_IF_CHANGED_STRING(ContactInfo);
4835  YES_IF_CHANGED_STRING(BridgeDistribution);
4836  YES_IF_CHANGED_LINELIST(MyFamily);
4837  YES_IF_CHANGED_STRING(AccountingStart);
4838  YES_IF_CHANGED_INT(AccountingMax);
4839  YES_IF_CHANGED_INT(AccountingRule);
4840  YES_IF_CHANGED_BOOL(DirCache);
4841  YES_IF_CHANGED_BOOL(AssumeReachable);
4842 
4843  if (get_effective_bwrate(old_options) != get_effective_bwrate(new_options) ||
4844  get_effective_bwburst(old_options) !=
4845  get_effective_bwburst(new_options) ||
4846  public_server_mode(old_options) != public_server_mode(new_options))
4847  return 1;
4848 
4849  return 0;
4850 }
4851 
4852 #ifdef _WIN32
4853 
4855 static char *
4856 get_windows_conf_root(void)
4857 {
4858  static int is_set = 0;
4859  static char path[MAX_PATH*2+1];
4860  TCHAR tpath[MAX_PATH] = {0};
4861 
4862  LPITEMIDLIST idl;
4863  IMalloc *m;
4864  HRESULT result;
4865 
4866  if (is_set)
4867  return path;
4868 
4869  /* Find X:\documents and settings\username\application data\ .
4870  * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
4871  */
4872 #ifdef ENABLE_LOCAL_APPDATA
4873 #define APPDATA_PATH CSIDL_LOCAL_APPDATA
4874 #else
4875 #define APPDATA_PATH CSIDL_APPDATA
4876 #endif
4877  if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, APPDATA_PATH, &idl))) {
4878  getcwd(path,MAX_PATH);
4879  is_set = 1;
4880  log_warn(LD_CONFIG,
4881  "I couldn't find your application data folder: are you "
4882  "running an ancient version of Windows 95? Defaulting to \"%s\"",
4883  path);
4884  return path;
4885  }
4886  /* Convert the path from an "ID List" (whatever that is!) to a path. */
4887  result = SHGetPathFromIDList(idl, tpath);
4888 #ifdef UNICODE
4889  wcstombs(path,tpath,sizeof(path));
4890  path[sizeof(path)-1] = '\0';
4891 #else
4892  strlcpy(path,tpath,sizeof(path));
4893 #endif /* defined(UNICODE) */
4894 
4895  /* Now we need to free the memory that the path-idl was stored in. In
4896  * typical Windows fashion, we can't just call 'free()' on it. */
4897  SHGetMalloc(&m);
4898  if (m) {
4899  m->lpVtbl->Free(m, idl);
4900  m->lpVtbl->Release(m);
4901  }
4902  if (!SUCCEEDED(result)) {
4903  return NULL;
4904  }
4905  strlcat(path,"\\tor",MAX_PATH);
4906  is_set = 1;
4907  return path;
4908 }
4909 #endif /* defined(_WIN32) */
4910 
4913 static const char *
4914 get_default_conf_file(int defaults_file)
4915 {
4916 #ifdef DISABLE_SYSTEM_TORRC
4917  (void) defaults_file;
4918  return NULL;
4919 #elif defined(_WIN32)
4920  if (defaults_file) {
4921  static char defaults_path[MAX_PATH+1];
4922  tor_snprintf(defaults_path, MAX_PATH, "%s\\torrc-defaults",
4923  get_windows_conf_root());
4924  return defaults_path;
4925  } else {
4926  static char path[MAX_PATH+1];
4927  tor_snprintf(path, MAX_PATH, "%s\\torrc",
4928  get_windows_conf_root());
4929  return path;
4930  }
4931 #else
4932  return defaults_file ? CONFDIR "/torrc-defaults" : CONFDIR "/torrc";
4933 #endif /* defined(DISABLE_SYSTEM_TORRC) || ... */
4934 }
4935 
4942 static int
4944  const config_line_t *lst, const char *name,
4945  char **msg)
4946 {
4947  if (!lst)
4948  return 0;
4949 
4950  config_line_t *new_nicknames = NULL;
4951  config_line_t **new_nicknames_next = &new_nicknames;
4952 
4953  const config_line_t *cl;
4954  for (cl = lst; cl; cl = cl->next) {
4955  const char *line = cl->value;
4956  if (!line)
4957  continue;
4958 
4959  int valid_line = 1;
4960  smartlist_t *sl = smartlist_new();
4961  smartlist_split_string(sl, line, ",",
4962  SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK|SPLIT_STRIP_SPACE, 0);
4963  SMARTLIST_FOREACH_BEGIN(sl, char *, s)
4964  {
4965  char *normalized = NULL;
4967  // check if first char is dollar
4968  if (s[0] != '$') {
4969  // Try again but with a dollar symbol prepended
4970  char *prepended;
4971  tor_asprintf(&prepended, "$%s", s);
4972 
4973  if (is_legal_nickname_or_hexdigest(prepended)) {
4974  // The nickname is valid when it's prepended, set it as the
4975  // normalized version
4976  normalized = prepended;
4977  } else {
4978  // Still not valid, free and fallback to error message
4979  tor_free(prepended);
4980  }
4981  }
4982 
4983  if (!normalized) {
4984  tor_asprintf(msg, "Invalid nickname '%s' in %s line", s, name);
4985  valid_line = 0;
4986  break;
4987  }
4988  } else {
4989  normalized = tor_strdup(s);
4990  }
4991 
4992  config_line_t *next = tor_malloc_zero(sizeof(*next));
4993  next->key = tor_strdup(cl->key);
4994  next->value = normalized;
4995  next->next = NULL;
4996 
4997  *new_nicknames_next = next;
4998  new_nicknames_next = &next->next;
4999  } SMARTLIST_FOREACH_END(s);
5000 
5001  SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
5002  smartlist_free(sl);
5003 
5004  if (!valid_line) {
5005  config_free_lines(new_nicknames);
5006  return -1;
5007  }
5008  }
5009 
5010  *normalized_out = new_nicknames;
5011 
5012  return 0;
5013 }
5014 
5026 static char *
5028  int defaults_file,
5029  int *using_default_fname, int *ignore_missing_torrc)
5030 {
5031  char *fname=NULL;
5032  config_line_t *p_index;
5033  const char *fname_opt = defaults_file ? "--defaults-torrc" : "-f";
5034  const char *ignore_opt = defaults_file ? NULL : "--ignore-missing-torrc";
5035 
5036  if (defaults_file)
5037  *ignore_missing_torrc = 1;
5038 
5039  for (p_index = cmd_arg; p_index; p_index = p_index->next) {
5040  if (!strcmp(p_index->key, fname_opt)) {
5041  if (fname) {
5042  log_warn(LD_CONFIG, "Duplicate %s options on command line.",
5043  fname_opt);
5044  tor_free(fname);
5045  }
5046  fname = expand_filename(p_index->value);
5047 
5048  {
5049  char *absfname;
5050  absfname = make_path_absolute(fname);
5051  tor_free(fname);
5052  fname = absfname;
5053  }
5054 
5055  *using_default_fname = 0;
5056  } else if (ignore_opt && !strcmp(p_index->key,ignore_opt)) {
5057  *ignore_missing_torrc = 1;
5058  }
5059  }
5060 
5061  if (*using_default_fname) {
5062  /* didn't find one, try CONFDIR */
5063  const char *dflt = get_default_conf_file(defaults_file);
5064  file_status_t st = file_status(dflt);
5065  if (dflt && (st == FN_FILE || st == FN_EMPTY)) {
5066  fname = tor_strdup(dflt);
5067  } else {
5068 #ifndef _WIN32
5069  char *fn = NULL;
5070  if (!defaults_file) {
5071  fn = expand_filename("~/.torrc");
5072  }
5073  if (fn) {
5074  file_status_t hmst = file_status(fn);
5075  if (hmst == FN_FILE || hmst == FN_EMPTY || dflt == NULL) {
5076  fname = fn;
5077  } else {
5078  tor_free(fn);
5079  fname = tor_strdup(dflt);
5080  }
5081  } else {
5082  fname = dflt ? tor_strdup(dflt) : NULL;
5083  }
5084 #else /* !(!defined(_WIN32)) */
5085  fname = dflt ? tor_strdup(dflt) : NULL;
5086 #endif /* !defined(_WIN32) */
5087  }
5088  }
5089  return fname;
5090 }
5091 
5095 static char *
5097 {
5098  size_t sz_out;
5099 
5100  return read_file_to_str_until_eof(STDIN_FILENO,SIZE_MAX,&sz_out);
5101 }
5102 
5110 static char *
5111 load_torrc_from_disk(config_line_t *cmd_arg, int defaults_file)
5112 {
5113  char *fname=NULL;
5114  char *cf = NULL;
5115  int using_default_torrc = 1;
5116  int ignore_missing_torrc = 0;
5117  char **fname_var = defaults_file ? &torrc_defaults_fname : &torrc_fname;
5118 
5119  if (*fname_var == NULL) {
5120  fname = find_torrc_filename(cmd_arg, defaults_file,
5121  &using_default_torrc, &ignore_missing_torrc);
5122  tor_free(*fname_var);
5123  *fname_var = fname;
5124  } else {
5125  fname = *fname_var;
5126  }
5127  log_debug(LD_CONFIG, "Opening config file \"%s\"", fname?fname:"<NULL>");
5128 
5129  /* Open config file */
5130  file_status_t st = fname ? file_status(fname) : FN_EMPTY;
5131  if (fname == NULL ||
5132  !(st == FN_FILE || st == FN_EMPTY) ||
5133  !(cf = read_file_to_str(fname,0,NULL))) {
5134  if (using_default_torrc == 1 || ignore_missing_torrc) {
5135  if (!defaults_file)
5136  log_notice(LD_CONFIG, "Configuration file \"%s\" not present, "
5137  "using reasonable defaults.", fname);
5138  tor_free(fname); /* sets fname to NULL */
5139  *fname_var = NULL;
5140  cf = tor_strdup("");
5141  } else {
5142  log_warn(LD_CONFIG,
5143  "Unable to open configuration file \"%s\".", fname);
5144  goto err;
5145  }
5146  } else {
5147  log_notice(LD_CONFIG, "Read configuration file \"%s\".", fname);
5148  }
5149 
5150  return cf;
5151  err:
5152  tor_free(fname);
5153  *fname_var = NULL;
5154  return NULL;
5155 }
5156 
5162 int
5163 options_init_from_torrc(int argc, char **argv)
5164 {
5165  char *cf=NULL, *cf_defaults=NULL;
5166  int command;
5167  int retval = -1;
5168  char *command_arg = NULL;
5169  char *errmsg=NULL;
5170  config_line_t *p_index = NULL;
5171  config_line_t *cmdline_only_options = NULL;
5172 
5173  /* Go through command-line variables */
5174  if (! have_parsed_cmdline) {
5175  /* Or we could redo the list every time we pass this place.
5176  * It does not really matter */
5179  goto err;
5180  }
5181  have_parsed_cmdline = 1;
5182  }
5183  cmdline_only_options = global_cmdline_only_options;
5184 
5185  if (config_line_find(cmdline_only_options, "-h") ||
5186  config_line_find(cmdline_only_options, "--help")) {
5187  print_usage();
5188  return 1;
5189  }
5190  if (config_line_find(cmdline_only_options, "--list-torrc-options")) {
5191  /* For validating whether we've documented everything. */
5193  return 1;
5194  }
5195  if (config_line_find(cmdline_only_options, "--list-deprecated-options")) {
5196  /* For validating whether what we have deprecated really exists. */
5198  return 1;
5199  }
5200 
5201  if (config_line_find(cmdline_only_options, "--version")) {
5202  printf("Tor version %s.\n",get_version());
5203  return 1;
5204  }
5205 
5206  if (config_line_find(cmdline_only_options, "--list-modules")) {
5208  return 1;
5209  }
5210 
5211  if (config_line_find(cmdline_only_options, "--library-versions")) {
5212  printf("Tor version %s. \n", get_version());
5213  printf("Library versions\tCompiled\t\tRuntime\n");
5214  printf("Libevent\t\t%-15s\t\t%s\n",
5217 #ifdef ENABLE_OPENSSL
5218  printf("OpenSSL \t\t%-15s\t\t%s\n",
5219  crypto_openssl_get_header_version_str(),
5220  crypto_openssl_get_version_str());
5221 #endif
5222 #ifdef ENABLE_NSS
5223  printf("NSS \t\t%-15s\t\t%s\n",
5224  crypto_nss_get_header_version_str(),
5225  crypto_nss_get_version_str());
5226 #endif
5227  if (tor_compress_supports_method(ZLIB_METHOD)) {
5228  printf("Zlib \t\t%-15s\t\t%s\n",
5229  tor_compress_version_str(ZLIB_METHOD),
5230  tor_compress_header_version_str(ZLIB_METHOD));
5231  }
5232  if (tor_compress_supports_method(LZMA_METHOD)) {
5233  printf("Liblzma \t\t%-15s\t\t%s\n",
5234  tor_compress_version_str(LZMA_METHOD),
5235  tor_compress_header_version_str(LZMA_METHOD));
5236  }
5237  if (tor_compress_supports_method(ZSTD_METHOD)) {
5238  printf("Libzstd \t\t%-15s\t\t%s\n",
5239  tor_compress_version_str(ZSTD_METHOD),
5240  tor_compress_header_version_str(ZSTD_METHOD));
5241  }
5242  //TODO: Hex versions?
5243  return 1;
5244  }
5245 
5246  command = CMD_RUN_TOR;
5247  for (p_index = cmdline_only_options; p_index; p_index = p_index->next) {
5248  if (!strcmp(p_index->key,"--keygen")) {
5249  command = CMD_KEYGEN;
5250  } else if (!strcmp(p_index->key, "--key-expiration")) {
5251  command = CMD_KEY_EXPIRATION;
5252  command_arg = p_index->value;
5253  } else if (!strcmp(p_index->key,"--list-fingerprint")) {
5254  command = CMD_LIST_FINGERPRINT;
5255  } else if (!strcmp(p_index->key, "--hash-password")) {
5256  command = CMD_HASH_PASSWORD;
5257  command_arg = p_index->value;
5258  } else if (!strcmp(p_index->key, "--dump-config")) {
5259  command = CMD_DUMP_CONFIG;
5260  command_arg = p_index->value;
5261  } else if (!strcmp(p_index->key, "--verify-config")) {
5262  command = CMD_VERIFY_CONFIG;
5263  }
5264  }
5265 
5266  if (command == CMD_HASH_PASSWORD) {
5267  cf_defaults = tor_strdup("");
5268  cf = tor_strdup("");
5269  } else {
5270  cf_defaults = load_torrc_from_disk(cmdline_only_options, 1);
5271 
5272  const config_line_t *f_line = config_line_find(cmdline_only_options,
5273  "-f");
5274 
5275  const int read_torrc_from_stdin =
5276  (f_line != NULL && strcmp(f_line->value, "-") == 0);
5277 
5278  if (read_torrc_from_stdin) {
5279  cf = load_torrc_from_stdin();
5280  } else {
5281  cf = load_torrc_from_disk(cmdline_only_options, 0);
5282  }
5283 
5284  if (!cf) {
5285  if (config_line_find(cmdline_only_options, "--allow-missing-torrc")) {
5286  cf = tor_strdup("");
5287  } else {
5288  goto err;
5289  }
5290  }
5291  }
5292 
5293  retval = options_init_from_string(cf_defaults, cf, command, command_arg,
5294  &errmsg);
5295 
5296  if (retval < 0)
5297  goto err;
5298 
5299  if (config_line_find(cmdline_only_options, "--no-passphrase")) {
5300  if (command == CMD_KEYGEN) {
5301  get_options_mutable()->keygen_force_passphrase = FORCE_PASSPHRASE_OFF;
5302  } else {
5303  log_err(LD_CONFIG, "--no-passphrase specified without --keygen!");
5304  retval = -1;
5305  goto err;
5306  }
5307  }
5308 
5309  if (config_line_find(cmdline_only_options, "--newpass")) {
5310  if (command == CMD_KEYGEN) {
5311  get_options_mutable()->change_key_passphrase = 1;
5312  } else {
5313  log_err(LD_CONFIG, "--newpass specified without --keygen!");
5314  retval = -1;
5315  goto err;
5316  }
5317  }
5318 
5319  {
5320  const config_line_t *fd_line = config_line_find(cmdline_only_options,
5321  "--passphrase-fd");
5322  if (fd_line) {
5323  if (get_options()->keygen_force_passphrase == FORCE_PASSPHRASE_OFF) {
5324  log_err(LD_CONFIG, "--no-passphrase specified with --passphrase-fd!");
5325  retval = -1;
5326  goto err;
5327  } else if (command != CMD_KEYGEN) {
5328  log_err(LD_CONFIG, "--passphrase-fd specified without --keygen!");
5329  retval = -1;
5330  goto err;
5331  } else {
5332  const char *v = fd_line->value;
5333  int ok = 1;
5334  long fd = tor_parse_long(v, 10, 0, INT_MAX, &ok, NULL);
5335  if (fd < 0 || ok == 0) {
5336  log_err(LD_CONFIG, "Invalid --passphrase-fd value %s", escaped(v));
5337  retval = -1;
5338  goto err;
5339  }
5340  get_options_mutable()->keygen_passphrase_fd = (int)fd;
5341  get_options_mutable()->use_keygen_passphrase_fd = 1;
5342  get_options_mutable()->keygen_force_passphrase = FORCE_PASSPHRASE_ON;
5343  }
5344  }
5345  }
5346 
5347  {
5348  const config_line_t *key_line = config_line_find(cmdline_only_options,
5349  "--master-key");
5350  if (key_line) {
5351  if (command != CMD_KEYGEN) {
5352  log_err(LD_CONFIG, "--master-key without --keygen!");
5353  retval = -1;
5354  goto err;
5355  } else {
5356  get_options_mutable()->master_key_fname = tor_strdup(key_line->value);
5357  }
5358  }
5359  }
5360 
5361  err:
5362 
5363  tor_free(cf);
5364  tor_free(cf_defaults);
5365  if (errmsg) {
5366  log_warn(LD_CONFIG,"%s", errmsg);
5367  tor_free(errmsg);
5368  }
5369  return retval < 0 ? -1 : 0;
5370 }
5371 
5382 options_init_from_string(const char *cf_defaults, const char *cf,
5383  int command, const char *command_arg,
5384  char **msg)
5385 {
5386  or_options_t *oldoptions, *newoptions, *newdefaultoptions=NULL;
5387  config_line_t *cl;
5388  int retval;
5389  setopt_err_t err = SETOPT_ERR_MISC;
5390  int cf_has_include = 0;
5391  tor_assert(msg);
5392 
5393  oldoptions = global_options; /* get_options unfortunately asserts if
5394  this is the first time we run*/
5395 
5396  newoptions = tor_malloc_zero(sizeof(or_options_t));
5397  newoptions->magic_ = OR_OPTIONS_MAGIC;
5398  options_init(newoptions);
5399  newoptions->command = command;
5400  newoptions->command_arg = command_arg ? tor_strdup(command_arg) : NULL;
5401 
5402  smartlist_t *opened_files = smartlist_new();
5403  for (int i = 0; i < 2; ++i) {
5404  const char *body = i==0 ? cf_defaults : cf;
5405  if (!body)
5406  continue;
5407 
5408  /* get config lines, assign them */
5409  retval = config_get_lines_include(body, &cl, 1,
5410  body == cf ? &cf_has_include : NULL,
5411  opened_files);
5412  if (retval < 0) {
5413  err = SETOPT_ERR_PARSE;
5414  goto err;
5415  }
5416  retval = config_assign(&options_format, newoptions, cl,
5417  CAL_WARN_DEPRECATIONS, msg);
5418  config_free_lines(cl);
5419  if (retval < 0) {
5420  err = SETOPT_ERR_PARSE;
5421  goto err;
5422  }
5423  if (i==0)
5424  newdefaultoptions = config_dup(&options_format, newoptions);
5425  }
5426 
5427  if (newdefaultoptions == NULL) {
5428  newdefaultoptions = config_dup(&options_format, global_default_options);
5429  }
5430 
5431  /* Go through command-line variables too */
5432  retval = config_assign(&options_format, newoptions,
5433  global_cmdline_options, CAL_WARN_DEPRECATIONS, msg);
5434  if (retval < 0) {
5435  err = SETOPT_ERR_PARSE;
5436  goto err;
5437  }
5438 
5439  newoptions->IncludeUsed = cf_has_include;
5440  newoptions->FilesOpenedByIncludes = opened_files;
5441 
5442  /* If this is a testing network configuration, change defaults
5443  * for a list of dependent config options, re-initialize newoptions
5444  * with the new defaults, and assign all options to it second time. */
5445  if (newoptions->TestingTorNetwork) {
5446  /* XXXX this is a bit of a kludge. perhaps there's a better way to do
5447  * this? We could, for example, make the parsing algorithm do two passes
5448  * over the configuration. If it finds any "suite" options like
5449  * TestingTorNetwork, it could change the defaults before its second pass.
5450  * Not urgent so long as this seems to work, but at any sign of trouble,
5451  * let's clean it up. -NM */
5452 
5453  /* Change defaults. */
5454  for (int i = 0; testing_tor_network_defaults[i].name; ++i) {
5455  const config_var_t *new_var = &testing_tor_network_defaults[i];
5456  config_var_t *old_var =
5458  tor_assert(new_var);
5459  tor_assert(old_var);
5460  old_var->initvalue = new_var->initvalue;
5461 
5462  if ((config_find_deprecation(&options_format, new_var->name))) {
5463  log_warn(LD_GENERAL, "Testing options override the deprecated "
5464  "option %s. Is that intentional?",
5465  new_var->name);
5466  }
5467  }
5468 
5469  /* Clear newoptions and re-initialize them with new defaults. */
5470  or_options_free(newoptions);
5471  or_options_free(newdefaultoptions);
5472  newdefaultoptions = NULL;
5473  newoptions = tor_malloc_zero(sizeof(or_options_t));
5474  newoptions->magic_ = OR_OPTIONS_MAGIC;
5475  options_init(newoptions);
5476  newoptions->command = command;
5477  newoptions->command_arg = command_arg ? tor_strdup(command_arg) : NULL;
5478 
5479  /* Assign all options a second time. */
5480  opened_files = smartlist_new();
5481  for (int i = 0; i < 2; ++i) {
5482  const char *body = i==0 ? cf_defaults : cf;
5483  if (!body)
5484  continue;
5485 
5486  /* get config lines, assign them */
5487  retval = config_get_lines_include(body, &cl, 1,
5488  body == cf ? &cf_has_include : NULL,
5489  opened_files);
5490  if (retval < 0) {
5491  err = SETOPT_ERR_PARSE;
5492  goto err;
5493  }
5494  retval = config_assign(&options_format, newoptions, cl, 0, msg);
5495  config_free_lines(cl);
5496  if (retval < 0) {
5497  err = SETOPT_ERR_PARSE;
5498  goto err;
5499  }
5500  if (i==0)
5501  newdefaultoptions = config_dup(&options_format, newoptions);
5502  }
5503  /* Assign command-line variables a second time too */
5504  retval = config_assign(&options_format, newoptions,
5505  global_cmdline_options, 0, msg);
5506  if (retval < 0) {
5507  err = SETOPT_ERR_PARSE;
5508  goto err;
5509  }
5510  }
5511 
5512  newoptions->IncludeUsed = cf_has_include;
5514  newoptions->FilesOpenedByIncludes = opened_files;
5515 
5516  /* Validate newoptions */
5517  if (options_validate(oldoptions, newoptions, newdefaultoptions,
5518  0, msg) < 0) {
5519  err = SETOPT_ERR_PARSE; /*XXX make this a separate return value.*/
5520  goto err;
5521  }
5522 
5523  if (options_transition_allowed(oldoptions, newoptions, msg) < 0) {
5524  err = SETOPT_ERR_TRANSITION;
5525  goto err;
5526  }
5528 
5529  if (set_options(newoptions, msg)) {
5530  err = SETOPT_ERR_SETTING;
5531  goto err; /* frees and replaces old options */
5532  }
5533 
5534  or_options_free(global_default_options);
5535  global_default_options = newdefaultoptions;
5536 
5537  return SETOPT_OK;
5538 
5539  err:
5541  if (opened_files) {
5542  SMARTLIST_FOREACH(opened_files, char *, f, tor_free(f));
5543  smartlist_free(opened_files);
5544  }
5545  // may have been set to opened_files, avoid double free
5546  newoptions->FilesOpenedByIncludes = NULL;
5547  or_options_free(newoptions);
5548  or_options_free(newdefaultoptions);
5549  if (*msg) {
5550  char *old_msg = *msg;
5551  tor_asprintf(msg, "Failed to parse/validate config: %s", old_msg);
5552  tor_free(old_msg);
5553  }
5554  return err;
5555 }
5556 
5559 const char *
5560 get_torrc_fname(int defaults_fname)
5561 {
5562  const char *fname = defaults_fname ? torrc_defaults_fname : torrc_fname;
5563 
5564  if (fname)
5565  return fname;
5566  else
5567  return get_default_conf_file(defaults_fname);
5568 }
5569 
5573 void
5575 {
5576  smartlist_t *elts;
5577  config_line_t *opt;
5578  const char *from, *to, *msg;
5579 
5581  elts = smartlist_new();
5582  for (opt = options->AddressMap; opt; opt = opt->next) {
5583  smartlist_split_string(elts, opt->value, NULL,
5584  SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
5585  if (smartlist_len(elts) < 2) {
5586  log_warn(LD_CONFIG,"MapAddress '%s' has too few arguments. Ignoring.",
5587  opt->value);
5588  goto cleanup;
5589  }
5590 
5591  from = smartlist_get(elts,0);
5592  to = smartlist_get(elts,1);
5593 
5594  if (to[0] == '.' || from[0] == '.') {
5595  log_warn(LD_CONFIG,"MapAddress '%s' is ambiguous - address starts with a"
5596  "'.'. Ignoring.",opt->value);
5597  goto cleanup;
5598  }
5599 
5600  if (addressmap_register_auto(from, to, 0, ADDRMAPSRC_TORRC, &msg) < 0) {
5601  log_warn(LD_CONFIG,"MapAddress '%s' failed: %s. Ignoring.", opt->value,
5602  msg);
5603  goto cleanup;
5604  }
5605 
5606  if (smartlist_len(elts) > 2)
5607  log_warn(LD_CONFIG,"Ignoring extra arguments to MapAddress.");
5608 
5609  cleanup:
5610  SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
5611  smartlist_clear(elts);
5612  }
5613  smartlist_free(elts);
5614 }
5615 
5618 /* XXXX move to connection_edge.c */
5619 int
5620 addressmap_register_auto(const char *from, const char *to,
5621  time_t expires,
5622  addressmap_entry_source_t addrmap_source,
5623  const char **msg)
5624 {
5625  int from_wildcard = 0, to_wildcard = 0;
5626 
5627  *msg = "whoops, forgot the error message";
5628 
5629  if (!strcmp(to, "*") || !strcmp(from, "*")) {
5630  *msg = "can't remap from or to *";
5631  return -1;
5632  }
5633  /* Detect asterisks in expressions of type: '*.example.com' */
5634  if (!strncmp(from,"*.",2)) {
5635  from += 2;
5636  from_wildcard = 1;
5637  }
5638  if (!strncmp(to,"*.",2)) {
5639  to += 2;
5640  to_wildcard = 1;
5641  }
5642 
5643  if (to_wildcard && !from_wildcard) {
5644  *msg = "can only use wildcard (i.e. '*.') if 'from' address "
5645  "uses wildcard also";
5646  return -1;
5647  }
5648 
5649  if (address_is_invalid_destination(to, 1)) {
5650  *msg = "destination is invalid";
5651  return -1;
5652  }
5653 
5654  addressmap_register(from, tor_strdup(to), expires, addrmap_source,
5655  from_wildcard, to_wildcard);
5656 
5657  return 0;
5658 }
5659 
5663 STATIC int
5665  const char *filename, int truncate_log)
5666 {
5667  int open_flags = O_WRONLY|O_CREAT;
5668  open_flags |= truncate_log ? O_TRUNC : O_APPEND;
5669 
5670  int fd = tor_open_cloexec(filename, open_flags, 0640);
5671  if (fd < 0)
5672  return -1;
5673 
5674  return add_file_log(severity, filename, fd);
5675 }
5676 
5680 static int
5681 options_init_logs(const or_options_t *old_options, or_options_t *options,
5682  int validate_only)
5683 {
5684  config_line_t *opt;
5685  int ok;
5686  smartlist_t *elts;
5687  int run_as_daemon =
5688 #ifdef _WIN32
5689  0;
5690 #else
5691  options->RunAsDaemon;
5692 #endif
5693 
5694  if (options->LogTimeGranularity <= 0) {
5695  log_warn(LD_CONFIG, "Log time granularity '%d' has to be positive.",
5696  options->LogTimeGranularity);
5697  return -1;
5698  } else if (1000 % options->LogTimeGranularity != 0 &&
5699  options->LogTimeGranularity % 1000 != 0) {
5700  int granularity = options->LogTimeGranularity;
5701  if (granularity < 40) {
5702  do granularity++;
5703  while (1000 % granularity != 0);
5704  } else if (granularity < 1000) {
5705  granularity = 1000 / granularity;
5706  while (1000 % granularity != 0)
5707  granularity--;
5708  granularity = 1000 / granularity;
5709  } else {
5710  granularity = 1000 * ((granularity / 1000) + 1);
5711  }
5712  log_warn(LD_CONFIG, "Log time granularity '%d' has to be either a "
5713  "divisor or a multiple of 1 second. Changing to "
5714  "'%d'.",
5715  options->LogTimeGranularity, granularity);
5716  if (!validate_only)
5717  set_log_time_granularity(granularity);
5718  } else {
5719  if (!validate_only)
5721  }
5722 
5723  ok = 1;
5724  elts = smartlist_new();
5725 
5726  for (opt = options->Logs; opt; opt = opt->next) {
5727  log_severity_list_t *severity;
5728  const char *cfg = opt->value;
5729  severity = tor_malloc_zero(sizeof(log_severity_list_t));
5730  if (parse_log_severity_config(&cfg, severity) < 0) {
5731  log_warn(LD_CONFIG, "Couldn't parse log levels in Log option 'Log %s'",
5732  opt->value);
5733  ok = 0; goto cleanup;
5734  }
5735 
5736  smartlist_split_string(elts, cfg, NULL,
5737  SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
5738 
5739  if (smartlist_len(elts) == 0)
5740  smartlist_add_strdup(elts, "stdout");
5741 
5742  if (smartlist_len(elts) == 1 &&
5743  (!strcasecmp(smartlist_get(elts,0), "stdout") ||
5744  !strcasecmp(smartlist_get(elts,0), "stderr"))) {
5745  int err = smartlist_len(elts) &&
5746  !strcasecmp(smartlist_get(elts,0), "stderr");
5747  if (!validate_only) {
5748  if (run_as_daemon) {
5749  log_warn(LD_CONFIG,
5750  "Can't log to %s with RunAsDaemon set; skipping stdout",
5751  err?"stderr":"stdout");
5752  } else {
5753  add_stream_log(severity, err?"<stderr>":"<stdout>",
5754  fileno(err?stderr:stdout));
5755  }
5756  }
5757  goto cleanup;
5758  }
5759  if (smartlist_len(elts) == 1) {
5760  if (!strcasecmp(smartlist_get(elts,0), "syslog")) {
5761 #ifdef HAVE_SYSLOG_H
5762  if (!validate_only) {
5763  add_syslog_log(severity, options->SyslogIdentityTag);
5764  }
5765 #else
5766  log_warn(LD_CONFIG, "Syslog is not supported on this system. Sorry.");
5767 #endif /* defined(HAVE_SYSLOG_H) */
5768  goto cleanup;
5769  }
5770 
5771  if (!strcasecmp(smartlist_get(elts, 0), "android")) {
5772 #ifdef HAVE_ANDROID_LOG_H
5773  if (!validate_only) {
5774  add_android_log(severity, options->AndroidIdentityTag);
5775  }
5776 #else
5777  log_warn(LD_CONFIG, "Android logging is not supported"
5778  " on this system. Sorry.");
5779 #endif // HAVE_ANDROID_LOG_H.
5780  goto cleanup;
5781  }
5782  }
5783 
5784  if (smartlist_len(elts) == 2 &&
5785  !strcasecmp(smartlist_get(elts,0), "file")) {
5786  if (!validate_only) {
5787  char *fname = expand_filename(smartlist_get(elts, 1));
5788  /* Truncate if TruncateLogFile is set and we haven't seen this option
5789  line before. */
5790  int truncate_log = 0;
5791  if (options->TruncateLogFile) {
5792  truncate_log = 1;
5793  if (old_options) {
5794  config_line_t *opt2;
5795  for (opt2 = old_options->Logs; opt2; opt2 = opt2->next)
5796  if (!strcmp(opt->value, opt2->value)) {
5797  truncate_log = 0;
5798  break;
5799  }
5800  }
5801  }
5802  if (open_and_add_file_log(severity, fname, truncate_log) < 0) {
5803  log_warn(LD_CONFIG, "Couldn't open file for 'Log %s': %s",
5804  opt->value, strerror(errno));
5805  ok = 0;
5806  }
5807  tor_free(fname);
5808  }
5809  goto cleanup;
5810  }
5811 
5812  log_warn(LD_CONFIG, "Bad syntax on file Log option 'Log %s'",
5813  opt->value);
5814  ok = 0; goto cleanup;
5815 
5816  cleanup:
5817  SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
5818  smartlist_clear(elts);
5819  tor_free(severity);
5820  }
5821  smartlist_free(elts);
5822 
5823  if (ok && !validate_only)
5825 
5826  return ok?0:-1;
5827 }
5828 
5832 static int
5834 {
5835  char *socks_string = NULL;
5836  size_t socks_string_len;
5837 
5838  tor_assert(args);
5839  tor_assert(smartlist_len(args) > 0);
5840 
5841  SMARTLIST_FOREACH_BEGIN(args, const char *, s) {
5842  if (!string_is_key_value(LOG_WARN, s)) { /* items should be k=v items */
5843  log_warn(LD_CONFIG, "'%s' is not a k=v item.", s);
5844  return -1;
5845  }
5846  } SMARTLIST_FOREACH_END(s);
5847 
5848  socks_string = pt_stringify_socks_args(args);
5849  if (!socks_string)
5850  return -1;
5851 
5852  socks_string_len = strlen(socks_string);
5853  tor_free(socks_string);
5854 
5855  if (socks_string_len > MAX_SOCKS5_AUTH_SIZE_TOTAL) {
5856  log_warn(LD_CONFIG, "SOCKS arguments can't be more than %u bytes (%lu).",
5858  (unsigned long) socks_string_len);
5859  return -1;
5860  }
5861 
5862  return 0;
5863 }
5864 
5866 /* private */ void
5868 {
5869  if (!bridge_line)
5870  return;
5871 
5872  if (bridge_line->socks_args) {
5873  SMARTLIST_FOREACH(bridge_line->socks_args, char*, s, tor_free(s));
5874  smartlist_free(bridge_line->socks_args);
5875  }
5876  tor_free(bridge_line->transport_name);
5877  tor_free(bridge_line);
5878 }
5879 
5892 /* private */ bridge_line_t *
5893 parse_bridge_line(const char *line)
5894 {
5895  smartlist_t *items = NULL;
5896  char *addrport=NULL, *fingerprint=NULL;
5897  char *field=NULL;
5898  bridge_line_t *bridge_line = tor_malloc_zero(sizeof(bridge_line_t));
5899 
5900  items = smartlist_new();
5901  smartlist_split_string(items, line, NULL,
5902  SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5903  if (smartlist_len(items) < 1) {
5904  log_warn(LD_CONFIG, "Too few arguments to Bridge line.");
5905  goto err;
5906  }
5907 
5908  /* first field is either a transport name or addrport */
5909  field = smartlist_get(items, 0);
5910  smartlist_del_keeporder(items, 0);
5911 
5912  if (string_is_C_identifier(field)) {
5913  /* It's a transport name. */
5914  bridge_line->transport_name = field;
5915  if (smartlist_len(items) < 1) {
5916  log_warn(LD_CONFIG, "Too few items to Bridge line.");
5917  goto err;
5918  }
5919  addrport = smartlist_get(items, 0); /* Next field is addrport then. */
5920  smartlist_del_keeporder(items, 0);
5921  } else {
5922  addrport = field;
5923  }
5924 
5925  if (tor_addr_port_parse(LOG_INFO, addrport,
5926  &bridge_line->addr, &bridge_line->port, 443)<0) {
5927  log_warn(LD_CONFIG, "Error parsing Bridge address '%s'", addrport);
5928  goto err;
5929  }
5930 
5931  /* If transports are enabled, next field could be a fingerprint or a
5932  socks argument. If transports are disabled, next field must be
5933  a fingerprint. */
5934  if (smartlist_len(items)) {
5935  if (bridge_line->transport_name) { /* transports enabled: */
5936  field = smartlist_get(items, 0);
5937  smartlist_del_keeporder(items, 0);
5938 
5939  /* If it's a key=value pair, then it's a SOCKS argument for the
5940  transport proxy... */
5941  if (string_is_key_value(LOG_DEBUG, field)) {
5942  bridge_line->socks_args = smartlist_new();
5943  smartlist_add(bridge_line->socks_args, field);
5944  } else { /* ...otherwise, it's the bridge fingerprint. */
5945  fingerprint = field;
5946  }
5947 
5948  } else { /* transports disabled: */
5949  fingerprint = smartlist_join_strings(items, "", 0, NULL);
5950  }
5951  }
5952 
5953  /* Handle fingerprint, if it was provided. */
5954  if (fingerprint) {
5955  if (strlen(fingerprint) != HEX_DIGEST_LEN) {
5956  log_warn(LD_CONFIG, "Key digest for Bridge is wrong length.");
5957  goto err;
5958  }
5959  if (base16_decode(bridge_line->digest, DIGEST_LEN,
5960  fingerprint, HEX_DIGEST_LEN) != DIGEST_LEN) {
5961  log_warn(LD_CONFIG, "Unable to decode Bridge key digest.");
5962  goto err;
5963  }
5964  }
5965 
5966  /* If we are using transports, any remaining items in the smartlist
5967  should be k=v values. */
5968  if (bridge_line->transport_name && smartlist_len(items)) {
5969  if (!bridge_line->socks_args)
5970  bridge_line->socks_args = smartlist_new();
5971 
5972  /* append remaining items of 'items' to 'socks_args' */
5973  smartlist_add_all(bridge_line->socks_args, items);
5974  smartlist_clear(items);
5975 
5976  tor_assert(smartlist_len(bridge_line->socks_args) > 0);
5977  }
5978 
5979  if (bridge_line->socks_args) {
5980  if (validate_transport_socks_arguments(bridge_line->socks_args) < 0)
5981  goto err;
5982  }
5983 
5984  goto done;
5985 
5986  err:
5987  bridge_line_free(bridge_line);
5988  bridge_line = NULL;
5989 
5990  done:
5991  SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5992  smartlist_free(items);
5993  tor_free(addrport);
5994  tor_free(fingerprint);
5995 
5996  return bridge_line;
5997 }
5998 
6010 STATIC int
6012  const char *line, int validate_only,
6013  int server)
6014 {
6015 
6016  smartlist_t *items = NULL;
6017  int r;
6018  const char *transports = NULL;
6019  smartlist_t *transport_list = NULL;
6020  char *type = NULL;
6021  char *addrport = NULL;
6022  tor_addr_t addr;
6023  uint16_t port = 0;
6024  int socks_ver = PROXY_NONE;
6025 
6026  /* managed proxy options */
6027  int is_managed = 0;
6028  char **proxy_argv = NULL;
6029  char **tmp = NULL;
6030  int proxy_argc, i;
6031  int is_useless_proxy = 1;
6032 
6033  int line_length;
6034 
6035  /* Split the line into space-separated tokens */
6036  items = smartlist_new();
6037  smartlist_split_string(items, line, NULL,
6038  SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
6039  line_length = smartlist_len(items);
6040 
6041  if (line_length < 3) {
6042  log_warn(LD_CONFIG,
6043  "Too few arguments on %sTransportPlugin line.",
6044  server ? "Server" : "Client");
6045  goto err;
6046  }
6047 
6048  /* Get the first line element, split it to commas into
6049  transport_list (in case it's multiple transports) and validate
6050  the transport names. */
6051  transports = smartlist_get(items, 0);
6052  transport_list = smartlist_new();
6053  smartlist_split_string(transport_list, transports, ",",
6054  SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
6055  SMARTLIST_FOREACH_BEGIN(transport_list, const char *, transport_name) {
6056  /* validate transport names */
6057  if (!string_is_C_identifier(transport_name)) {
6058  log_warn(LD_CONFIG, "Transport name is not a C identifier (%s).",
6059  transport_name);
6060  goto err;
6061  }
6062 
6063  /* see if we actually need the transports provided by this proxy */
6064  if (!validate_only && transport_is_needed(transport_name))
6065  is_useless_proxy = 0;
6066  } SMARTLIST_FOREACH_END(transport_name);
6067 
6068  type = smartlist_get(items, 1);
6069  if (!strcmp(type, "exec")) {
6070  is_managed = 1;
6071  } else if (server && !strcmp(type, "proxy")) {
6072  /* 'proxy' syntax only with ServerTransportPlugin */
6073  is_managed = 0;
6074  } else if (!server && !strcmp(type, "socks4")) {
6075  /* 'socks4' syntax only with ClientTransportPlugin */
6076  is_managed = 0;
6077  socks_ver = PROXY_SOCKS4;
6078  } else if (!server && !strcmp(type, "socks5")) {
6079  /* 'socks5' syntax only with ClientTransportPlugin */
6080  is_managed = 0;
6081  socks_ver = PROXY_SOCKS5;
6082  } else {
6083  log_warn(LD_CONFIG,
6084  "Strange %sTransportPlugin type '%s'",
6085  server ? "Server" : "Client", type);
6086  goto err;
6087  }
6088 
6089  if (is_managed && options->Sandbox) {
6090  log_warn(LD_CONFIG,
6091  "Managed proxies are not compatible with Sandbox mode."
6092  "(%sTransportPlugin line was %s)",
6093  server ? "Server" : "Client", escaped(line));
6094  goto err;
6095  }
6096 
6097  if (is_managed && options->NoExec) {
6098  log_warn(LD_CONFIG,
6099  "Managed proxies are not compatible with NoExec mode; ignoring."
6100  "(%sTransportPlugin line was %s)",
6101  server ? "Server" : "Client", escaped(line));
6102  r = 0;
6103  goto done;
6104  }
6105 
6106  if (is_managed) {
6107  /* managed */
6108 
6109  if (!server && !validate_only && is_useless_proxy) {
6110  log_info(LD_GENERAL,
6111  "Pluggable transport proxy (%s) does not provide "
6112  "any needed transports and will not be launched.",
6113  line);
6114  }
6115 
6116  /*
6117  * If we are not just validating, use the rest of the line as the
6118  * argv of the proxy to be launched. Also, make sure that we are
6119  * only launching proxies that contribute useful transports.
6120  */
6121 
6122  if (!validate_only && (server || !is_useless_proxy)) {
6123  proxy_argc = line_length - 2;
6124  tor_assert(proxy_argc > 0);
6125  proxy_argv = tor_calloc((proxy_argc + 1), sizeof(char *));
6126  tmp = proxy_argv;
6127 
6128  for (i = 0; i < proxy_argc; i++) {
6129  /* store arguments */
6130  *tmp++ = smartlist_get(items, 2);
6131  smartlist_del_keeporder(items, 2);
6132  }
6133  *tmp = NULL; /* terminated with NULL, just like execve() likes it */
6134 
6135  /* kickstart the thing */
6136  if (server) {
6137  pt_kickstart_server_proxy(transport_list, proxy_argv);
6138  } else {
6139  pt_kickstart_client_proxy(transport_list, proxy_argv);
6140  }
6141  }
6142  } else {
6143  /* external */
6144 
6145  /* ClientTransportPlugins connecting through a proxy is managed only. */
6146  if (!server && (options->Socks4Proxy || options->Socks5Proxy ||
6147  options->HTTPSProxy)) {
6148  log_warn(LD_CONFIG, "You have configured an external proxy with another "
6149  "proxy type. (Socks4Proxy|Socks5Proxy|HTTPSProxy)");
6150  goto err;
6151  }
6152 
6153  if (smartlist_len(transport_list) != 1) {
6154  log_warn(LD_CONFIG,
6155  "You can't have an external proxy with more than "
6156  "one transport.");
6157  goto err;
6158  }
6159 
6160  addrport = smartlist_get(items, 2);
6161 
6162  if (tor_addr_port_lookup(addrport, &addr, &port) < 0) {
6163  log_warn(LD_CONFIG,
6164  "Error parsing transport address '%s'", addrport);
6165  goto err;
6166  }
6167 
6168  if (!port) {
6169  log_warn(LD_CONFIG,
6170  "Transport address '%s' has no port.", addrport);
6171  goto err;
6172  }
6173 
6174  if (!validate_only) {
6175  log_info(LD_DIR, "%s '%s' at %s.",
6176  server ? "Server transport" : "Transport",
6177  transports, fmt_addrport(&addr, port));
6178 
6179  if (!server) {
6180  transport_add_from_config(&addr, port,
6181  smartlist_get(transport_list, 0),
6182  socks_ver);
6183  }
6184  }
6185  }
6186 
6187  r = 0;
6188  goto done;
6189 
6190  err:
6191  r = -1;
6192 
6193  done:
6194  SMARTLIST_FOREACH(items, char*, s, tor_free(s));
6195  smartlist_free(items);
6196  if (transport_list) {
6197  SMARTLIST_FOREACH(transport_list, char*, s, tor_free(s));
6198  smartlist_free(transport_list);
6199  }
6200 
6201  return r;
6202 }
6203 
6213 static char *
6214 get_bindaddr_from_transport_listen_line(const char *line,const char *transport)
6215 {
6216  smartlist_t *items = NULL;
6217  const char *parsed_transport = NULL;
6218  char *addrport = NULL;
6219  tor_addr_t addr;
6220  uint16_t port = 0;
6221 
6222  items = smartlist_new();
6223  smartlist_split_string(items, line, NULL,
6224  SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
6225 
6226  if (smartlist_len(items) < 2) {
6227  log_warn(LD_CONFIG,"Too few arguments on ServerTransportListenAddr line.");
6228  goto err;
6229  }
6230 
6231  parsed_transport = smartlist_get(items, 0);
6232  addrport = tor_strdup(smartlist_get(items, 1));
6233 
6234  /* If 'transport' is given, check if it matches the one on the line */
6235  if (transport && strcmp(transport, parsed_transport))
6236  goto err;
6237 
6238  /* Validate addrport */
6239  if (tor_addr_port_parse(LOG_WARN, addrport, &addr, &port, -1)<0) {
6240  log_warn(LD_CONFIG, "Error parsing ServerTransportListenAddr "
6241  "address '%s'", addrport);
6242  goto err;
6243  }
6244 
6245  goto done;
6246 
6247  err:
6248  tor_free(addrport);
6249  addrport = NULL;
6250 
6251  done:
6252  SMARTLIST_FOREACH(items, char*, s, tor_free(s));
6253  smartlist_free(items);
6254 
6255  return addrport;
6256 }
6257 
6266 smartlist_t *
6267 get_options_from_transport_options_line(const char *line,const char *transport)
6268 {
6269  smartlist_t *items = smartlist_new();
6270  smartlist_t *options = smartlist_new();
6271  const char *parsed_transport = NULL;
6272 
6273  smartlist_split_string(items, line, NULL,
6274  SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
6275 
6276  if (smartlist_len(items) < 2) {
6277  log_warn(LD_CONFIG,"Too few arguments on ServerTransportOptions line.");
6278  goto err;
6279  }
6280 
6281  parsed_transport = smartlist_get(items, 0);
6282  /* If 'transport' is given, check if it matches the one on the line */
6283  if (transport && strcmp(transport, parsed_transport))
6284  goto err;
6285 
6286  SMARTLIST_FOREACH_BEGIN(items, const char *, option) {
6287  if (option_sl_idx == 0) /* skip the transport field (first field)*/
6288  continue;
6289 
6290  /* validate that it's a k=v value */
6291  if (!string_is_key_value(LOG_WARN, option)) {
6292  log_warn(LD_CONFIG, "%s is not a k=v value.", escaped(option));
6293  goto err;
6294  }
6295 
6296  /* add it to the options smartlist */
6297  smartlist_add_strdup(options, option);
6298  log_debug(LD_CONFIG, "Added %s to the list of options", escaped(option));
6299  } SMARTLIST_FOREACH_END(option);
6300 
6301  goto done;
6302 
6303  err:
6304  SMARTLIST_FOREACH(options, char*, s, tor_free(s));
6305  smartlist_free(options);
6306  options = NULL;
6307 
6308  done:
6309  SMARTLIST_FOREACH(items, char*, s, tor_free(s));
6310  smartlist_free(items);
6311 
6312  return options;
6313 }
6314 
6319 char *
6321 {
6322  config_line_t *cl;
6323  const or_options_t *options = get_options();
6324 
6325  for (cl = options->ServerTransportListenAddr; cl; cl = cl->next) {
6326  char *bindaddr =
6327  get_bindaddr_from_transport_listen_line(cl->value, transport);
6328  if (bindaddr)
6329  return bindaddr;
6330  }
6331 
6332  return NULL;
6333 }
6334 
6339 smartlist_t *
6340 get_options_for_server_transport(const char *transport)
6341 {
6342  config_line_t *cl;
6343  const or_options_t *options = get_options();
6344 
6345  for (cl = options->ServerTransportOptions; cl; cl = cl->next) {
6346  smartlist_t *options_sl =
6347  get_options_from_transport_options_line(cl->value, transport);
6348  if (options_sl)
6349  return options_sl;
6350  }
6351 
6352  return NULL;
6353 }
6354 
6362 STATIC int
6363 parse_dir_authority_line(const char *line, dirinfo_type_t required_type,
6364  int validate_only)
6365 {
6366  smartlist_t *items = NULL;
6367  int r;
6368  char *addrport=NULL, *address=NULL, *nickname=NULL, *fingerprint=NULL;
6369  tor_addr_port_t ipv6_addrport, *ipv6_addrport_ptr = NULL;
6370  uint16_t dir_port = 0, or_port = 0;
6371  char digest[DIGEST_LEN];
6372  char v3_digest[DIGEST_LEN];
6373  dirinfo_type_t type = 0;
6374  double weight = 1.0;
6375 
6376  memset(v3_digest, 0, sizeof(v3_digest));
6377 
6378  items = smartlist_new();
6379  smartlist_split_string(items, line, NULL,
6380  SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
6381  if (smartlist_len(items) < 1) {
6382  log_warn(LD_CONFIG, "No arguments on DirAuthority line.");
6383  goto err;
6384  }
6385 
6386  if (is_legal_nickname(smartlist_get(items, 0))) {
6387  nickname = smartlist_get(items, 0);
6388  smartlist_del_keeporder(items, 0);
6389  }
6390 
6391  while (smartlist_len(items)) {
6392  char *flag = smartlist_get(items, 0);
6393  if (TOR_ISDIGIT(flag[0]))
6394  break;
6395  if (!strcasecmp(flag, "hs") ||
6396  !strcasecmp(flag, "no-hs")) {
6397  log_warn(LD_CONFIG, "The DirAuthority options 'hs' and 'no-hs' are "
6398  "obsolete; you don't need them any more.");
6399  } else if (!strcasecmp(flag, "bridge")) {
6400  type |= BRIDGE_DIRINFO;
6401  } else if (!strcasecmp(flag, "no-v2")) {
6402  /* obsolete, but may still be contained in DirAuthority lines generated