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