tor  0.4.1.0-alpha-dev
config.c
Go to the documentation of this file.
1 /* Copyright (c) 2001 Matej Pfajfar.
2  * Copyright (c) 2001-2004, Roger Dingledine.
3  * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4  * Copyright (c) 2007-2019, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
6 
61 #define CONFIG_PRIVATE
62 #include "core/or/or.h"
63 #include "app/config/config.h"
64 #include "app/config/confparse.h"
65 #include "app/config/statefile.h"
66 #include "app/main/main.h"
67 #include "app/main/subsysmgr.h"
70 #include "core/mainloop/mainloop.h"
71 #include "core/mainloop/netstatus.h"
72 #include "core/or/channel.h"
73 #include "core/or/circuitbuild.h"
74 #include "core/or/circuitlist.h"
75 #include "core/or/circuitmux.h"
77 #include "core/or/circuitstats.h"
79 #include "core/or/connection_or.h"
80 #include "core/or/dos.h"
81 #include "core/or/policies.h"
82 #include "core/or/relay.h"
83 #include "core/or/scheduler.h"
84 #include "feature/client/addressmap.h"
85 #include "feature/client/bridges.h"
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_opts(const or_options_t *options, const char *address)
1060 {
1061  tor_assert(address);
1062  if (!options) {
1063  options = get_options();
1064  }
1065 
1066  if (options->SafeLogging_ == SAFELOG_SCRUB_ALL)
1067  return "[scrubbed]";
1068  else
1069  return address;
1070 }
1071 
1079 const char *
1080 safe_str_opts(const or_options_t *options, const char *address)
1081 {
1082  tor_assert(address);
1083  if (!options) {
1084  options = get_options();
1085  }
1086 
1087  if (options->SafeLogging_ != SAFELOG_SCRUB_NONE)
1088  return "[scrubbed]";
1089  else
1090  return address;
1091 }
1092 
1096 const char *
1097 escaped_safe_str_client(const char *address)
1098 {
1099  if (get_options()->SafeLogging_ == SAFELOG_SCRUB_ALL)
1100  return "[scrubbed]";
1101  else
1102  return escaped(address);
1103 }
1104 
1108 const char *
1109 escaped_safe_str(const char *address)
1110 {
1111  if (get_options()->SafeLogging_ != SAFELOG_SCRUB_NONE)
1112  return "[scrubbed]";
1113  else
1114  return escaped(address);
1115 }
1116 
1126 
1129 int
1131 {
1133 }
1134 
1136 static void
1138 {
1140  warning_severity);
1141 }
1142 
1147 void
1149 {
1152 }
1153 
1157 static void
1159 {
1161 }
1162 
1165 static const char *default_authorities[] = {
1166 #include "auth_dirs.inc"
1167  NULL
1168 };
1169 
1173 static const char *default_fallbacks[] = {
1174 #include "fallback_dirs.inc"
1175  NULL
1176 };
1177 
1182 STATIC void
1184 {
1185  int i;
1186  for (i=0; default_authorities[i]; i++) {
1187  if (parse_dir_authority_line(default_authorities[i], type, 0)<0) {
1188  log_err(LD_BUG, "Couldn't parse internal DirAuthority line %s",
1189  default_authorities[i]);
1190  }
1191  }
1192 }
1193 
1197 add_default_fallback_dir_servers,(void))
1198 {
1199  int i;
1200  for (i=0; default_fallbacks[i]; i++) {
1202  log_err(LD_BUG, "Couldn't parse internal FallbackDir line %s",
1203  default_fallbacks[i]);
1204  }
1205  }
1206 }
1207 
1212 static int
1214 {
1215  config_line_t *cl;
1216 
1217  if (options->DirAuthorities &&
1218  (options->AlternateDirAuthority || options->AlternateBridgeAuthority)) {
1219  log_warn(LD_CONFIG,
1220  "You cannot set both DirAuthority and Alternate*Authority.");
1221  return -1;
1222  }
1223 
1224  /* do we want to complain to the user about being partitionable? */
1225  if ((options->DirAuthorities &&
1226  (!old_options ||
1227  !config_lines_eq(options->DirAuthorities,
1228  old_options->DirAuthorities))) ||
1229  (options->AlternateDirAuthority &&
1230  (!old_options ||
1232  old_options->AlternateDirAuthority)))) {
1233  log_warn(LD_CONFIG,
1234  "You have used DirAuthority or AlternateDirAuthority to "
1235  "specify alternate directory authorities in "
1236  "your configuration. This is potentially dangerous: it can "
1237  "make you look different from all other Tor users, and hurt "
1238  "your anonymity. Even if you've specified the same "
1239  "authorities as Tor uses by default, the defaults could "
1240  "change in the future. Be sure you know what you're doing.");
1241  }
1242 
1243  /* Now go through the four ways you can configure an alternate
1244  * set of directory authorities, and make sure none are broken. */
1245  for (cl = options->DirAuthorities; cl; cl = cl->next)
1246  if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
1247  return -1;
1248  for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
1249  if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
1250  return -1;
1251  for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
1252  if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
1253  return -1;
1254  for (cl = options->FallbackDir; cl; cl = cl->next)
1255  if (parse_dir_fallback_line(cl->value, 1)<0)
1256  return -1;
1257  return 0;
1258 }
1259 
1263 int
1265  const or_options_t *old_options)
1266 {
1267  config_line_t *cl;
1268  int need_to_update =
1269  !smartlist_len(router_get_trusted_dir_servers()) ||
1270  !smartlist_len(router_get_fallback_dir_servers()) || !old_options ||
1271  !config_lines_eq(options->DirAuthorities, old_options->DirAuthorities) ||
1272  !config_lines_eq(options->FallbackDir, old_options->FallbackDir) ||
1273  (options->UseDefaultFallbackDirs != old_options->UseDefaultFallbackDirs) ||
1275  old_options->AlternateBridgeAuthority) ||
1277  old_options->AlternateDirAuthority);
1278 
1279  if (!need_to_update)
1280  return 0; /* all done */
1281 
1282  /* "You cannot set both DirAuthority and Alternate*Authority."
1283  * Checking that this restriction holds allows us to simplify
1284  * the unit tests. */
1285  tor_assert(!(options->DirAuthorities &&
1286  (options->AlternateDirAuthority
1287  || options->AlternateBridgeAuthority)));
1288 
1289  /* Start from a clean slate. */
1291 
1292  if (!options->DirAuthorities) {
1293  /* then we may want some of the defaults */
1294  dirinfo_type_t type = NO_DIRINFO;
1295  if (!options->AlternateBridgeAuthority) {
1296  type |= BRIDGE_DIRINFO;
1297  }
1298  if (!options->AlternateDirAuthority) {
1300  /* Only add the default fallback directories when the DirAuthorities,
1301  * AlternateDirAuthority, and FallbackDir directory config options
1302  * are set to their defaults, and when UseDefaultFallbackDirs is 1. */
1303  if (!options->FallbackDir && options->UseDefaultFallbackDirs) {
1304  add_default_fallback_dir_servers();
1305  }
1306  }
1307  /* if type == NO_DIRINFO, we don't want to add any of the
1308  * default authorities, because we've replaced them all */
1309  if (type != NO_DIRINFO)
1311  }
1312 
1313  for (cl = options->DirAuthorities; cl; cl = cl->next)
1314  if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
1315  return -1;
1316  for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
1317  if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
1318  return -1;
1319  for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
1320  if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
1321  return -1;
1322  for (cl = options->FallbackDir; cl; cl = cl->next)
1323  if (parse_dir_fallback_line(cl->value, 0)<0)
1324  return -1;
1325  return 0;
1326 }
1327 
1334 static int
1336  const char *directory,
1337  int group_readable,
1338  const char *owner,
1339  char **msg_out)
1340 {
1341  cpd_check_t cpd_opts = create ? CPD_CREATE : CPD_CHECK;
1342  if (group_readable)
1343  cpd_opts |= CPD_GROUP_READ;
1344  if (check_private_dir(directory,
1345  cpd_opts,
1346  owner) < 0) {
1347  tor_asprintf(msg_out,
1348  "Couldn't %s private data directory \"%s\"",
1349  create ? "create" : "access",
1350  directory);
1351  return -1;
1352  }
1353 
1354 #ifndef _WIN32
1355  if (group_readable) {
1356  /* Only new dirs created get new opts, also enforce group read. */
1357  if (chmod(directory, 0750)) {
1358  log_warn(LD_FS,"Unable to make %s group-readable: %s",
1359  directory, strerror(errno));
1360  }
1361  }
1362 #endif /* !defined(_WIN32) */
1363 
1364  return 0;
1365 }
1366 
1371 int
1373 {
1374  /* Make sure DataDirectory exists, and is private. */
1375  cpd_check_t cpd_opts = CPD_CREATE;
1376  if (options->DataDirectoryGroupReadable)
1377  cpd_opts |= CPD_GROUP_READ;
1378  if (check_private_dir(options->DataDirectory, cpd_opts, options->User)) {
1379  log_err(LD_OR, "Can't create/check datadirectory %s",
1380  options->DataDirectory);
1381  return -1;
1382  }
1383 
1384  /* Check the key directory. */
1385  if (check_private_dir(options->KeyDirectory, CPD_CREATE, options->User)) {
1386  return -1;
1387  }
1388  return 0;
1389 }
1390 
1391 /* Helps determine flags to pass to switch_id. */
1392 static int have_low_ports = -1;
1393 
1400 static int
1401 options_act_reversible(const or_options_t *old_options, char **msg)
1402 {
1403  smartlist_t *new_listeners = smartlist_new();
1404  or_options_t *options = get_options_mutable();
1405  int running_tor = options->command == CMD_RUN_TOR;
1406  int set_conn_limit = 0;
1407  int r = -1;
1408  int logs_marked = 0, logs_initialized = 0;
1409  int old_min_log_level = get_min_log_level();
1410 
1411  /* Daemonize _first_, since we only want to open most of this stuff in
1412  * the subprocess. Libevent bases can't be reliably inherited across
1413  * processes. */
1414  if (running_tor && options->RunAsDaemon) {
1416  subsystems_prefork();
1417  /* No need to roll back, since you can't change the value. */
1418  if (start_daemon())
1419  subsystems_postfork();
1420  }
1421 
1422 #ifdef HAVE_SYSTEMD
1423  /* Our PID may have changed, inform supervisor */
1424  sd_notifyf(0, "MAINPID=%ld\n", (long int)getpid());
1425 #endif
1426 
1427 #ifndef HAVE_SYS_UN_H
1428  if (options->ControlSocket || options->ControlSocketsGroupWritable) {
1429  *msg = tor_strdup("Unix domain sockets (ControlSocket) not supported "
1430  "on this OS/with this build.");
1431  goto rollback;
1432  }
1433 #else /* !(!defined(HAVE_SYS_UN_H)) */
1434  if (options->ControlSocketsGroupWritable && !options->ControlSocket) {
1435  *msg = tor_strdup("Setting ControlSocketGroupWritable without setting"
1436  "a ControlSocket makes no sense.");
1437  goto rollback;
1438  }
1439 #endif /* !defined(HAVE_SYS_UN_H) */
1440 
1441  if (running_tor) {
1442  int n_ports=0;
1443  /* We need to set the connection limit before we can open the listeners. */
1444  if (! sandbox_is_active()) {
1445  if (set_max_file_descriptors((unsigned)options->ConnLimit,
1446  &options->ConnLimit_) < 0) {
1447  *msg = tor_strdup("Problem with ConnLimit value. "
1448  "See logs for details.");
1449  goto rollback;
1450  }
1451  set_conn_limit = 1;
1452  } else {
1453  tor_assert(old_options);
1454  options->ConnLimit_ = old_options->ConnLimit_;
1455  }
1456 
1457  /* Set up libevent. (We need to do this before we can register the
1458  * listeners as listeners.) */
1459  if (running_tor && !libevent_initialized) {
1460  init_libevent(options);
1461  libevent_initialized = 1;
1462 
1463  /* This has to come up after libevent is initialized. */
1464  control_initialize_event_queue();
1465 
1466  /*
1467  * Initialize the scheduler - this has to come after
1468  * options_init_from_torrc() sets up libevent - why yes, that seems
1469  * completely sensible to hide the libevent setup in the option parsing
1470  * code! It also needs to happen before init_keys(), so it needs to
1471  * happen here too. How yucky. */
1472  scheduler_init();
1473  }
1474 
1475  /* Adjust the port configuration so we can launch listeners. */
1476  if (parse_ports(options, 0, msg, &n_ports, NULL)) {
1477  if (!*msg)
1478  *msg = tor_strdup("Unexpected problem parsing port config");
1479  goto rollback;
1480  }
1481 
1482  /* Set the hibernation state appropriately.*/
1483  consider_hibernation(time(NULL));
1484 
1485  /* Launch the listeners. (We do this before we setuid, so we can bind to
1486  * ports under 1024.) We don't want to rebind if we're hibernating or
1487  * shutting down. If networking is disabled, this will close all but the
1488  * control listeners, but disable those. */
1489  if (!we_are_hibernating()) {
1490  if (retry_all_listeners(new_listeners, options->DisableNetwork) < 0) {
1491  *msg = tor_strdup("Failed to bind one of the listener ports.");
1492  goto rollback;
1493  }
1494  }
1495  if (options->DisableNetwork) {
1496  /* Aggressively close non-controller stuff, NOW */
1497  log_notice(LD_NET, "DisableNetwork is set. Tor will not make or accept "
1498  "non-control network connections. Shutting down all existing "
1499  "connections.");
1501  /* We can't complete circuits until the network is re-enabled. */
1503  }
1504  }
1505 
1506 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
1507  /* Open /dev/pf before dropping privileges. */
1508  if (options->TransPort_set &&
1509  options->TransProxyType_parsed == TPT_DEFAULT) {
1510  if (get_pf_socket() < 0) {
1511  *msg = tor_strdup("Unable to open /dev/pf for transparent proxy.");
1512  goto rollback;
1513  }
1514  }
1515 #endif /* defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H) */
1516 
1517  /* Attempt to lock all current and future memory with mlockall() only once */
1518  if (options->DisableAllSwap) {
1519  if (tor_mlockall() == -1) {
1520  *msg = tor_strdup("DisableAllSwap failure. Do you have proper "
1521  "permissions?");
1522  goto done;
1523  }
1524  }
1525 
1526  /* Setuid/setgid as appropriate */
1527  if (options->User) {
1528  tor_assert(have_low_ports != -1);
1529  unsigned switch_id_flags = 0;
1530  if (options->KeepBindCapabilities == 1) {
1531  switch_id_flags |= SWITCH_ID_KEEP_BINDLOW;
1532  switch_id_flags |= SWITCH_ID_WARN_IF_NO_CAPS;
1533  }
1534  if (options->KeepBindCapabilities == -1 && have_low_ports) {
1535  switch_id_flags |= SWITCH_ID_KEEP_BINDLOW;
1536  }
1537  if (switch_id(options->User, switch_id_flags) != 0) {
1538  /* No need to roll back, since you can't change the value. */
1539  *msg = tor_strdup("Problem with User value. See logs for details.");
1540  goto done;
1541  }
1542  }
1543 
1544  /* Ensure data directory is private; create if possible. */
1545  /* It's okay to do this in "options_act_reversible()" even though it isn't
1546  * actually reversible, since you can't change the DataDirectory while
1547  * Tor is running. */
1548  if (check_and_create_data_directory(running_tor /* create */,
1549  options->DataDirectory,
1550  options->DataDirectoryGroupReadable,
1551  options->User,
1552  msg) < 0) {
1553  goto done;
1554  }
1555  if (check_and_create_data_directory(running_tor /* create */,
1556  options->KeyDirectory,
1557  options->KeyDirectoryGroupReadable,
1558  options->User,
1559  msg) < 0) {
1560  goto done;
1561  }
1562 
1563  /* We need to handle the group-readable flag for the cache directory
1564  * specially, since the directory defaults to being the same as the
1565  * DataDirectory. */
1566  int cache_dir_group_readable;
1567  if (options->CacheDirectoryGroupReadable != -1) {
1568  /* If the user specified a value, use their setting */
1569  cache_dir_group_readable = options->CacheDirectoryGroupReadable;
1570  } else if (!strcmp(options->CacheDirectory, options->DataDirectory)) {
1571  /* If the user left the value as "auto", and the cache is the same as the
1572  * datadirectory, use the datadirectory setting.
1573  */
1574  cache_dir_group_readable = options->DataDirectoryGroupReadable;
1575  } else {
1576  /* Otherwise, "auto" means "not group readable". */
1577  cache_dir_group_readable = 0;
1578  }
1579  if (check_and_create_data_directory(running_tor /* create */,
1580  options->CacheDirectory,
1581  cache_dir_group_readable,
1582  options->User,
1583  msg) < 0) {
1584  goto done;
1585  }
1586 
1587  /* Bail out at this point if we're not going to be a client or server:
1588  * we don't run Tor itself. */
1589  if (!running_tor)
1590  goto commit;
1591 
1592  mark_logs_temp(); /* Close current logs once new logs are open. */
1593  logs_marked = 1;
1594  /* Configure the tor_log(s) */
1595  if (options_init_logs(old_options, options, 0)<0) {
1596  *msg = tor_strdup("Failed to init Log options. See logs for details.");
1597  goto rollback;
1598  }
1599  logs_initialized = 1;
1600 
1601  commit:
1602  r = 0;
1603  if (logs_marked) {
1604  log_severity_list_t *severity =
1605  tor_malloc_zero(sizeof(log_severity_list_t));
1606  close_temp_logs();
1610  tor_free(severity);
1612  }
1613  if (logs_initialized) {
1615  }
1616 
1617  {
1618  const char *badness = NULL;
1619  int bad_safelog = 0, bad_severity = 0, new_badness = 0;
1620  if (options->SafeLogging_ != SAFELOG_SCRUB_ALL) {
1621  bad_safelog = 1;
1622  if (!old_options || old_options->SafeLogging_ != options->SafeLogging_)
1623  new_badness = 1;
1624  }
1625  if (get_min_log_level() >= LOG_INFO) {
1626  bad_severity = 1;
1627  if (get_min_log_level() != old_min_log_level)
1628  new_badness = 1;
1629  }
1630  if (bad_safelog && bad_severity)
1631  badness = "you disabled SafeLogging, and "
1632  "you're logging more than \"notice\"";
1633  else if (bad_safelog)
1634  badness = "you disabled SafeLogging";
1635  else
1636  badness = "you're logging more than \"notice\"";
1637  if (new_badness)
1638  log_warn(LD_GENERAL, "Your log may contain sensitive information - %s. "
1639  "Don't log unless it serves an important reason. "
1640  "Overwrite the log afterwards.", badness);
1641  }
1642 
1643  if (set_conn_limit) {
1644  /*
1645  * If we adjusted the conn limit, recompute the OOS threshold too
1646  *
1647  * How many possible sockets to keep in reserve? If we have lots of
1648  * possible sockets, keep this below a limit and set ConnLimit_high_thresh
1649  * very close to ConnLimit_, but if ConnLimit_ is low, shrink it in
1650  * proportion.
1651  *
1652  * Somewhat arbitrarily, set socks_in_reserve to 5% of ConnLimit_, but
1653  * cap it at 64.
1654  */
1655  int socks_in_reserve = options->ConnLimit_ / 20;
1656  if (socks_in_reserve > 64) socks_in_reserve = 64;
1657 
1658  options->ConnLimit_high_thresh = options->ConnLimit_ - socks_in_reserve;
1659  options->ConnLimit_low_thresh = (options->ConnLimit_ / 4) * 3;
1660  log_info(LD_GENERAL,
1661  "Recomputed OOS thresholds: ConnLimit %d, ConnLimit_ %d, "
1662  "ConnLimit_high_thresh %d, ConnLimit_low_thresh %d",
1663  options->ConnLimit, options->ConnLimit_,
1664  options->ConnLimit_high_thresh,
1665  options->ConnLimit_low_thresh);
1666 
1667  /* Give the OOS handler a chance with the new thresholds */
1669  }
1670 
1671  goto done;
1672 
1673  rollback:
1674  r = -1;
1675  tor_assert(*msg);
1676 
1677  if (logs_marked) {
1680  }
1681 
1682  if (set_conn_limit && old_options)
1683  set_max_file_descriptors((unsigned)old_options->ConnLimit,
1684  &options->ConnLimit_);
1685 
1686  SMARTLIST_FOREACH(new_listeners, connection_t *, conn,
1687  {
1688  log_notice(LD_NET, "Closing partially-constructed %s on %s:%d",
1689  conn_type_to_string(conn->type), conn->address, conn->port);
1691  connection_mark_for_close(conn);
1692  });
1693 
1694  done:
1695  smartlist_free(new_listeners);
1696  return r;
1697 }
1698 
1701 int
1702 options_need_geoip_info(const or_options_t *options, const char **reason_out)
1703 {
1704  int bridge_usage = should_record_bridge_info(options);
1705  int routerset_usage =
1706  routerset_needs_geoip(options->EntryNodes) ||
1707  routerset_needs_geoip(options->ExitNodes) ||
1708  routerset_needs_geoip(options->MiddleNodes) ||
1710  routerset_needs_geoip(options->ExcludeNodes) ||
1713 
1714  if (routerset_usage && reason_out) {
1715  *reason_out = "We've been configured to use (or avoid) nodes in certain "
1716  "countries, and we need GEOIP information to figure out which ones they "
1717  "are.";
1718  } else if (bridge_usage && reason_out) {
1719  *reason_out = "We've been configured to see which countries can access "
1720  "us as a bridge, and we need GEOIP information to tell which countries "
1721  "clients are in.";
1722  }
1723  return bridge_usage || routerset_usage;
1724 }
1725 
1728 uint32_t
1730 {
1731  uint64_t bw = options->BandwidthRate;
1732  if (bw > options->MaxAdvertisedBandwidth)
1733  bw = options->MaxAdvertisedBandwidth;
1734  if (options->RelayBandwidthRate > 0 && bw > options->RelayBandwidthRate)
1735  bw = options->RelayBandwidthRate;
1736  /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1737  return (uint32_t)bw;
1738 }
1739 
1742 uint32_t
1744 {
1745  uint64_t bw = options->BandwidthBurst;
1746  if (options->RelayBandwidthBurst > 0 && bw > options->RelayBandwidthBurst)
1747  bw = options->RelayBandwidthBurst;
1748  /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
1749  return (uint32_t)bw;
1750 }
1751 
1752 /* Used in the various options_transition_affects* functions. */
1753 #define YES_IF_CHANGED_BOOL(opt) \
1754  if (!CFG_EQ_BOOL(old_options, new_options, opt)) return 1;
1755 #define YES_IF_CHANGED_INT(opt) \
1756  if (!CFG_EQ_INT(old_options, new_options, opt)) return 1;
1757 #define YES_IF_CHANGED_STRING(opt) \
1758  if (!CFG_EQ_STRING(old_options, new_options, opt)) return 1;
1759 #define YES_IF_CHANGED_LINELIST(opt) \
1760  if (!CFG_EQ_LINELIST(old_options, new_options, opt)) return 1;
1761 #define YES_IF_CHANGED_SMARTLIST(opt) \
1762  if (!CFG_EQ_SMARTLIST(old_options, new_options, opt)) return 1;
1763 #define YES_IF_CHANGED_ROUTERSET(opt) \
1764  if (!CFG_EQ_ROUTERSET(old_options, new_options, opt)) return 1;
1765 
1770 static int
1772  const or_options_t *new_options)
1773 {
1774  /* NOTE: Make sure this function stays in sync with
1775  * node_passes_guard_filter */
1776  tor_assert(old_options);
1777  tor_assert(new_options);
1778 
1779  YES_IF_CHANGED_BOOL(UseEntryGuards);
1780  YES_IF_CHANGED_BOOL(UseBridges);
1781  YES_IF_CHANGED_BOOL(ClientUseIPv4);
1782  YES_IF_CHANGED_BOOL(ClientUseIPv6);
1783  YES_IF_CHANGED_BOOL(FascistFirewall);
1784  YES_IF_CHANGED_ROUTERSET(ExcludeNodes);
1785  YES_IF_CHANGED_ROUTERSET(EntryNodes);
1786  YES_IF_CHANGED_SMARTLIST(FirewallPorts);
1787  YES_IF_CHANGED_LINELIST(Bridges);
1788  YES_IF_CHANGED_LINELIST(ReachableORAddresses);
1789  YES_IF_CHANGED_LINELIST(ReachableDirAddresses);
1790 
1791  return 0;
1792 }
1793 
1798 static int
1800  const or_options_t *new_options)
1801 {
1802  tor_assert(old_options);
1803  tor_assert(new_options);
1804 
1805  if (authdir_mode_v3(old_options) != authdir_mode_v3(new_options))
1806  return 1;
1807  if (! authdir_mode_v3(new_options))
1808  return 0;
1809  YES_IF_CHANGED_INT(V3AuthVotingInterval);
1810  YES_IF_CHANGED_INT(V3AuthVoteDelay);
1811  YES_IF_CHANGED_INT(V3AuthDistDelay);
1812  YES_IF_CHANGED_INT(TestingV3AuthInitialVotingInterval);
1813  YES_IF_CHANGED_INT(TestingV3AuthInitialVoteDelay);
1814  YES_IF_CHANGED_INT(TestingV3AuthInitialDistDelay);
1815  YES_IF_CHANGED_INT(TestingV3AuthVotingStartOffset);
1816 
1817  return 0;
1818 }
1819 
1829 STATIC int
1830 options_act(const or_options_t *old_options)
1831 {
1832  config_line_t *cl;
1833  or_options_t *options = get_options_mutable();
1834  int running_tor = options->command == CMD_RUN_TOR;
1835  char *msg=NULL;
1836  const int transition_affects_workers =
1837  old_options && options_transition_affects_workers(old_options, options);
1838  const int transition_affects_guards =
1839  old_options && options_transition_affects_guards(old_options, options);
1840 
1841  if (options->NoExec || options->Sandbox) {
1843  }
1844 
1845  /* disable ptrace and later, other basic debugging techniques */
1846  {
1847  /* Remember if we already disabled debugger attachment */
1848  static int disabled_debugger_attach = 0;
1849  /* Remember if we already warned about being configured not to disable
1850  * debugger attachment */
1851  static int warned_debugger_attach = 0;
1852  /* Don't disable debugger attachment when we're running the unit tests. */
1853  if (options->DisableDebuggerAttachment && !disabled_debugger_attach &&
1854  running_tor) {
1855  int ok = tor_disable_debugger_attach();
1856  /* LCOV_EXCL_START the warned_debugger_attach is 0 can't reach inside. */
1857  if (warned_debugger_attach && ok == 1) {
1858  log_notice(LD_CONFIG, "Disabled attaching debuggers for unprivileged "
1859  "users.");
1860  }
1861  /* LCOV_EXCL_STOP */
1862  disabled_debugger_attach = (ok == 1);
1863  } else if (!options->DisableDebuggerAttachment &&
1864  !warned_debugger_attach) {
1865  log_notice(LD_CONFIG, "Not disabling debugger attaching for "
1866  "unprivileged users.");
1867  warned_debugger_attach = 1;
1868  }
1869  }
1870 
1871  /* Write control ports to disk as appropriate */
1873 
1874  if (running_tor && !have_lockfile()) {
1875  if (try_locking(options, 1) < 0)
1876  return -1;
1877  }
1878 
1879  {
1880  int warning_severity = options->ProtocolWarnings ? LOG_WARN : LOG_INFO;
1881  set_protocol_warning_severity_level(warning_severity);
1882  }
1883 
1884  if (consider_adding_dir_servers(options, old_options) < 0) {
1885  // XXXX This should get validated earlier, and committed here, to
1886  // XXXX lower opportunities for reaching an error case.
1887  return -1;
1888  }
1889 
1890  if (rend_non_anonymous_mode_enabled(options)) {
1891  log_warn(LD_GENERAL, "This copy of Tor was compiled or configured to run "
1892  "in a non-anonymous mode. It will provide NO ANONYMITY.");
1893  }
1894 
1895  /* If we are a bridge with a pluggable transport proxy but no
1896  Extended ORPort, inform the user that they are missing out. */
1897  if (server_mode(options) && options->ServerTransportPlugin &&
1898  !options->ExtORPort_lines) {
1899  log_notice(LD_CONFIG, "We use pluggable transports but the Extended "
1900  "ORPort is disabled. Tor and your pluggable transports proxy "
1901  "communicate with each other via the Extended ORPort so it "
1902  "is suggested you enable it: it will also allow your Bridge "
1903  "to collect statistics about its clients that use pluggable "
1904  "transports. Please enable it using the ExtORPort torrc option "
1905  "(e.g. set 'ExtORPort auto').");
1906  }
1907 
1908  if (options->Bridges) {
1909  mark_bridge_list();
1910  for (cl = options->Bridges; cl; cl = cl->next) {
1911  bridge_line_t *bridge_line = parse_bridge_line(cl->value);
1912  if (!bridge_line) {
1913  // LCOV_EXCL_START
1914  log_warn(LD_BUG,
1915  "Previously validated Bridge line could not be added!");
1916  return -1;
1917  // LCOV_EXCL_STOP
1918  }
1919  bridge_add_from_config(bridge_line);
1920  }
1922  }
1923 
1924  if (running_tor && hs_config_service_all(options, 0)<0) {
1925  // LCOV_EXCL_START
1926  log_warn(LD_BUG,
1927  "Previously validated hidden services line could not be added!");
1928  return -1;
1929  // LCOV_EXCL_STOP
1930  }
1931 
1932  if (running_tor && hs_config_client_auth_all(options, 0) < 0) {
1933  // LCOV_EXCL_START
1934  log_warn(LD_BUG, "Previously validated client authorization for "
1935  "hidden services could not be added!");
1936  return -1;
1937  // LCOV_EXCL_STOP
1938  }
1939 
1940  if (running_tor && !old_options &&
1941  options->OwningControllerFD != UINT64_MAX) {
1942  const unsigned ctrl_flags =
1943  CC_LOCAL_FD_IS_OWNER |
1944  CC_LOCAL_FD_IS_AUTHENTICATED;
1945  tor_socket_t ctrl_sock = (tor_socket_t)options->OwningControllerFD;
1946  if (control_connection_add_local_fd(ctrl_sock, ctrl_flags) < 0) {
1947  log_warn(LD_CONFIG, "Could not add local controller connection with "
1948  "given FD.");
1949  return -1;
1950  }
1951  }
1952 
1953  /* Load state */
1954  if (! or_state_loaded() && running_tor) {
1955  if (or_state_load())
1956  return -1;
1957  rep_hist_load_mtbf_data(time(NULL));
1958  }
1959 
1960  /* If we have an ExtORPort, initialize its auth cookie. */
1961  if (running_tor &&
1962  init_ext_or_cookie_authentication(!!options->ExtORPort_lines) < 0) {
1963  log_warn(LD_CONFIG,"Error creating Extended ORPort cookie file.");
1964  return -1;
1965  }
1966 
1969  if (!options->DisableNetwork) {
1970  if (options->ClientTransportPlugin) {
1971  for (cl = options->ClientTransportPlugin; cl; cl = cl->next) {
1972  if (parse_transport_line(options, cl->value, 0, 0) < 0) {
1973  // LCOV_EXCL_START
1974  log_warn(LD_BUG,
1975  "Previously validated ClientTransportPlugin line "
1976  "could not be added!");
1977  return -1;
1978  // LCOV_EXCL_STOP
1979  }
1980  }
1981  }
1982 
1983  if (options->ServerTransportPlugin && server_mode(options)) {
1984  for (cl = options->ServerTransportPlugin; cl; cl = cl->next) {
1985  if (parse_transport_line(options, cl->value, 0, 1) < 0) {
1986  // LCOV_EXCL_START
1987  log_warn(LD_BUG,
1988  "Previously validated ServerTransportPlugin line "
1989  "could not be added!");
1990  return -1;
1991  // LCOV_EXCL_STOP
1992  }
1993  }
1994  }
1995  }
1997  sweep_proxy_list();
1998 
1999  /* Start the PT proxy configuration. By doing this configuration
2000  here, we also figure out which proxies need to be restarted and
2001  which not. */
2002  if (pt_proxies_configuration_pending() && !net_is_disabled())
2004 
2005  /* Bail out at this point if we're not going to be a client or server:
2006  * we want to not fork, and to log stuff to stderr. */
2007  if (!running_tor)
2008  return 0;
2009 
2010  /* Finish backgrounding the process */
2011  if (options->RunAsDaemon) {
2012  /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
2013  finish_daemon(options->DataDirectory);
2014  }
2015 
2016  /* We want to reinit keys as needed before we do much of anything else:
2017  keys are important, and other things can depend on them. */
2018  if (transition_affects_workers ||
2019  (options->V3AuthoritativeDir && (!old_options ||
2020  !old_options->V3AuthoritativeDir))) {
2021  if (init_keys() < 0) {
2022  log_warn(LD_BUG,"Error initializing keys; exiting");
2023  return -1;
2024  }
2025  }
2026 
2027  /* Write our PID to the PID file. If we do not have write permissions we
2028  * will log a warning and exit. */
2029  if (options->PidFile && !sandbox_is_active()) {
2030  if (write_pidfile(options->PidFile) < 0) {
2031  log_err(LD_CONFIG, "Unable to write PIDFile %s",
2032  escaped(options->PidFile));
2033  return -1;
2034  }
2035  }
2036 
2037  /* Register addressmap directives */
2038  config_register_addressmaps(options);
2039  parse_virtual_addr_network(options->VirtualAddrNetworkIPv4, AF_INET,0,NULL);
2040  parse_virtual_addr_network(options->VirtualAddrNetworkIPv6, AF_INET6,0,NULL);
2041 
2042  /* Update address policies. */
2043  if (policies_parse_from_options(options) < 0) {
2044  /* This should be impossible, but let's be sure. */
2045  log_warn(LD_BUG,"Error parsing already-validated policy options.");
2046  return -1;
2047  }
2048 
2049  if (server_mode(options)) {
2050  static int cdm_initialized = 0;
2051  if (cdm_initialized == 0) {
2052  cdm_initialized = 1;
2053  consdiffmgr_configure(NULL);
2054  consdiffmgr_validate();
2055  }
2056  }
2057 
2058  if (init_control_cookie_authentication(options->CookieAuthentication) < 0) {
2059  log_warn(LD_CONFIG,"Error creating control cookie authentication file.");
2060  return -1;
2061  }
2062 
2064 
2065  /* reload keys as needed for rendezvous services. */
2066  if (hs_service_load_all_keys() < 0) {
2067  log_warn(LD_GENERAL,"Error loading rendezvous service keys");
2068  return -1;
2069  }
2070 
2071  /* Inform the scheduler subsystem that a configuration changed happened. It
2072  * might be a change of scheduler or parameter. */
2074 
2075  /* Set up accounting */
2076  if (accounting_parse_options(options, 0)<0) {
2077  // LCOV_EXCL_START
2078  log_warn(LD_BUG,"Error in previously validated accounting options");
2079  return -1;
2080  // LCOV_EXCL_STOP
2081  }
2082  if (accounting_is_enabled(options))
2083  configure_accounting(time(NULL));
2084 
2085  /* Change the cell EWMA settings */
2086  cmux_ewma_set_options(options, networkstatus_get_latest_consensus());
2087 
2088  /* Update the BridgePassword's hashed version as needed. We store this as a
2089  * digest so that we can do side-channel-proof comparisons on it.
2090  */
2091  if (options->BridgePassword) {
2092  char *http_authenticator;
2093  http_authenticator = alloc_http_authenticator(options->BridgePassword);
2094  if (!http_authenticator) {
2095  // XXXX This should get validated in options_validate().
2096  log_warn(LD_BUG, "Unable to allocate HTTP authenticator. Not setting "
2097  "BridgePassword.");
2098  return -1;
2099  }
2100  options->BridgePassword_AuthDigest_ = tor_malloc(DIGEST256_LEN);
2102  http_authenticator, strlen(http_authenticator),
2103  DIGEST_SHA256);
2104  tor_free(http_authenticator);
2105  }
2106 
2107  if (parse_outbound_addresses(options, 0, &msg) < 0) {
2108  // LCOV_EXCL_START
2109  log_warn(LD_BUG, "Failed parsing previously validated outbound "
2110  "bind addresses: %s", msg);
2111  tor_free(msg);
2112  return -1;
2113  // LCOV_EXCL_STOP
2114  }
2115 
2116  config_maybe_load_geoip_files_(options, old_options);
2117 
2118  if (geoip_is_loaded(AF_INET) && options->GeoIPExcludeUnknown) {
2119  /* ExcludeUnknown is true or "auto" */
2120  const int is_auto = options->GeoIPExcludeUnknown == -1;
2121  int changed;
2122 
2123  changed = routerset_add_unknown_ccs(&options->ExcludeNodes, is_auto);
2124  changed += routerset_add_unknown_ccs(&options->ExcludeExitNodes, is_auto);
2125 
2126  if (changed)
2128  }
2129 
2130  /* Check for transitions that need action. */
2131  if (old_options) {
2132  int revise_trackexithosts = 0;
2133  int revise_automap_entries = 0;
2134  int abandon_circuits = 0;
2135  if ((options->UseEntryGuards && !old_options->UseEntryGuards) ||
2136  options->UseBridges != old_options->UseBridges ||
2137  (options->UseBridges &&
2138  !config_lines_eq(options->Bridges, old_options->Bridges)) ||
2139  !routerset_equal(old_options->ExcludeNodes,options->ExcludeNodes) ||
2140  !routerset_equal(old_options->ExcludeExitNodes,
2141  options->ExcludeExitNodes) ||
2142  !routerset_equal(old_options->EntryNodes, options->EntryNodes) ||
2143  !routerset_equal(old_options->ExitNodes, options->ExitNodes) ||
2144  !routerset_equal(old_options->HSLayer2Nodes,
2145  options->HSLayer2Nodes) ||
2146  !routerset_equal(old_options->HSLayer3Nodes,
2147  options->HSLayer3Nodes) ||
2148  !routerset_equal(old_options->MiddleNodes, options->MiddleNodes) ||
2149  options->StrictNodes != old_options->StrictNodes) {
2150  log_info(LD_CIRC,
2151  "Changed to using entry guards or bridges, or changed "
2152  "preferred or excluded node lists. "
2153  "Abandoning previous circuits.");
2154  abandon_circuits = 1;
2155  }
2156 
2157  if (transition_affects_guards) {
2158  if (guards_update_all()) {
2159  abandon_circuits = 1;
2160  }
2161  }
2162 
2163  if (abandon_circuits) {
2166  revise_trackexithosts = 1;
2167  }
2168 
2169  if (!smartlist_strings_eq(old_options->TrackHostExits,
2170  options->TrackHostExits))
2171  revise_trackexithosts = 1;
2172 
2173  if (revise_trackexithosts)
2175 
2176  if (!options->AutomapHostsOnResolve &&
2177  old_options->AutomapHostsOnResolve) {
2178  revise_automap_entries = 1;
2179  } else {
2180  if (!smartlist_strings_eq(old_options->AutomapHostsSuffixes,
2181  options->AutomapHostsSuffixes))
2182  revise_automap_entries = 1;
2183  else if (!opt_streq(old_options->VirtualAddrNetworkIPv4,
2184  options->VirtualAddrNetworkIPv4) ||
2185  !opt_streq(old_options->VirtualAddrNetworkIPv6,
2186  options->VirtualAddrNetworkIPv6))
2187  revise_automap_entries = 1;
2188  }
2189 
2190  if (revise_automap_entries)
2192 
2193 /* How long should we delay counting bridge stats after becoming a bridge?
2194  * We use this so we don't count clients who used our bridge thinking it is
2195  * a relay. If you change this, don't forget to change the log message
2196  * below. It's 4 hours (the time it takes to stop being used by clients)
2197  * plus some extra time for clock skew. */
2198 #define RELAY_BRIDGE_STATS_DELAY (6 * 60 * 60)
2199 
2200  if (! bool_eq(options->BridgeRelay, old_options->BridgeRelay)) {
2201  int was_relay = 0;
2202  if (options->BridgeRelay) {
2203  time_t int_start = time(NULL);
2204  if (config_lines_eq(old_options->ORPort_lines,options->ORPort_lines)) {
2205  int_start += RELAY_BRIDGE_STATS_DELAY;
2206  was_relay = 1;
2207  }
2208  geoip_bridge_stats_init(int_start);
2209  log_info(LD_CONFIG, "We are acting as a bridge now. Starting new "
2210  "GeoIP stats interval%s.", was_relay ? " in 6 "
2211  "hours from now" : "");
2212  } else {
2214  log_info(LD_GENERAL, "We are no longer acting as a bridge. "
2215  "Forgetting GeoIP stats.");
2216  }
2217  }
2218 
2219  if (transition_affects_workers) {
2220  log_info(LD_GENERAL,
2221  "Worker-related options changed. Rotating workers.");
2222  const int server_mode_turned_on =
2223  server_mode(options) && !server_mode(old_options);
2224  const int dir_server_mode_turned_on =
2225  dir_server_mode(options) && !dir_server_mode(old_options);
2226 
2227  if (server_mode_turned_on || dir_server_mode_turned_on) {
2228  cpu_init();
2229  }
2230 
2231  if (server_mode_turned_on) {
2232  ip_address_changed(0);
2233  if (have_completed_a_circuit() || !any_predicted_circuits(time(NULL)))
2235  }
2237  if (dns_reset())
2238  return -1;
2239  } else {
2240  if (dns_reset())
2241  return -1;
2242  }
2243 
2244  if (options->PerConnBWRate != old_options->PerConnBWRate ||
2245  options->PerConnBWBurst != old_options->PerConnBWBurst)
2246  connection_or_update_token_buckets(get_connection_array(), options);
2247 
2248  if (options->BandwidthRate != old_options->BandwidthRate ||
2249  options->BandwidthBurst != old_options->BandwidthBurst ||
2250  options->RelayBandwidthRate != old_options->RelayBandwidthRate ||
2251  options->RelayBandwidthBurst != old_options->RelayBandwidthBurst)
2252  connection_bucket_adjust(options);
2253 
2254  if (options->MainloopStats != old_options->MainloopStats) {
2256  }
2257  }
2258 
2259  /* Only collect directory-request statistics on relays and bridges. */
2260  options->DirReqStatistics = options->DirReqStatistics_option &&
2261  server_mode(options);
2262  options->HiddenServiceStatistics =
2263  options->HiddenServiceStatistics_option && server_mode(options);
2264 
2265  if (options->CellStatistics || options->DirReqStatistics ||
2266  options->EntryStatistics || options->ExitPortStatistics ||
2267  options->ConnDirectionStatistics ||
2268  options->HiddenServiceStatistics ||
2269  options->BridgeAuthoritativeDir) {
2270  time_t now = time(NULL);
2271  int print_notice = 0;
2272 
2273  /* Only collect other relay-only statistics on relays. */
2274  if (!public_server_mode(options)) {
2275  options->CellStatistics = 0;
2276  options->EntryStatistics = 0;
2277  options->ConnDirectionStatistics = 0;
2278  options->ExitPortStatistics = 0;
2279  }
2280 
2281  if ((!old_options || !old_options->CellStatistics) &&
2282  options->CellStatistics) {
2284  print_notice = 1;
2285  }
2286  if ((!old_options || !old_options->DirReqStatistics) &&
2287  options->DirReqStatistics) {
2288  if (geoip_is_loaded(AF_INET)) {
2290  print_notice = 1;
2291  } else {
2292  /* disable statistics collection since we have no geoip file */
2293  options->DirReqStatistics = 0;
2294  if (options->ORPort_set)
2295  log_notice(LD_CONFIG, "Configured to measure directory request "
2296  "statistics, but no GeoIP database found. "
2297  "Please specify a GeoIP database using the "
2298  "GeoIPFile option.");
2299  }
2300  }
2301  if ((!old_options || !old_options->EntryStatistics) &&
2302  options->EntryStatistics && !should_record_bridge_info(options)) {
2303  /* If we get here, we've started recording bridge info when we didn't
2304  * do so before. Note that "should_record_bridge_info()" will
2305  * always be false at this point, because of the earlier block
2306  * that cleared EntryStatistics when public_server_mode() was false.
2307  * We're leaving it in as defensive programming. */
2308  if (geoip_is_loaded(AF_INET) || geoip_is_loaded(AF_INET6)) {
2310  print_notice = 1;
2311  } else {
2312  options->EntryStatistics = 0;
2313  log_notice(LD_CONFIG, "Configured to measure entry node "
2314  "statistics, but no GeoIP database found. "
2315  "Please specify a GeoIP database using the "
2316  "GeoIPFile option.");
2317  }
2318  }
2319  if ((!old_options || !old_options->ExitPortStatistics) &&
2320  options->ExitPortStatistics) {
2322  print_notice = 1;
2323  }
2324  if ((!old_options || !old_options->ConnDirectionStatistics) &&
2325  options->ConnDirectionStatistics) {
2327  }
2328  if ((!old_options || !old_options->HiddenServiceStatistics) &&
2329  options->HiddenServiceStatistics) {
2330  log_info(LD_CONFIG, "Configured to measure hidden service statistics.");
2332  }
2333  if ((!old_options || !old_options->BridgeAuthoritativeDir) &&
2334  options->BridgeAuthoritativeDir) {
2336  print_notice = 1;
2337  }
2338  if (print_notice)
2339  log_notice(LD_CONFIG, "Configured to measure statistics. Look for "
2340  "the *-stats files that will first be written to the "
2341  "data directory in 24 hours from now.");
2342  }
2343 
2344  /* If we used to have statistics enabled but we just disabled them,
2345  stop gathering them. */
2346  if (old_options && old_options->CellStatistics &&
2347  !options->CellStatistics)
2349  if (old_options && old_options->DirReqStatistics &&
2350  !options->DirReqStatistics)
2352  if (old_options && old_options->EntryStatistics &&
2353  !options->EntryStatistics)
2355  if (old_options && old_options->HiddenServiceStatistics &&
2356  !options->HiddenServiceStatistics)
2358  if (old_options && old_options->ExitPortStatistics &&
2359  !options->ExitPortStatistics)
2361  if (old_options && old_options->ConnDirectionStatistics &&
2362  !options->ConnDirectionStatistics)
2364  if (old_options && old_options->BridgeAuthoritativeDir &&
2365  !options->BridgeAuthoritativeDir)
2367 
2368  /* Since our options changed, we might need to regenerate and upload our
2369  * server descriptor.
2370  */
2371  if (!old_options ||
2372  options_transition_affects_descriptor(old_options, options))
2373  mark_my_descriptor_dirty("config change");
2374 
2375  /* We may need to reschedule some directory stuff if our status changed. */
2376  if (old_options) {
2377  if (options_transition_affects_dirauth_timing(old_options, options)) {
2378  voting_schedule_recalculate_timing(options, time(NULL));
2379  reschedule_dirvote(options);
2380  }
2382  directory_fetches_dir_info_early(old_options)) ||
2384  directory_fetches_dir_info_later(old_options))) {
2385  /* Make sure update_router_have_minimum_dir_info() gets called. */
2387  /* We might need to download a new consensus status later or sooner than
2388  * we had expected. */
2390  }
2391  }
2392 
2393  /* DoS mitigation subsystem only applies to public relay. */
2394  if (public_server_mode(options)) {
2395  /* If we are configured as a relay, initialize the subsystem. Even on HUP,
2396  * this is safe to call as it will load data from the current options
2397  * or/and the consensus. */
2398  dos_init();
2399  } else if (old_options && public_server_mode(old_options)) {
2400  /* Going from relay to non relay, clean it up. */
2401  dos_free_all();
2402  }
2403 
2404  /* Load the webpage we're going to serve every time someone asks for '/' on
2405  our DirPort. */
2407  if (options->DirPortFrontPage) {
2409  read_file_to_str(options->DirPortFrontPage, 0, NULL);
2411  log_warn(LD_CONFIG,
2412  "DirPortFrontPage file '%s' not found. Continuing anyway.",
2413  options->DirPortFrontPage);
2414  }
2415  }
2416 
2417  return 0;
2418 }
2419 
2420 typedef enum {
2421  TAKES_NO_ARGUMENT = 0,
2422  ARGUMENT_NECESSARY = 1,
2423  ARGUMENT_OPTIONAL = 2
2424 } takes_argument_t;
2425 
2426 static const struct {
2427  const char *name;
2428  takes_argument_t takes_argument;
2429 } CMDLINE_ONLY_OPTIONS[] = {
2430  { "-f", ARGUMENT_NECESSARY },
2431  { "--allow-missing-torrc", TAKES_NO_ARGUMENT },
2432  { "--defaults-torrc", ARGUMENT_NECESSARY },
2433  { "--hash-password", ARGUMENT_NECESSARY },
2434  { "--dump-config", ARGUMENT_OPTIONAL },
2435  { "--list-fingerprint", TAKES_NO_ARGUMENT },
2436  { "--keygen", TAKES_NO_ARGUMENT },
2437  { "--key-expiration", ARGUMENT_OPTIONAL },
2438  { "--newpass", TAKES_NO_ARGUMENT },
2439  { "--no-passphrase", TAKES_NO_ARGUMENT },
2440  { "--passphrase-fd", ARGUMENT_NECESSARY },
2441  { "--verify-config", TAKES_NO_ARGUMENT },
2442  { "--ignore-missing-torrc", TAKES_NO_ARGUMENT },
2443  { "--quiet", TAKES_NO_ARGUMENT },
2444  { "--hush", TAKES_NO_ARGUMENT },
2445  { "--version", TAKES_NO_ARGUMENT },
2446  { "--library-versions", TAKES_NO_ARGUMENT },
2447  { "-h", TAKES_NO_ARGUMENT },
2448  { "--help", TAKES_NO_ARGUMENT },
2449  { "--list-torrc-options", TAKES_NO_ARGUMENT },
2450  { "--list-deprecated-options",TAKES_NO_ARGUMENT },
2451  { "--nt-service", TAKES_NO_ARGUMENT },
2452  { "-nt-service", TAKES_NO_ARGUMENT },
2453  { NULL, 0 },
2454 };
2455 
2461 int
2462 config_parse_commandline(int argc, char **argv, int ignore_errors,
2463  config_line_t **result,
2464  config_line_t **cmdline_result)
2465 {
2466  config_line_t *param = NULL;
2467 
2468  config_line_t *front = NULL;
2469  config_line_t **new = &front;
2470 
2471  config_line_t *front_cmdline = NULL;
2472  config_line_t **new_cmdline = &front_cmdline;
2473 
2474  char *s, *arg;
2475  int i = 1;
2476 
2477  while (i < argc) {
2478  unsigned command = CONFIG_LINE_NORMAL;
2479  takes_argument_t want_arg = ARGUMENT_NECESSARY;
2480  int is_cmdline = 0;
2481  int j;
2482 
2483  for (j = 0; CMDLINE_ONLY_OPTIONS[j].name != NULL; ++j) {
2484  if (!strcmp(argv[i], CMDLINE_ONLY_OPTIONS[j].name)) {
2485  is_cmdline = 1;
2486  want_arg = CMDLINE_ONLY_OPTIONS[j].takes_argument;
2487  break;
2488  }
2489  }
2490 
2491  s = argv[i];
2492 
2493  /* Each keyword may be prefixed with one or two dashes. */
2494  if (*s == '-')
2495  s++;
2496  if (*s == '-')
2497  s++;
2498  /* Figure out the command, if any. */
2499  if (*s == '+') {
2500  s++;
2501  command = CONFIG_LINE_APPEND;
2502  } else if (*s == '/') {
2503  s++;
2504  command = CONFIG_LINE_CLEAR;
2505  /* A 'clear' command has no argument. */
2506  want_arg = 0;
2507  }
2508 
2509  const int is_last = (i == argc-1);
2510 
2511  if (want_arg == ARGUMENT_NECESSARY && is_last) {
2512  if (ignore_errors) {
2513  arg = tor_strdup("");
2514  } else {
2515  log_warn(LD_CONFIG,"Command-line option '%s' with no value. Failing.",
2516  argv[i]);
2517  config_free_lines(front);
2518  config_free_lines(front_cmdline);
2519  return -1;
2520  }
2521  } else if (want_arg == ARGUMENT_OPTIONAL && is_last) {
2522  arg = tor_strdup("");
2523  } else {
2524  arg = (want_arg != TAKES_NO_ARGUMENT) ? tor_strdup(argv[i+1]) :
2525  tor_strdup("");
2526  }
2527 
2528  param = tor_malloc_zero(sizeof(config_line_t));
2529  param->key = is_cmdline ? tor_strdup(argv[i]) :
2530  tor_strdup(config_expand_abbrev(&options_format, s, 1, 1));
2531  param->value = arg;
2532  param->command = command;
2533  param->next = NULL;
2534  log_debug(LD_CONFIG, "command line: parsed keyword '%s', value '%s'",
2535  param->key, param->value);
2536 
2537  if (is_cmdline) {
2538  *new_cmdline = param;
2539  new_cmdline = &((*new_cmdline)->next);
2540  } else {
2541  *new = param;
2542  new = &((*new)->next);
2543  }
2544 
2545  i += want_arg ? 2 : 1;
2546  }
2547  *cmdline_result = front_cmdline;
2548  *result = front;
2549  return 0;
2550 }
2551 
2553 int
2554 option_is_recognized(const char *key)
2555 {
2556  const config_var_t *var = config_find_option(&options_format, key);
2557  return (var != NULL);
2558 }
2559 
2562 const char *
2564 {
2565  const config_var_t *var = config_find_option(&options_format, key);
2566  return var ? var->name : NULL;
2567 }
2568 
2571 config_line_t *
2572 option_get_assignment(const or_options_t *options, const char *key)
2573 {
2574  return config_get_assigned_option(&options_format, options, key, 1);
2575 }
2576 
2587 options_trial_assign(config_line_t *list, unsigned flags, char **msg)
2588 {
2589  int r;
2590  or_options_t *trial_options = config_dup(&options_format, get_options());
2591 
2592  if ((r=config_assign(&options_format, trial_options,
2593  list, flags, msg)) < 0) {
2594  or_options_free(trial_options);
2595  return r;
2596  }
2597 
2598  setopt_err_t rv;
2599  or_options_t *cur_options = get_options_mutable();
2600 
2602 
2603  if (options_validate(cur_options, trial_options,
2604  global_default_options, 1, msg) < 0) {
2605  or_options_free(trial_options);
2606  rv = SETOPT_ERR_PARSE; /*XXX make this a separate return value. */
2607  goto done;
2608  }
2609 
2610  if (options_transition_allowed(cur_options, trial_options, msg) < 0) {
2611  or_options_free(trial_options);
2612  rv = SETOPT_ERR_TRANSITION;
2613  goto done;
2614  }
2616 
2617  if (set_options(trial_options, msg)<0) {
2618  or_options_free(trial_options);
2619  rv = SETOPT_ERR_SETTING;
2620  goto done;
2621  }
2622 
2623  /* we liked it. put it in place. */
2624  rv = SETOPT_OK;
2625  done:
2627  return rv;
2628 }
2629 
2631 static void
2633 {
2634  printf(
2635 "Copyright (c) 2001-2004, Roger Dingledine\n"
2636 "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
2637 "Copyright (c) 2007-2019, The Tor Project, Inc.\n\n"
2638 "tor -f <torrc> [args]\n"
2639 "See man page for options, or https://www.torproject.org/ for "
2640 "documentation.\n");
2641 }
2642 
2644 static void
2646 {
2647  int i;
2648  for (i = 0; option_vars_[i].name; ++i) {
2649  const config_var_t *var = &option_vars_[i];
2650  if (var->type == CONFIG_TYPE_OBSOLETE ||
2651  var->type == CONFIG_TYPE_LINELIST_V)
2652  continue;
2653  printf("%s\n", var->name);
2654  }
2655 }
2656 
2658 static void
2660 {
2661  const config_deprecation_t *d;
2662  for (d = option_deprecation_notes_; d->name; ++d) {
2663  printf("%s\n", d->name);
2664  }
2665 }
2666 
2668 static uint32_t last_resolved_addr = 0;
2669 
2671 uint32_t
2673 {
2674  return last_resolved_addr;
2675 }
2676 
2678 void
2680 {
2681  last_resolved_addr = 0;
2682 }
2683 
2684 /* Return true if <b>options</b> is using the default authorities, and false
2685  * if any authority-related option has been overridden. */
2686 int
2687 using_default_dir_authorities(const or_options_t *options)
2688 {
2689  return (!options->DirAuthorities && !options->AlternateDirAuthority);
2690 }
2691 
2740 int
2741 resolve_my_address(int warn_severity, const or_options_t *options,
2742  uint32_t *addr_out,
2743  const char **method_out, char **hostname_out)
2744 {
2745  struct in_addr in;
2746  uint32_t addr; /* host order */
2747  char hostname[256];
2748  const char *method_used;
2749  const char *hostname_used;
2750  int explicit_ip=1;
2751  int explicit_hostname=1;
2752  int from_interface=0;
2753  char *addr_string = NULL;
2754  const char *address = options->Address;
2755  int notice_severity = warn_severity <= LOG_NOTICE ?
2756  LOG_NOTICE : warn_severity;
2757 
2758  tor_addr_t myaddr;
2759  tor_assert(addr_out);
2760 
2761  /*
2762  * Step one: Fill in 'hostname' to be our best guess.
2763  */
2764 
2765  if (address && *address) {
2766  strlcpy(hostname, address, sizeof(hostname));
2767  } else { /* then we need to guess our address */
2768  explicit_ip = 0; /* it's implicit */
2769  explicit_hostname = 0; /* it's implicit */
2770 
2771  if (tor_gethostname(hostname, sizeof(hostname)) < 0) {
2772  log_fn(warn_severity, LD_NET,"Error obtaining local hostname");
2773  return -1;
2774  }
2775  log_debug(LD_CONFIG, "Guessed local host name as '%s'", hostname);
2776  }
2777 
2778  /*
2779  * Step two: Now that we know 'hostname', parse it or resolve it. If
2780  * it doesn't parse or resolve, look at the interface address. Set 'addr'
2781  * to be our (host-order) 32-bit answer.
2782  */
2783 
2784  if (tor_inet_aton(hostname, &in) == 0) {
2785  /* then we have to resolve it */
2786  explicit_ip = 0;
2787  if (tor_lookup_hostname(hostname, &addr)) { /* failed to resolve */
2788  uint32_t interface_ip; /* host order */
2789 
2790  if (explicit_hostname) {
2791  log_fn(warn_severity, LD_CONFIG,
2792  "Could not resolve local Address '%s'. Failing.", hostname);
2793  return -1;
2794  }
2795  log_fn(notice_severity, LD_CONFIG,
2796  "Could not resolve guessed local hostname '%s'. "
2797  "Trying something else.", hostname);
2798  if (get_interface_address(warn_severity, &interface_ip)) {
2799  log_fn(warn_severity, LD_CONFIG,
2800  "Could not get local interface IP address. Failing.");
2801  return -1;
2802  }
2803  from_interface = 1;
2804  addr = interface_ip;
2805  log_fn(notice_severity, LD_CONFIG, "Learned IP address '%s' for "
2806  "local interface. Using that.", fmt_addr32(addr));
2807  strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2808  } else { /* resolved hostname into addr */
2809  tor_addr_from_ipv4h(&myaddr, addr);
2810 
2811  if (!explicit_hostname &&
2812  tor_addr_is_internal(&myaddr, 0)) {
2813  tor_addr_t interface_ip;
2814 
2815  log_fn(notice_severity, LD_CONFIG, "Guessed local hostname '%s' "
2816  "resolves to a private IP address (%s). Trying something "
2817  "else.", hostname, fmt_addr32(addr));
2818 
2819  if (get_interface_address6(warn_severity, AF_INET, &interface_ip)<0) {
2820  log_fn(warn_severity, LD_CONFIG,
2821  "Could not get local interface IP address. Too bad.");
2822  } else if (tor_addr_is_internal(&interface_ip, 0)) {
2823  log_fn(notice_severity, LD_CONFIG,
2824  "Interface IP address '%s' is a private address too. "
2825  "Ignoring.", fmt_addr(&interface_ip));
2826  } else {
2827  from_interface = 1;
2828  addr = tor_addr_to_ipv4h(&interface_ip);
2829  log_fn(notice_severity, LD_CONFIG,
2830  "Learned IP address '%s' for local interface."
2831  " Using that.", fmt_addr32(addr));
2832  strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
2833  }
2834  }
2835  }
2836  } else {
2837  addr = ntohl(in.s_addr); /* set addr so that addr_string is not
2838  * illformed */
2839  }
2840 
2841  /*
2842  * Step three: Check whether 'addr' is an internal IP address, and error
2843  * out if it is and we don't want that.
2844  */
2845 
2846  tor_addr_from_ipv4h(&myaddr,addr);
2847 
2848  addr_string = tor_dup_ip(addr);
2849  if (tor_addr_is_internal(&myaddr, 0)) {
2850  /* make sure we're ok with publishing an internal IP */
2851  if (using_default_dir_authorities(options)) {
2852  /* if they are using the default authorities, disallow internal IPs
2853  * always. */
2854  log_fn(warn_severity, LD_CONFIG,
2855  "Address '%s' resolves to private IP address '%s'. "
2856  "Tor servers that use the default DirAuthorities must have "
2857  "public IP addresses.", hostname, addr_string);
2858  tor_free(addr_string);
2859  return -1;
2860  }
2861  if (!explicit_ip) {
2862  /* even if they've set their own authorities, require an explicit IP if
2863  * they're using an internal address. */
2864  log_fn(warn_severity, LD_CONFIG, "Address '%s' resolves to private "
2865  "IP address '%s'. Please set the Address config option to be "
2866  "the IP address you want to use.", hostname, addr_string);
2867  tor_free(addr_string);
2868  return -1;
2869  }
2870  }
2871 
2872  /*
2873  * Step four: We have a winner! 'addr' is our answer for sure, and
2874  * 'addr_string' is its string form. Fill out the various fields to
2875  * say how we decided it.
2876  */
2877 
2878  log_debug(LD_CONFIG, "Resolved Address to '%s'.", addr_string);
2879 
2880  if (explicit_ip) {
2881  method_used = "CONFIGURED";
2882  hostname_used = NULL;
2883  } else if (explicit_hostname) {
2884  method_used = "RESOLVED";
2885  hostname_used = hostname;
2886  } else if (from_interface) {
2887  method_used = "INTERFACE";
2888  hostname_used = NULL;
2889  } else {
2890  method_used = "GETHOSTNAME";
2891  hostname_used = hostname;
2892  }
2893 
2894  *addr_out = addr;
2895  if (method_out)
2896  *method_out = method_used;
2897  if (hostname_out)
2898  *hostname_out = hostname_used ? tor_strdup(hostname_used) : NULL;
2899 
2900  /*
2901  * Step five: Check if the answer has changed since last time (or if
2902  * there was no last time), and if so call various functions to keep
2903  * us up-to-date.
2904  */
2905 
2906  if (last_resolved_addr && last_resolved_addr != *addr_out) {
2907  /* Leave this as a notice, regardless of the requested severity,
2908  * at least until dynamic IP address support becomes bulletproof. */
2909  log_notice(LD_NET,
2910  "Your IP address seems to have changed to %s "
2911  "(METHOD=%s%s%s). Updating.",
2912  addr_string, method_used,
2913  hostname_used ? " HOSTNAME=" : "",
2914  hostname_used ? hostname_used : "");
2915  ip_address_changed(0);
2916  }
2917 
2918  if (last_resolved_addr != *addr_out) {
2920  "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s%s%s",
2921  addr_string, method_used,
2922  hostname_used ? " HOSTNAME=" : "",
2923  hostname_used ? hostname_used : "");
2924  }
2925  last_resolved_addr = *addr_out;
2926 
2927  /*
2928  * And finally, clean up and return success.
2929  */
2930 
2931  tor_free(addr_string);
2932  return 0;
2933 }
2934 
2939 is_local_addr, (const tor_addr_t *addr))
2940 {
2941  if (tor_addr_is_internal(addr, 0))
2942  return 1;
2943  /* Check whether ip is on the same /24 as we are. */
2944  if (get_options()->EnforceDistinctSubnets == 0)
2945  return 0;
2946  if (tor_addr_family(addr) == AF_INET) {
2947  uint32_t ip = tor_addr_to_ipv4h(addr);
2948 
2949  /* It's possible that this next check will hit before the first time
2950  * resolve_my_address actually succeeds. (For clients, it is likely that
2951  * resolve_my_address will never be called at all). In those cases,
2952  * last_resolved_addr will be 0, and so checking to see whether ip is on
2953  * the same /24 as last_resolved_addr will be the same as checking whether
2954  * it was on net 0, which is already done by tor_addr_is_internal.
2955  */
2956  if ((last_resolved_addr & (uint32_t)0xffffff00ul)
2957  == (ip & (uint32_t)0xffffff00ul))
2958  return 1;
2959  }
2960  return 0;
2961 }
2962 
2964 or_options_t *
2966 {
2967  return config_new(&options_format);
2968 }
2969 
2972 void
2974 {
2975  config_init(&options_format, options);
2976 }
2977 
2982 char *
2983 options_dump(const or_options_t *options, int how_to_dump)
2984 {
2985  const or_options_t *use_defaults;
2986  int minimal;
2987  switch (how_to_dump) {
2988  case OPTIONS_DUMP_MINIMAL:
2989  use_defaults = global_default_options;
2990  minimal = 1;
2991  break;
2992  case OPTIONS_DUMP_DEFAULTS:
2993  use_defaults = NULL;
2994  minimal = 1;
2995  break;
2996  case OPTIONS_DUMP_ALL:
2997  use_defaults = NULL;
2998  minimal = 0;
2999  break;
3000  default:
3001  log_warn(LD_BUG, "Bogus value for how_to_dump==%d", how_to_dump);
3002  return NULL;
3003  }
3004 
3005  return config_dump(&options_format, use_defaults, options, minimal, 0);
3006 }
3007 
3011 static int
3012 validate_ports_csv(smartlist_t *sl, const char *name, char **msg)
3013 {
3014  int i;
3015  tor_assert(name);
3016 
3017  if (!sl)
3018  return 0;
3019 
3020  SMARTLIST_FOREACH(sl, const char *, cp,
3021  {
3022  i = atoi(cp);
3023  if (i < 1 || i > 65535) {
3024  tor_asprintf(msg, "Port '%s' out of range in %s", cp, name);
3025  return -1;
3026  }
3027  });
3028  return 0;
3029 }
3030 
3035 static int
3036 ensure_bandwidth_cap(uint64_t *value, const char *desc, char **msg)
3037 {
3038  if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
3039  /* This handles an understandable special case where somebody says "2gb"
3040  * whereas our actual maximum is 2gb-1 (INT_MAX) */
3041  --*value;
3042  }
3043  if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
3044  tor_asprintf(msg, "%s (%"PRIu64") must be at most %d",
3045  desc, (*value),
3046  ROUTER_MAX_DECLARED_BANDWIDTH);
3047  return -1;
3048  }
3049  return 0;
3050 }
3051 
3058 static int
3060 {
3061  smartlist_t *list = options->PublishServerDescriptor;
3062  dirinfo_type_t *auth = &options->PublishServerDescriptor_;
3063  *auth = NO_DIRINFO;
3064  if (!list) /* empty list, answer is none */
3065  return 0;
3066  SMARTLIST_FOREACH_BEGIN(list, const char *, string) {
3067  if (!strcasecmp(string, "v1"))
3068  log_warn(LD_CONFIG, "PublishServerDescriptor v1 has no effect, because "
3069  "there are no v1 directory authorities anymore.");
3070  else if (!strcmp(string, "1"))
3071  if (options->BridgeRelay)
3072  *auth |= BRIDGE_DIRINFO;
3073  else
3074  *auth |= V3_DIRINFO;
3075  else if (!strcasecmp(string, "v2"))
3076  log_warn(LD_CONFIG, "PublishServerDescriptor v2 has no effect, because "
3077  "there are no v2 directory authorities anymore.");
3078  else if (!strcasecmp(string, "v3"))
3079  *auth |= V3_DIRINFO;
3080  else if (!strcasecmp(string, "bridge"))
3081  *auth |= BRIDGE_DIRINFO;
3082  else if (!strcasecmp(string, "hidserv"))
3083  log_warn(LD_CONFIG,
3084  "PublishServerDescriptor hidserv is invalid. See "
3085  "PublishHidServDescriptors.");
3086  else if (!strcasecmp(string, "") || !strcmp(string, "0"))
3087  /* no authority */;
3088  else
3089  return -1;
3090  } SMARTLIST_FOREACH_END(string);
3091  return 0;
3092 }
3093 
3096 #define MIN_REND_POST_PERIOD (10*60)
3097 #define MIN_REND_POST_PERIOD_TESTING (5)
3098 
3102 #define MAX_CIRCS_AVAILABLE_TIME (24*60*60)
3103 
3105 #define MAX_DIR_PERIOD ((7*24*60*60)/2)
3106 
3109 #define MIN_MAX_CIRCUIT_DIRTINESS 10
3110 
3113 #define MAX_MAX_CIRCUIT_DIRTINESS (30*24*60*60)
3114 
3117 #define MIN_CIRCUIT_STREAM_TIMEOUT 10
3118 
3124 #define RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT (10)
3125 
3126 static int
3127 options_validate_cb(void *old_options, void *options, void *default_options,
3128  int from_setconf, char **msg)
3129 {
3131  int rv = options_validate(old_options, options, default_options,
3132  from_setconf, msg);
3134  return rv;
3135 }
3136 
3138 static void
3139 options_free_cb(void *options)
3140 {
3141  or_options_free_(options);
3142 }
3143 
3144 #define REJECT(arg) \
3145  STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
3146 #if defined(__GNUC__) && __GNUC__ <= 3
3147 #define COMPLAIN(args...) \
3148  STMT_BEGIN log_warn(LD_CONFIG, args); STMT_END
3149 #else
3150 #define COMPLAIN(args, ...) \
3151  STMT_BEGIN log_warn(LD_CONFIG, args, ##__VA_ARGS__); STMT_END
3152 #endif /* defined(__GNUC__) && __GNUC__ <= 3 */
3153 
3162 static int
3164  char *filepath)
3165 {
3166  if (filepath && path_is_relative(filepath)) {
3167  char *abs_path = make_path_absolute(filepath);
3168  COMPLAIN("Path for %s (%s) is relative and will resolve to %s."
3169  " Is this what you wanted?", option, filepath, abs_path);
3170  tor_free(abs_path);
3171  return 1;
3172  }
3173  return 0;
3174 }
3175 
3181 static int
3183 {
3184  tor_assert(options);
3185  int n = 0;
3186 
3187  n += warn_if_option_path_is_relative("CookieAuthFile",
3188  options->CookieAuthFile);
3189  n += warn_if_option_path_is_relative("ExtORPortCookieAuthFile",
3190  options->ExtORPortCookieAuthFile);
3191  n += warn_if_option_path_is_relative("DirPortFrontPage",
3192  options->DirPortFrontPage);
3193  n += warn_if_option_path_is_relative("V3BandwidthsFile",
3194  options->V3BandwidthsFile);
3195  n += warn_if_option_path_is_relative("ControlPortWriteToFile",
3196  options->ControlPortWriteToFile);
3197  n += warn_if_option_path_is_relative("GeoIPFile",options->GeoIPFile);
3198  n += warn_if_option_path_is_relative("GeoIPv6File",options->GeoIPv6File);
3199  n += warn_if_option_path_is_relative("Log",options->DebugLogFile);
3200  n += warn_if_option_path_is_relative("AccelDir",options->AccelDir);
3201  n += warn_if_option_path_is_relative("DataDirectory",options->DataDirectory);
3202  n += warn_if_option_path_is_relative("PidFile",options->PidFile);
3203  n += warn_if_option_path_is_relative("ClientOnionAuthDir",
3204  options->ClientOnionAuthDir);
3205 
3206  for (config_line_t *hs_line = options->RendConfigLines; hs_line;
3207  hs_line = hs_line->next) {
3208  if (!strcasecmp(hs_line->key, "HiddenServiceDir"))
3209  n += warn_if_option_path_is_relative("HiddenServiceDir",hs_line->value);
3210  }
3211  return n != 0;
3212 }
3213 
3214 /* Validate options related to the scheduler. From the Schedulers list, the
3215  * SchedulerTypes_ list is created with int values so once we select the
3216  * scheduler, which can happen anytime at runtime, we don't have to parse
3217  * strings and thus be quick.
3218  *
3219  * Return 0 on success else -1 and msg is set with an error message. */
3220 static int
3221 options_validate_scheduler(or_options_t *options, char **msg)
3222 {
3223  tor_assert(options);
3224  tor_assert(msg);
3225 
3226  if (!options->Schedulers || smartlist_len(options->Schedulers) == 0) {
3227  REJECT("Empty Schedulers list. Either remove the option so the defaults "
3228  "can be used or set at least one value.");
3229  }
3230  /* Ok, we do have scheduler types, validate them. */
3231  options->SchedulerTypes_ = smartlist_new();
3232  SMARTLIST_FOREACH_BEGIN(options->Schedulers, const char *, type) {
3233  int *sched_type;
3234  if (!strcasecmp("KISTLite", type)) {
3235  sched_type = tor_malloc_zero(sizeof(int));
3236  *sched_type = SCHEDULER_KIST_LITE;
3237  smartlist_add(options->SchedulerTypes_, sched_type);
3238  } else if (!strcasecmp("KIST", type)) {
3239  sched_type = tor_malloc_zero(sizeof(int));
3240  *sched_type = SCHEDULER_KIST;
3241  smartlist_add(options->SchedulerTypes_, sched_type);
3242  } else if (!strcasecmp("Vanilla", type)) {
3243  sched_type = tor_malloc_zero(sizeof(int));
3244  *sched_type = SCHEDULER_VANILLA;
3245  smartlist_add(options->SchedulerTypes_, sched_type);
3246  } else {
3247  tor_asprintf(msg, "Unknown type %s in option Schedulers. "
3248  "Possible values are KIST, KISTLite and Vanilla.",
3249  escaped(type));
3250  return -1;
3251  }
3252  } SMARTLIST_FOREACH_END(type);
3253 
3254  if (options->KISTSockBufSizeFactor < 0) {
3255  REJECT("KISTSockBufSizeFactor must be at least 0");
3256  }
3257 
3258  /* Don't need to validate that the Interval is less than anything because
3259  * zero is valid and all negative values are valid. */
3260  if (options->KISTSchedRunInterval > KIST_SCHED_RUN_INTERVAL_MAX) {
3261  tor_asprintf(msg, "KISTSchedRunInterval must not be more than %d (ms)",
3262  KIST_SCHED_RUN_INTERVAL_MAX);
3263  return -1;
3264  }
3265 
3266  return 0;
3267 }
3268 
3269 /* Validate options related to single onion services.
3270  * Modifies some options that are incompatible with single onion services.
3271  * On failure returns -1, and sets *msg to an error string.
3272  * Returns 0 on success. */
3273 STATIC int
3274 options_validate_single_onion(or_options_t *options, char **msg)
3275 {
3276  /* The two single onion service options must have matching values. */
3277  if (options->HiddenServiceSingleHopMode &&
3278  !options->HiddenServiceNonAnonymousMode) {
3279  REJECT("HiddenServiceSingleHopMode does not provide any server anonymity. "
3280  "It must be used with HiddenServiceNonAnonymousMode set to 1.");
3281  }
3282  if (options->HiddenServiceNonAnonymousMode &&
3283  !options->HiddenServiceSingleHopMode) {
3284  REJECT("HiddenServiceNonAnonymousMode does not provide any server "
3285  "anonymity. It must be used with HiddenServiceSingleHopMode set to "
3286  "1.");
3287  }
3288 
3289  /* Now that we've checked that the two options are consistent, we can safely
3290  * call the rend_service_* functions that abstract these options. */
3291 
3292  /* If you run an anonymous client with an active Single Onion service, the
3293  * client loses anonymity. */
3294  const int client_port_set = (options->SocksPort_set ||
3295  options->TransPort_set ||
3296  options->NATDPort_set ||
3297  options->DNSPort_set ||
3298  options->HTTPTunnelPort_set);
3299  if (rend_service_non_anonymous_mode_enabled(options) && client_port_set) {
3300  REJECT("HiddenServiceNonAnonymousMode is incompatible with using Tor as "
3301  "an anonymous client. Please set Socks/Trans/NATD/DNSPort to 0, or "
3302  "revert HiddenServiceNonAnonymousMode to 0.");
3303  }
3304 
3305  if (rend_service_allow_non_anonymous_connection(options)
3306  && options->UseEntryGuards) {
3307  /* Single Onion services only use entry guards when uploading descriptors;
3308  * all other connections are one-hop. Further, Single Onions causes the
3309  * hidden service code to do things which break the path bias
3310  * detector, and it's far easier to turn off entry guards (and
3311  * thus the path bias detector with it) than to figure out how to
3312  * make path bias compatible with single onions.
3313  */
3314  log_notice(LD_CONFIG,
3315  "HiddenServiceSingleHopMode is enabled; disabling "
3316  "UseEntryGuards.");
3317  options->UseEntryGuards = 0;
3318  }
3319 
3320  return 0;
3321 }
3322 
3336 STATIC int
3338  or_options_t *default_options, int from_setconf, char **msg)
3339 {
3340  config_line_t *cl;
3341  const char *uname = get_uname();
3342  int n_ports=0;
3343  int world_writable_control_socket=0;
3344 
3345  tor_assert(msg);
3346  *msg = NULL;
3347 
3348  if (parse_ports(options, 1, msg, &n_ports,
3349  &world_writable_control_socket) < 0)
3350  return -1;
3351 
3352  /* Set UseEntryGuards from the configured value, before we check it below.
3353  * We change UseEntryGuards when it's incompatible with other options,
3354  * but leave UseEntryGuards_option with the original value.
3355  * Always use the value of UseEntryGuards, not UseEntryGuards_option. */
3356  options->UseEntryGuards = options->UseEntryGuards_option;
3357 
3358  if (server_mode(options) &&
3359  (!strcmpstart(uname, "Windows 95") ||
3360  !strcmpstart(uname, "Windows 98") ||
3361  !strcmpstart(uname, "Windows Me"))) {
3362  log_warn(LD_CONFIG, "Tor is running as a server, but you are "
3363  "running %s; this probably won't work. See "
3364  "https://www.torproject.org/docs/faq.html#BestOSForRelay "
3365  "for details.", uname);
3366  }
3367 
3368  if (parse_outbound_addresses(options, 1, msg) < 0)
3369  return -1;
3370 
3371  if (validate_data_directories(options)<0)
3372  REJECT("Invalid DataDirectory");
3373 
3374  /* need to check for relative paths after we populate
3375  * options->DataDirectory (just above). */
3376  if (warn_about_relative_paths(options) && options->RunAsDaemon) {
3377  REJECT("You have specified at least one relative path (see above) "
3378  "with the RunAsDaemon option. RunAsDaemon is not compatible "
3379  "with relative paths.");
3380  }
3381 
3382  if (options->Nickname == NULL) {
3383  if (server_mode(options)) {
3384  options->Nickname = tor_strdup(UNNAMED_ROUTER_NICKNAME);
3385  }
3386  } else {
3387  if (!is_legal_nickname(options->Nickname)) {
3388  tor_asprintf(msg,
3389  "Nickname '%s', nicknames must be between 1 and 19 characters "
3390  "inclusive, and must contain only the characters [a-zA-Z0-9].",
3391  options->Nickname);
3392  return -1;
3393  }
3394  }
3395 
3396  if (server_mode(options) && !options->ContactInfo)
3397  log_notice(LD_CONFIG, "Your ContactInfo config option is not set. "
3398  "Please consider setting it, so we can contact you if your server is "
3399  "misconfigured or something else goes wrong.");
3400  const char *ContactInfo = options->ContactInfo;
3401  if (ContactInfo && !string_is_utf8(ContactInfo, strlen(ContactInfo)))
3402  REJECT("ContactInfo config option must be UTF-8.");
3403 
3404  check_network_configuration(server_mode(options));
3405 
3406  /* Special case on first boot if no Log options are given. */
3407  if (!options->Logs && !options->RunAsDaemon && !from_setconf) {
3408  if (quiet_level == 0)
3409  config_line_append(&options->Logs, "Log", "notice stdout");
3410  else if (quiet_level == 1)
3411  config_line_append(&options->Logs, "Log", "warn stdout");
3412  }
3413 
3414  /* Validate the tor_log(s) */
3415  if (options_init_logs(old_options, options, 1)<0)
3416  REJECT("Failed to validate Log options. See logs for details.");
3417 
3418  if (authdir_mode(options)) {
3419  /* confirm that our address isn't broken, so we can complain now */
3420  uint32_t tmp;
3421  if (resolve_my_address(LOG_WARN, options, &tmp, NULL, NULL) < 0)
3422  REJECT("Failed to resolve/guess local address. See logs for details.");
3423  }
3424 
3425  if (server_mode(options) && options->RendConfigLines)
3426  log_warn(LD_CONFIG,
3427  "Tor is currently configured as a relay and a hidden service. "
3428  "That's not very secure: you should probably run your hidden service "
3429  "in a separate Tor process, at least -- see "
3430  "https://trac.torproject.org/8742");
3431 
3432  /* XXXX require that the only port not be DirPort? */
3433  /* XXXX require that at least one port be listened-upon. */
3434  if (n_ports == 0 && !options->RendConfigLines)
3435  log_warn(LD_CONFIG,
3436  "SocksPort, TransPort, NATDPort, DNSPort, and ORPort are all "
3437  "undefined, and there aren't any hidden services configured. "
3438  "Tor will still run, but probably won't do anything.");
3439 
3440  options->TransProxyType_parsed = TPT_DEFAULT;
3441 #ifdef USE_TRANSPARENT
3442  if (options->TransProxyType) {
3443  if (!strcasecmp(options->TransProxyType, "default")) {
3444  options->TransProxyType_parsed = TPT_DEFAULT;
3445  } else if (!strcasecmp(options->TransProxyType, "pf-divert")) {
3446 #if !defined(OpenBSD) && !defined( DARWIN )
3447  /* Later versions of OS X have pf */
3448  REJECT("pf-divert is a OpenBSD-specific "
3449  "and OS X/Darwin-specific feature.");
3450 #else
3451  options->TransProxyType_parsed = TPT_PF_DIVERT;
3452 #endif /* !defined(OpenBSD) && !defined( DARWIN ) */
3453  } else if (!strcasecmp(options->TransProxyType, "tproxy")) {
3454 #if !defined(__linux__)
3455  REJECT("TPROXY is a Linux-specific feature.");
3456 #else
3457  options->TransProxyType_parsed = TPT_TPROXY;
3458 #endif
3459  } else if (!strcasecmp(options->TransProxyType, "ipfw")) {
3460 #ifndef KERNEL_MAY_SUPPORT_IPFW
3461  /* Earlier versions of OS X have ipfw */
3462  REJECT("ipfw is a FreeBSD-specific "
3463  "and OS X/Darwin-specific feature.");
3464 #else
3465  options->TransProxyType_parsed = TPT_IPFW;
3466 #endif /* !defined(KERNEL_MAY_SUPPORT_IPFW) */
3467  } else {
3468  REJECT("Unrecognized value for TransProxyType");
3469  }
3470 
3471  if (strcasecmp(options->TransProxyType, "default") &&
3472  !options->TransPort_set) {
3473  REJECT("Cannot use TransProxyType without any valid TransPort.");
3474  }
3475  }
3476 #else /* !(defined(USE_TRANSPARENT)) */
3477  if (options->TransPort_set)
3478  REJECT("TransPort is disabled in this build.");
3479 #endif /* defined(USE_TRANSPARENT) */
3480 
3481  if (options->TokenBucketRefillInterval <= 0
3482  || options->TokenBucketRefillInterval > 1000) {
3483  REJECT("TokenBucketRefillInterval must be between 1 and 1000 inclusive.");
3484  }
3485 
3486  if (options->ExcludeExitNodes || options->ExcludeNodes) {
3490  }
3491 
3492  if (options->NodeFamilies) {
3493  options->NodeFamilySets = smartlist_new();
3494  for (cl = options->NodeFamilies; cl; cl = cl->next) {
3495  routerset_t *rs = routerset_new();
3496  if (routerset_parse(rs, cl->value, cl->key) == 0) {
3497  smartlist_add(options->NodeFamilySets, rs);
3498  } else {
3499  routerset_free(rs);
3500  }
3501  }
3502  }
3503 
3504  if (options->ExcludeNodes && options->StrictNodes) {
3505  COMPLAIN("You have asked to exclude certain relays from all positions "
3506  "in your circuits. Expect hidden services and other Tor "
3507  "features to be broken in unpredictable ways.");
3508  }
3509 
3510  for (cl = options->RecommendedPackages; cl; cl = cl->next) {
3511  if (! validate_recommended_package_line(cl->value)) {
3512  log_warn(LD_CONFIG, "Invalid RecommendedPackage line %s will be ignored",
3513  escaped(cl->value));
3514  }
3515  }
3516 
3517  if (options->AuthoritativeDir) {
3518  if (!options->ContactInfo && !options->TestingTorNetwork)
3519  REJECT("Authoritative directory servers must set ContactInfo");
3520  if (!options->RecommendedClientVersions)
3521  options->RecommendedClientVersions =
3523  if (!options->RecommendedServerVersions)
3524  options->RecommendedServerVersions =
3526  if (options->VersioningAuthoritativeDir &&
3527  (!options->RecommendedClientVersions ||
3528  !options->RecommendedServerVersions))
3529  REJECT("Versioning authoritative dir servers must set "
3530  "Recommended*Versions.");
3531 
3532 #ifdef HAVE_MODULE_DIRAUTH
3533  char *t;
3534  /* Call these functions to produce warnings only. */
3535  t = format_recommended_version_list(options->RecommendedClientVersions, 1);
3536  tor_free(t);
3537  t = format_recommended_version_list(options->RecommendedServerVersions, 1);
3538  tor_free(t);
3539 #endif
3540 
3541  if (options->UseEntryGuards) {
3542  log_info(LD_CONFIG, "Authoritative directory servers can't set "
3543  "UseEntryGuards. Disabling.");
3544  options->UseEntryGuards = 0;
3545  }
3546  if (!options->DownloadExtraInfo && authdir_mode_v3(options)) {
3547  log_info(LD_CONFIG, "Authoritative directories always try to download "
3548  "extra-info documents. Setting DownloadExtraInfo.");
3549  options->DownloadExtraInfo = 1;
3550  }
3551  if (!(options->BridgeAuthoritativeDir ||
3552  options->V3AuthoritativeDir))
3553  REJECT("AuthoritativeDir is set, but none of "
3554  "(Bridge/V3)AuthoritativeDir is set.");
3555  /* If we have a v3bandwidthsfile and it's broken, complain on startup */
3556  if (options->V3BandwidthsFile && !old_options) {
3558  NULL);
3559  }
3560  /* same for guardfraction file */
3561  if (options->GuardfractionFile && !old_options) {
3563  }
3564  }
3565 
3566  if (options->AuthoritativeDir && !options->DirPort_set)
3567  REJECT("Running as authoritative directory, but no DirPort set.");
3568 
3569  if (options->AuthoritativeDir && !options->ORPort_set)
3570  REJECT("Running as authoritative directory, but no ORPort set.");
3571 
3572  if (options->AuthoritativeDir && options->ClientOnly)
3573  REJECT("Running as authoritative directory, but ClientOnly also set.");
3574 
3575  if (options->FetchDirInfoExtraEarly && !options->FetchDirInfoEarly)
3576  REJECT("FetchDirInfoExtraEarly requires that you also set "
3577  "FetchDirInfoEarly");
3578 
3579  if (options->ConnLimit <= 0) {
3580  tor_asprintf(msg,
3581  "ConnLimit must be greater than 0, but was set to %d",
3582  options->ConnLimit);
3583  return -1;
3584  }
3585 
3586  if (options->PathsNeededToBuildCircuits >= 0.0) {
3587  if (options->PathsNeededToBuildCircuits < 0.25) {
3588  log_warn(LD_CONFIG, "PathsNeededToBuildCircuits is too low. Increasing "
3589  "to 0.25");
3590  options->PathsNeededToBuildCircuits = 0.25;
3591  } else if (options->PathsNeededToBuildCircuits > 0.95) {
3592  log_warn(LD_CONFIG, "PathsNeededToBuildCircuits is too high. Decreasing "
3593  "to 0.95");
3594  options->PathsNeededToBuildCircuits = 0.95;
3595  }
3596  }
3597 
3598  if (options->MaxClientCircuitsPending <= 0 ||
3599  options->MaxClientCircuitsPending > MAX_MAX_CLIENT_CIRCUITS_PENDING) {
3600  tor_asprintf(msg,
3601  "MaxClientCircuitsPending must be between 1 and %d, but "
3602  "was set to %d", MAX_MAX_CLIENT_CIRCUITS_PENDING,
3603  options->MaxClientCircuitsPending);
3604  return -1;
3605  }
3606 
3607  if (validate_ports_csv(options->FirewallPorts, "FirewallPorts", msg) < 0)
3608  return -1;
3609 
3610  if (validate_ports_csv(options->LongLivedPorts, "LongLivedPorts", msg) < 0)
3611  return -1;
3612 
3614  "RejectPlaintextPorts", msg) < 0)
3615  return -1;
3616 
3618  "WarnPlaintextPorts", msg) < 0)
3619  return -1;
3620 
3621  if (options->FascistFirewall && !options->ReachableAddresses) {
3622  if (options->FirewallPorts && smartlist_len(options->FirewallPorts)) {
3623  /* We already have firewall ports set, so migrate them to
3624  * ReachableAddresses, which will set ReachableORAddresses and
3625  * ReachableDirAddresses if they aren't set explicitly. */
3626  smartlist_t *instead = smartlist_new();
3627  config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3628  new_line->key = tor_strdup("ReachableAddresses");
3629  /* If we're configured with the old format, we need to prepend some
3630  * open ports. */
3631  SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
3632  {
3633  int p = atoi(portno);
3634  if (p<0) continue;
3635  smartlist_add_asprintf(instead, "*:%d", p);
3636  });
3637  new_line->value = smartlist_join_strings(instead,",",0,NULL);
3638  /* These have been deprecated since 0.1.1.5-alpha-cvs */
3639  log_notice(LD_CONFIG,
3640  "Converting FascistFirewall and FirewallPorts "
3641  "config options to new format: \"ReachableAddresses %s\"",
3642  new_line->value);
3643  options->ReachableAddresses = new_line;
3644  SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
3645  smartlist_free(instead);
3646  } else {
3647  /* We do not have FirewallPorts set, so add 80 to
3648  * ReachableDirAddresses, and 443 to ReachableORAddresses. */
3649  if (!options->ReachableDirAddresses) {
3650  config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3651  new_line->key = tor_strdup("ReachableDirAddresses");
3652  new_line->value = tor_strdup("*:80");
3653  options->ReachableDirAddresses = new_line;
3654  log_notice(LD_CONFIG, "Converting FascistFirewall config option "
3655  "to new format: \"ReachableDirAddresses *:80\"");
3656  }
3657  if (!options->ReachableORAddresses) {
3658  config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
3659  new_line->key = tor_strdup("ReachableORAddresses");
3660  new_line->value = tor_strdup("*:443");
3661  options->ReachableORAddresses = new_line;
3662  log_notice(LD_CONFIG, "Converting FascistFirewall config option "
3663  "to new format: \"ReachableORAddresses *:443\"");
3664  }
3665  }
3666  }
3667 
3668  if ((options->ReachableAddresses ||
3669  options->ReachableORAddresses ||
3670  options->ReachableDirAddresses ||
3671  options->ClientUseIPv4 == 0) &&
3672  server_mode(options))
3673  REJECT("Servers must be able to freely connect to the rest "
3674  "of the Internet, so they must not set Reachable*Addresses "
3675  "or FascistFirewall or FirewallPorts or ClientUseIPv4 0.");
3676 
3677  if (options->UseBridges &&
3678  server_mode(options))
3679  REJECT("Servers must be able to freely connect to the rest "
3680  "of the Internet, so they must not set UseBridges.");
3681 
3682  /* If both of these are set, we'll end up with funny behavior where we
3683  * demand enough entrynodes be up and running else we won't build
3684  * circuits, yet we never actually use them. */
3685  if (options->UseBridges && options->EntryNodes)
3686  REJECT("You cannot set both UseBridges and EntryNodes.");
3687 
3688  /* If we have UseBridges as 1 and UseEntryGuards as 0, we end up bypassing
3689  * the use of bridges */
3690  if (options->UseBridges && !options->UseEntryGuards)
3691  REJECT("Setting UseBridges requires also setting UseEntryGuards.");
3692 
3693  options->MaxMemInQueues =
3694  compute_real_max_mem_in_queues(options->MaxMemInQueues_raw,
3695  server_mode(options));
3696  options->MaxMemInQueues_low_threshold = (options->MaxMemInQueues / 4) * 3;
3697 
3698  if (!options->SafeLogging ||
3699  !strcasecmp(options->SafeLogging, "0")) {
3700  options->SafeLogging_ = SAFELOG_SCRUB_NONE;
3701  } else if (!strcasecmp(options->SafeLogging, "relay")) {
3702  options->SafeLogging_ = SAFELOG_SCRUB_RELAY;
3703  } else if (!strcasecmp(options->SafeLogging, "1")) {
3704  options->SafeLogging_ = SAFELOG_SCRUB_ALL;
3705  } else {
3706  tor_asprintf(msg,
3707  "Unrecognized value '%s' in SafeLogging",
3708  escaped(options->SafeLogging));
3709  return -1;
3710  }
3711 
3712  if (compute_publishserverdescriptor(options) < 0) {
3713  tor_asprintf(msg, "Unrecognized value in PublishServerDescriptor");
3714  return -1;
3715  }
3716 
3717  if ((options->BridgeRelay
3719  && (options->PublishServerDescriptor_ & V3_DIRINFO)) {
3720  REJECT("Bridges are not supposed to publish router descriptors to the "
3721  "directory authorities. Please correct your "
3722  "PublishServerDescriptor line.");
3723  }
3724 
3725  if (options->BridgeRelay && options->DirPort_set) {
3726  log_warn(LD_CONFIG, "Can't set a DirPort on a bridge relay; disabling "
3727  "DirPort");
3728  config_free_lines(options->DirPort_lines);
3729  options->DirPort_lines = NULL;
3730  options->DirPort_set = 0;
3731  }
3732 
3733  if (server_mode(options) && options->ConnectionPadding != -1) {
3734  REJECT("Relays must use 'auto' for the ConnectionPadding setting.");
3735  }
3736 
3737  if (server_mode(options) && options->ReducedConnectionPadding != 0) {
3738  REJECT("Relays cannot set ReducedConnectionPadding. ");
3739  }
3740 
3741  if (options->BridgeDistribution) {
3742  if (!options->BridgeRelay) {
3743  REJECT("You set BridgeDistribution, but you didn't set BridgeRelay!");
3744  }
3746  REJECT("Invalid BridgeDistribution value.");
3747  }
3748  }
3749 
3750  if (options->MinUptimeHidServDirectoryV2 < 0) {
3751  log_warn(LD_CONFIG, "MinUptimeHidServDirectoryV2 option must be at "
3752  "least 0 seconds. Changing to 0.");
3753  options->MinUptimeHidServDirectoryV2 = 0;
3754  }
3755 
3756  const int min_rendpostperiod =
3757  options->TestingTorNetwork ?
3758  MIN_REND_POST_PERIOD_TESTING : MIN_REND_POST_PERIOD;
3759  if (options->RendPostPeriod < min_rendpostperiod) {
3760  log_warn(LD_CONFIG, "RendPostPeriod option is too short; "
3761  "raising to %d seconds.", min_rendpostperiod);
3762  options->RendPostPeriod = min_rendpostperiod;
3763  }
3764 
3765  if (options->RendPostPeriod > MAX_DIR_PERIOD) {
3766  log_warn(LD_CONFIG, "RendPostPeriod is too large; clipping to %ds.",
3767  MAX_DIR_PERIOD);
3768  options->RendPostPeriod = MAX_DIR_PERIOD;
3769  }
3770 
3771  /* Check the Single Onion Service options */
3772  if (options_validate_single_onion(options, msg) < 0)
3773  return -1;
3774 
3776  // options_t is immutable for new code (the above code is older),
3777  // so just make the user fix the value themselves rather than
3778  // silently keep a shadow value lower than what they asked for.
3779  REJECT("CircuitsAvailableTimeout is too large. Max is 24 hours.");
3780  }
3781 
3782  if (options->EntryNodes && !options->UseEntryGuards) {
3783  REJECT("If EntryNodes is set, UseEntryGuards must be enabled.");
3784  }
3785 
3786  if (!(options->UseEntryGuards) &&
3787  (options->RendConfigLines != NULL) &&
3788  !rend_service_allow_non_anonymous_connection(options)) {
3789  log_warn(LD_CONFIG,
3790  "UseEntryGuards is disabled, but you have configured one or more "
3791  "hidden services on this Tor instance. Your hidden services "
3792  "will be very easy to locate using a well-known attack -- see "
3793  "http://freehaven.net/anonbib/#hs-attack06 for details.");
3794  }
3795 
3796  if (options->NumPrimaryGuards && options->NumEntryGuards &&
3797  options->NumEntryGuards > options->NumPrimaryGuards) {
3798  REJECT("NumEntryGuards must not be greater than NumPrimaryGuards.");
3799  }
3800 
3801  if (options->EntryNodes &&
3802  routerset_is_list(options->EntryNodes) &&
3803  (routerset_len(options->EntryNodes) == 1) &&
3804  (options->RendConfigLines != NULL)) {
3805  tor_asprintf(msg,
3806  "You have one single EntryNodes and at least one hidden service "
3807  "configured. This is bad because it's very easy to locate your "
3808  "entry guard which can then lead to the deanonymization of your "
3809  "hidden service -- for more details, see "
3810  "https://trac.torproject.org/projects/tor/ticket/14917. "
3811  "For this reason, the use of one EntryNodes with an hidden "
3812  "service is prohibited until a better solution is found.");
3813  return -1;
3814  }
3815 
3816  /* Inform the hidden service operator that pinning EntryNodes can possibly
3817  * be harmful for the service anonymity. */
3818  if (options->EntryNodes &&
3819  routerset_is_list(options->EntryNodes) &&
3820  (options->RendConfigLines != NULL)) {
3821  log_warn(LD_CONFIG,
3822  "EntryNodes is set with multiple entries and at least one "
3823  "hidden service is configured. Pinning entry nodes can possibly "
3824  "be harmful to the service anonymity. Because of this, we "
3825  "recommend you either don't do that or make sure you know what "
3826  "you are doing. For more details, please look at "
3827  "https://trac.torproject.org/projects/tor/ticket/21155.");
3828  }
3829 
3830  /* Single Onion Services: non-anonymous hidden services */
3831  if (rend_service_non_anonymous_mode_enabled(options)) {
3832  log_warn(LD_CONFIG,
3833  "HiddenServiceNonAnonymousMode is set. Every hidden service on "
3834  "this tor instance is NON-ANONYMOUS. If "
3835  "the HiddenServiceNonAnonymousMode option is changed, Tor will "
3836  "refuse to launch hidden services from the same directories, to "
3837  "protect your anonymity against config errors. This setting is "
3838  "for experimental use only.");
3839  }
3840 
3841  if (!options->LearnCircuitBuildTimeout && options->CircuitBuildTimeout &&
3843  log_warn(LD_CONFIG,
3844  "CircuitBuildTimeout is shorter (%d seconds) than the recommended "
3845  "minimum (%d seconds), and LearnCircuitBuildTimeout is disabled. "
3846  "If tor isn't working, raise this value or enable "
3847  "LearnCircuitBuildTimeout.",
3848  options->CircuitBuildTimeout,
3850  } else if (!options->LearnCircuitBuildTimeout &&
3851  !options->CircuitBuildTimeout) {
3852  int severity = LOG_NOTICE;
3853  /* Be a little quieter if we've deliberately disabled
3854  * LearnCircuitBuildTimeout. */
3855  if (circuit_build_times_disabled_(options, 1)) {
3856  severity = LOG_INFO;
3857  }
3858  log_fn(severity, LD_CONFIG, "You disabled LearnCircuitBuildTimeout, but "
3859  "didn't specify a CircuitBuildTimeout. I'll pick a plausible "
3860  "default.");
3861  }
3862 
3863  if (options->DormantClientTimeout < 10*60 && !options->TestingTorNetwork) {
3864  REJECT("DormantClientTimeout is too low. It must be at least 10 minutes.");
3865  }
3866 
3867  if (options->PathBiasNoticeRate > 1.0) {
3868  tor_asprintf(msg,
3869  "PathBiasNoticeRate is too high. "
3870  "It must be between 0 and 1.0");
3871  return -1;
3872  }
3873  if (options->PathBiasWarnRate > 1.0) {
3874  tor_asprintf(msg,
3875  "PathBiasWarnRate is too high. "
3876  "It must be between 0 and 1.0");
3877  return -1;
3878  }
3879  if (options->PathBiasExtremeRate > 1.0) {
3880  tor_asprintf(msg,
3881  "PathBiasExtremeRate is too high. "
3882  "It must be between 0 and 1.0");
3883  return -1;
3884  }
3885  if (options->PathBiasNoticeUseRate > 1.0) {
3886  tor_asprintf(msg,
3887  "PathBiasNoticeUseRate is too high. "
3888  "It must be between 0 and 1.0");
3889  return -1;
3890  }
3891  if (options->PathBiasExtremeUseRate > 1.0) {
3892  tor_asprintf(msg,
3893  "PathBiasExtremeUseRate is too high. "
3894  "It must be between 0 and 1.0");
3895  return -1;
3896  }
3897 
3899  log_warn(LD_CONFIG, "MaxCircuitDirtiness option is too short; "
3900  "raising to %d seconds.", MIN_MAX_CIRCUIT_DIRTINESS);
3902  }
3903 
3905  log_warn(LD_CONFIG, "MaxCircuitDirtiness option is too high; "
3906  "setting to %d days.", MAX_MAX_CIRCUIT_DIRTINESS/86400);
3908  }
3909 
3910  if (options->CircuitStreamTimeout &&
3912  log_warn(LD_CONFIG, "CircuitStreamTimeout option is too short; "
3913  "raising to %d seconds.", MIN_CIRCUIT_STREAM_TIMEOUT);
3915  }
3916 
3917  if (options->HeartbeatPeriod &&
3919  !options->TestingTorNetwork) {
3920  log_warn(LD_CONFIG, "HeartbeatPeriod option is too short; "
3921  "raising to %d seconds.", MIN_HEARTBEAT_PERIOD);
3923  }
3924 
3925  if (options->KeepalivePeriod < 1)
3926  REJECT("KeepalivePeriod option must be positive.");
3927 
3928  if (ensure_bandwidth_cap(&options->BandwidthRate,
3929  "BandwidthRate", msg) < 0)
3930  return -1;
3931  if (ensure_bandwidth_cap(&options->BandwidthBurst,
3932  "BandwidthBurst", msg) < 0)
3933  return -1;
3935  "MaxAdvertisedBandwidth", msg) < 0)
3936  return -1;
3938  "RelayBandwidthRate", msg) < 0)
3939  return -1;
3941  "RelayBandwidthBurst", msg) < 0)
3942  return -1;
3943  if (ensure_bandwidth_cap(&options->PerConnBWRate,
3944  "PerConnBWRate", msg) < 0)
3945  return -1;
3946  if (ensure_bandwidth_cap(&options->PerConnBWBurst,
3947  "PerConnBWBurst", msg) < 0)
3948  return -1;
3950  "AuthDirFastGuarantee", msg) < 0)
3951  return -1;
3953  "AuthDirGuardBWGuarantee", msg) < 0)
3954  return -1;
3955 
3956  if (options->RelayBandwidthRate && !options->RelayBandwidthBurst)
3957  options->RelayBandwidthBurst = options->RelayBandwidthRate;
3958  if (options->RelayBandwidthBurst && !options->RelayBandwidthRate)
3959  options->RelayBandwidthRate = options->RelayBandwidthBurst;
3960 
3961  if (server_mode(options)) {
3962  const unsigned required_min_bw =
3963  public_server_mode(options) ?
3964  RELAY_REQUIRED_MIN_BANDWIDTH : BRIDGE_REQUIRED_MIN_BANDWIDTH;
3965  const char * const optbridge =
3966  public_server_mode(options) ? "" : "bridge ";
3967  if (options->BandwidthRate < required_min_bw) {
3968  tor_asprintf(msg,
3969  "BandwidthRate is set to %d bytes/second. "
3970  "For %sservers, it must be at least %u.",
3971  (int)options->BandwidthRate, optbridge,
3972  required_min_bw);
3973  return -1;
3974  } else if (options->MaxAdvertisedBandwidth <
3975  required_min_bw/2) {
3976  tor_asprintf(msg,
3977  "MaxAdvertisedBandwidth is set to %d bytes/second. "
3978  "For %sservers, it must be at least %u.",
3979  (int)options->MaxAdvertisedBandwidth, optbridge,
3980  required_min_bw/2);
3981  return -1;
3982  }
3983  if (options->RelayBandwidthRate &&
3984  options->RelayBandwidthRate < required_min_bw) {
3985  tor_asprintf(msg,
3986  "RelayBandwidthRate is set to %d bytes/second. "
3987  "For %sservers, it must be at least %u.",
3988  (int)options->RelayBandwidthRate, optbridge,
3989  required_min_bw);
3990  return -1;
3991  }
3992  }
3993 
3994  if (options->RelayBandwidthRate > options->RelayBandwidthBurst)
3995  REJECT("RelayBandwidthBurst must be at least equal "
3996  "to RelayBandwidthRate.");
3997 
3998  if (options->BandwidthRate > options->BandwidthBurst)
3999  REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
4000 
4001  /* if they set relaybandwidth* really high but left bandwidth*
4002  * at the default, raise the defaults. */
4003  if (options->RelayBandwidthRate > options->BandwidthRate)
4004  options->BandwidthRate = options->RelayBandwidthRate;
4005  if (options->RelayBandwidthBurst > options->BandwidthBurst)
4006  options->BandwidthBurst = options->RelayBandwidthBurst;
4007 
4008  if (accounting_parse_options(options, 1)<0)
4009  REJECT("Failed to parse accounting options. See logs for details.");
4010 
4011  if (options->AccountingMax) {
4012  if (options->RendConfigLines && server_mode(options)) {
4013  log_warn(LD_CONFIG, "Using accounting with a hidden service and an "
4014  "ORPort is risky: your hidden service(s) and your public "
4015  "address will all turn off at the same time, which may alert "
4016  "observers that they are being run by the same party.");
4017  } else if (config_count_key(options->RendConfigLines,
4018  "HiddenServiceDir") > 1) {
4019  log_warn(LD_CONFIG, "Using accounting with multiple hidden services is "
4020  "risky: they will all turn off at the same time, which may "
4021  "alert observers that they are being run by the same party.");
4022  }
4023  }
4024 
4025  options->AccountingRule = ACCT_MAX;
4026  if (options->AccountingRule_option) {
4027  if (!strcmp(options->AccountingRule_option, "sum"))
4028  options->AccountingRule = ACCT_SUM;
4029  else if (!strcmp(options->AccountingRule_option, "max"))
4030  options->AccountingRule = ACCT_MAX;
4031  else if (!strcmp(options->AccountingRule_option, "in"))
4032  options->AccountingRule = ACCT_IN;
4033  else if (!strcmp(options->AccountingRule_option, "out"))
4034  options->AccountingRule = ACCT_OUT;
4035  else
4036  REJECT("AccountingRule must be 'sum', 'max', 'in', or 'out'");
4037  }
4038 
4039  if (options->DirPort_set && !options->DirCache) {
4040  REJECT("DirPort configured but DirCache disabled. DirPort requires "
4041  "DirCache.");
4042  }
4043 
4044  if (options->BridgeRelay && !options->DirCache) {
4045  REJECT("We're a bridge but DirCache is disabled. BridgeRelay requires "
4046  "DirCache.");
4047  }
4048 
4049  if (server_mode(options)) {
4050  char *dircache_msg = NULL;
4051  if (have_enough_mem_for_dircache(options, 0, &dircache_msg)) {
4052  log_warn(LD_CONFIG, "%s", dircache_msg);
4053  tor_free(dircache_msg);
4054  }
4055  }
4056 
4057  if (options->HTTPProxy) { /* parse it now */
4058  if (tor_addr_port_lookup(options->HTTPProxy,
4059  &options->HTTPProxyAddr, &options->HTTPProxyPort) < 0)
4060  REJECT("HTTPProxy failed to parse or resolve. Please fix.");
4061  if (options->HTTPProxyPort == 0) { /* give it a default */
4062  options->HTTPProxyPort = 80;
4063  }
4064  }
4065 
4066  if (options->HTTPProxyAuthenticator) {
4067  if (strlen(options->HTTPProxyAuthenticator) >= 512)
4068  REJECT("HTTPProxyAuthenticator is too long (>= 512 chars).");
4069  }
4070 
4071  if (options->HTTPSProxy) { /* parse it now */
4072  if (tor_addr_port_lookup(options->HTTPSProxy,
4073  &options->HTTPSProxyAddr, &options->HTTPSProxyPort) <0)
4074  REJECT("HTTPSProxy failed to parse or resolve. Please fix.");
4075  if (options->HTTPSProxyPort == 0) { /* give it a default */
4076  options->HTTPSProxyPort = 443;
4077  }
4078  }
4079 
4080  if (options->HTTPSProxyAuthenticator) {
4081  if (strlen(options->HTTPSProxyAuthenticator) >= 512)
4082  REJECT("HTTPSProxyAuthenticator is too long (>= 512 chars).");
4083  }
4084 
4085  if (options->Socks4Proxy) { /* parse it now */
4086  if (tor_addr_port_lookup(options->Socks4Proxy,
4087  &options->Socks4ProxyAddr,
4088  &options->Socks4ProxyPort) <0)
4089  REJECT("Socks4Proxy failed to parse or resolve. Please fix.");
4090  if (options->Socks4ProxyPort == 0) { /* give it a default */
4091  options->Socks4ProxyPort = 1080;
4092  }
4093  }
4094 
4095  if (options->Socks5Proxy) { /* parse it now */
4096  if (tor_addr_port_lookup(options->Socks5Proxy,
4097  &options->Socks5ProxyAddr,
4098  &options->Socks5ProxyPort) <0)
4099  REJECT("Socks5Proxy failed to parse or resolve. Please fix.");
4100  if (options->Socks5ProxyPort == 0) { /* give it a default */
4101  options->Socks5ProxyPort = 1080;
4102  }
4103  }
4104 
4105  /* Check if more than one exclusive proxy type has been enabled. */
4106  if (!!options->Socks4Proxy + !!options->Socks5Proxy +
4107  !!options->HTTPSProxy > 1)
4108  REJECT("You have configured more than one proxy type. "
4109  "(Socks4Proxy|Socks5Proxy|HTTPSProxy)");
4110 
4111  /* Check if the proxies will give surprising behavior. */
4112  if (options->HTTPProxy && !(options->Socks4Proxy ||
4113  options->Socks5Proxy ||
4114  options->HTTPSProxy)) {
4115  log_warn(LD_CONFIG, "HTTPProxy configured, but no SOCKS proxy or "
4116  "HTTPS proxy configured. Watch out: this configuration will "
4117  "proxy unencrypted directory connections only.");
4118  }
4119 
4120  if (options->Socks5ProxyUsername) {
4121  size_t len;
4122 
4123  len = strlen(options->Socks5ProxyUsername);
4124  if (len < 1 || len > MAX_SOCKS5_AUTH_FIELD_SIZE)
4125  REJECT("Socks5ProxyUsername must be between 1 and 255 characters.");
4126 
4127  if (!options->Socks5ProxyPassword)
4128  REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
4129 
4130  len = strlen(options->Socks5ProxyPassword);
4131  if (len < 1 || len > MAX_SOCKS5_AUTH_FIELD_SIZE)
4132  REJECT("Socks5ProxyPassword must be between 1 and 255 characters.");
4133  } else if (options->Socks5ProxyPassword)
4134  REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
4135 
4136  if (options->HashedControlPassword) {
4138  if (!sl) {
4139  REJECT("Bad HashedControlPassword: wrong length or bad encoding");
4140  } else {
4141  SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
4142  smartlist_free(sl);
4143  }
4144  }
4145 
4146  if (options->HashedControlSessionPassword) {
4148  options->HashedControlSessionPassword);
4149  if (!sl) {
4150  REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
4151  } else {
4152  SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
4153  smartlist_free(sl);
4154  }
4155  }
4156 
4157  if (options->OwningControllerProcess) {
4158  const char *validate_pspec_msg = NULL;
4160  &validate_pspec_msg)) {
4161  tor_asprintf(msg, "Bad OwningControllerProcess: %s",
4162  validate_pspec_msg);
4163  return -1;
4164  }
4165  }
4166 
4167  if ((options->ControlPort_set || world_writable_control_socket) &&
4168  !options->HashedControlPassword &&
4169  !options->HashedControlSessionPassword &&
4170  !options->CookieAuthentication) {
4171  log_warn(LD_CONFIG, "Control%s is %s, but no authentication method "
4172  "has been configured. This means that any program on your "
4173  "computer can reconfigure your Tor. That's bad! You should "
4174  "upgrade your Tor controller as soon as possible.",
4175  options->ControlPort_set ? "Port" : "Socket",
4176  options->ControlPort_set ? "open" : "world writable");
4177  }
4178 
4179  if (options->CookieAuthFileGroupReadable && !options->CookieAuthFile) {
4180  log_warn(LD_CONFIG, "CookieAuthFileGroupReadable is set, but will have "
4181  "no effect: you must specify an explicit CookieAuthFile to "
4182  "have it group-readable.");
4183  }
4184 
4185  if (options->MyFamily_lines && options->BridgeRelay) {
4186  log_warn(LD_CONFIG, "Listing a family for a bridge relay is not "
4187  "supported: it can reveal bridge fingerprints to censors. "
4188  "You should also make sure you aren't listing this bridge's "
4189  "fingerprint in any other MyFamily.");
4190  }
4191  if (options->MyFamily_lines && !options->ContactInfo) {
4192  log_warn(LD_CONFIG, "MyFamily is set but ContactInfo is not configured. "
4193  "ContactInfo should always be set when MyFamily option is too.");
4194  }
4195  if (normalize_nickname_list(&options->MyFamily,
4196  options->MyFamily_lines, "MyFamily", msg))
4197  return -1;
4198  for (cl = options->NodeFamilies; cl; cl = cl->next) {
4199  routerset_t *rs = routerset_new();
4200  if (routerset_parse(rs, cl->value, cl->key)) {
4201  routerset_free(rs);
4202  return -1;
4203  }
4204  routerset_free(rs);
4205  }
4206 
4207  if (validate_addr_policies(options, msg) < 0)
4208  return -1;
4209 
4210  /* If FallbackDir is set, we don't UseDefaultFallbackDirs */
4211  if (options->UseDefaultFallbackDirs && options->FallbackDir) {
4212  log_info(LD_CONFIG, "You have set UseDefaultFallbackDirs 1 and "
4213  "FallbackDir(s). Ignoring UseDefaultFallbackDirs, and "
4214  "using the FallbackDir(s) you have set.");
4215  }
4216 
4217  if (validate_dir_servers(options, old_options) < 0)
4218  REJECT("Directory authority/fallback line did not parse. See logs "
4219  "for details.");
4220 
4221  if (options->UseBridges && !options->Bridges)
4222  REJECT("If you set UseBridges, you must specify at least one bridge.");
4223 
4224  for (cl = options->Bridges; cl; cl = cl->next) {
4225  bridge_line_t *bridge_line = parse_bridge_line(cl->value);
4226  if (!bridge_line)
4227  REJECT("Bridge line did not parse. See logs for details.");
4228  bridge_line_free(bridge_line);
4229  }
4230 
4231  for (cl = options->ClientTransportPlugin; cl; cl = cl->next) {
4232  if (parse_transport_line(options, cl->value, 1, 0) < 0)
4233  REJECT("Invalid client transport line. See logs for details.");
4234  }
4235 
4236  for (cl = options->ServerTransportPlugin; cl; cl = cl->next) {
4237  if (parse_transport_line(options, cl->value, 1, 1) < 0)
4238  REJECT("Invalid server transport line. See logs for details.");
4239  }
4240 
4241  if (options->ServerTransportPlugin && !server_mode(options)) {
4242  log_notice(LD_GENERAL, "Tor is not configured as a relay but you specified"
4243  " a ServerTransportPlugin line (%s). The ServerTransportPlugin "
4244  "line will be ignored.",
4245  escaped(options->ServerTransportPlugin->value));
4246  }
4247 
4248  for (cl = options->ServerTransportListenAddr; cl; cl = cl->next) {
4252  char *bindaddr = get_bindaddr_from_transport_listen_line(cl->value, NULL);
4253  if (!bindaddr)
4254  REJECT("ServerTransportListenAddr did not parse. See logs for details.");
4255  tor_free(bindaddr);
4256  }
4257 
4258  if (options->ServerTransportListenAddr && !options->ServerTransportPlugin) {
4259  log_notice(LD_GENERAL, "You need at least a single managed-proxy to "
4260  "specify a transport listen address. The "
4261  "ServerTransportListenAddr line will be ignored.");
4262  }
4263 
4264  for (cl = options->ServerTransportOptions; cl; cl = cl->next) {
4268  smartlist_t *options_sl =
4269  get_options_from_transport_options_line(cl->value, NULL);
4270  if (!options_sl)
4271  REJECT("ServerTransportOptions did not parse. See logs for details.");
4272 
4273  SMARTLIST_FOREACH(options_sl, char *, cp, tor_free(cp));
4274  smartlist_free(options_sl);
4275  }
4276 
4277  if (options->ConstrainedSockets) {
4278  /* If the user wants to constrain socket buffer use, make sure the desired
4279  * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
4280  if (options->ConstrainedSockSize < MIN_CONSTRAINED_TCP_BUFFER ||
4281  options->ConstrainedSockSize > MAX_CONSTRAINED_TCP_BUFFER ||
4282  options->ConstrainedSockSize % 1024) {
4283  tor_asprintf(msg,
4284  "ConstrainedSockSize is invalid. Must be a value between %d and %d "
4285  "in 1024 byte increments.",
4286  MIN_CONSTRAINED_TCP_BUFFER, MAX_CONSTRAINED_TCP_BUFFER);
4287  return -1;
4288  }
4289  if (options->DirPort_set) {
4290  /* Providing cached directory entries while system TCP buffers are scarce
4291  * will exacerbate the socket errors. Suggest that this be disabled. */
4292  COMPLAIN("You have requested constrained socket buffers while also "
4293  "serving directory entries via DirPort. It is strongly "
4294  "suggested that you disable serving directory requests when "
4295  "system TCP buffer resources are scarce.");
4296  }
4297  }
4298 
4299  if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
4300  options->V3AuthVotingInterval/2) {
4301  /*
4302  This doesn't work, but it seems like it should:
4303  what code is preventing the interval being less than twice the lead-up?
4304  if (options->TestingTorNetwork) {
4305  if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
4306  options->V3AuthVotingInterval) {
4307  REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than "
4308  "V3AuthVotingInterval");
4309  } else {
4310  COMPLAIN("V3AuthVoteDelay plus V3AuthDistDelay is more than half "
4311  "V3AuthVotingInterval. This may lead to "
4312  "consensus instability, particularly if clocks drift.");
4313  }
4314  } else {
4315  */
4316  REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
4317  "V3AuthVotingInterval");
4318  /*
4319  }
4320  */
4321  }
4322 
4323  if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS) {
4324  if (options->TestingTorNetwork) {
4325  if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS_TESTING) {
4326  REJECT("V3AuthVoteDelay is way too low.");
4327  } else {
4328  COMPLAIN("V3AuthVoteDelay is very low. "
4329  "This may lead to failure to vote for a consensus.");
4330  }
4331  } else {
4332  REJECT("V3AuthVoteDelay is way too low.");
4333  }
4334  }
4335 
4336  if (options->V3AuthDistDelay < MIN_DIST_SECONDS) {
4337  if (options->TestingTorNetwork) {
4338  if (options->V3AuthDistDelay < MIN_DIST_SECONDS_TESTING) {
4339  REJECT("V3AuthDistDelay is way too low.");
4340  } else {
4341  COMPLAIN("V3AuthDistDelay is very low. "
4342  "This may lead to missing votes in a consensus.");
4343  }
4344  } else {
4345  REJECT("V3AuthDistDelay is way too low.");
4346  }
4347  }
4348 
4349  if (options->V3AuthNIntervalsValid < 2)
4350  REJECT("V3AuthNIntervalsValid must be at least 2.");
4351 
4352  if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL) {
4353  if (options->TestingTorNetwork) {
4355  REJECT("V3AuthVotingInterval is insanely low.");
4356  } else {
4357  COMPLAIN("V3AuthVotingInterval is very low. "
4358  "This may lead to failure to synchronise for a consensus.");
4359  }
4360  } else {
4361  REJECT("V3AuthVotingInterval is insanely low.");
4362  }
4363  } else if (options->V3AuthVotingInterval > 24*60*60) {
4364  REJECT("V3AuthVotingInterval is insanely high.");
4365  } else if (((24*60*60) % options->V3AuthVotingInterval) != 0) {
4366  COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
4367  }
4368 
4369  if (hs_config_service_all(options, 1) < 0)
4370  REJECT("Failed to configure rendezvous options. See logs for details.");
4371 
4372  /* Parse client-side authorization for hidden services. */
4373  if (hs_config_client_auth_all(options, 1) < 0)
4374  REJECT("Failed to configure client authorization for hidden services. "
4375  "See logs for details.");
4376 
4378  AF_INET, 1, msg)<0)
4379  return -1;
4381  AF_INET6, 1, msg)<0)
4382  return -1;
4383 
4384  if (options->TestingTorNetwork &&
4385  !(options->DirAuthorities ||
4386  (options->AlternateDirAuthority &&
4387  options->AlternateBridgeAuthority))) {
4388  REJECT("TestingTorNetwork may only be configured in combination with "
4389  "a non-default set of DirAuthority or both of "
4390  "AlternateDirAuthority and AlternateBridgeAuthority configured.");
4391  }
4392 
4393 #define CHECK_DEFAULT(arg) \
4394  STMT_BEGIN \
4395  if (!options->TestingTorNetwork && \
4396  !options->UsingTestNetworkDefaults_ && \
4397  !config_is_same(&options_format,options, \
4398  default_options,#arg)) { \
4399  REJECT(#arg " may only be changed in testing Tor " \
4400  "networks!"); \
4401  } STMT_END
4402  CHECK_DEFAULT(TestingV3AuthInitialVotingInterval);
4403  CHECK_DEFAULT(TestingV3AuthInitialVoteDelay);
4404  CHECK_DEFAULT(TestingV3AuthInitialDistDelay);
4405  CHECK_DEFAULT(TestingV3AuthVotingStartOffset);
4406  CHECK_DEFAULT(TestingAuthDirTimeToLearnReachability);
4407  CHECK_DEFAULT(TestingEstimatedDescriptorPropagationTime);
4408  CHECK_DEFAULT(TestingServerDownloadInitialDelay);
4409  CHECK_DEFAULT(TestingClientDownloadInitialDelay);
4410  CHECK_DEFAULT(TestingServerConsensusDownloadInitialDelay);
4411  CHECK_DEFAULT(TestingClientConsensusDownloadInitialDelay);
4412  CHECK_DEFAULT(TestingBridgeDownloadInitialDelay);
4413  CHECK_DEFAULT(TestingBridgeBootstrapDownloadInitialDelay);
4414  CHECK_DEFAULT(TestingClientMaxIntervalWithoutRequest);
4415  CHECK_DEFAULT(TestingDirConnectionMaxStall);
4416  CHECK_DEFAULT(TestingAuthKeyLifetime);
4417  CHECK_DEFAULT(TestingLinkCertLifetime);
4418  CHECK_DEFAULT(TestingSigningKeySlop);
4419  CHECK_DEFAULT(TestingAuthKeySlop);
4420  CHECK_DEFAULT(TestingLinkKeySlop);
4421 #undef CHECK_DEFAULT
4422 
4423  if (!options->ClientDNSRejectInternalAddresses &&
4424  !(options->DirAuthorities ||
4425  (options->AlternateDirAuthority && options->AlternateBridgeAuthority)))
4426  REJECT("ClientDNSRejectInternalAddresses used for default network.");
4427  if (options->SigningKeyLifetime < options->TestingSigningKeySlop*2)
4428  REJECT("SigningKeyLifetime is too short.");
4429  if (options->TestingLinkCertLifetime < options->TestingAuthKeySlop*2)
4430  REJECT("LinkCertLifetime is too short.");
4431  if (options->TestingAuthKeyLifetime < options->TestingLinkKeySlop*2)
4432  REJECT("TestingAuthKeyLifetime is too short.");
4433 
4435  < MIN_VOTE_INTERVAL_TESTING_INITIAL) {
4436  REJECT("TestingV3AuthInitialVotingInterval is insanely low.");
4437  } else if (((30*60) % options->TestingV3AuthInitialVotingInterval) != 0) {
4438  REJECT("TestingV3AuthInitialVotingInterval does not divide evenly into "
4439  "30 minutes.");
4440  }
4441 
4443  REJECT("TestingV3AuthInitialVoteDelay is way too low.");
4444  }
4445 
4447  REJECT("TestingV3AuthInitialDistDelay is way too low.");
4448  }
4449 
4450  if (options->TestingV3AuthInitialVoteDelay +
4451  options->TestingV3AuthInitialDistDelay >=
4453  REJECT("TestingV3AuthInitialVoteDelay plus TestingV3AuthInitialDistDelay "
4454  "must be less than TestingV3AuthInitialVotingInterval");
4455  }
4456 
4457  if (options->TestingV3AuthVotingStartOffset >
4459  options->V3AuthVotingInterval)) {
4460  REJECT("TestingV3AuthVotingStartOffset is higher than the voting "
4461  "interval.");
4462  } else if (options->TestingV3AuthVotingStartOffset < 0) {
4463  REJECT("TestingV3AuthVotingStartOffset must be non-negative.");
4464  }
4465 
4466  if (options->TestingAuthDirTimeToLearnReachability < 0) {
4467  REJECT("TestingAuthDirTimeToLearnReachability must be non-negative.");
4468  } else if (options->TestingAuthDirTimeToLearnReachability > 2*60*60) {
4469  COMPLAIN("TestingAuthDirTimeToLearnReachability is insanely high.");
4470  }
4471 
4472  if (options->TestingEstimatedDescriptorPropagationTime < 0) {
4473  REJECT("TestingEstimatedDescriptorPropagationTime must be non-negative.");
4474  } else if (options->TestingEstimatedDescriptorPropagationTime > 60*60) {
4475  COMPLAIN("TestingEstimatedDescriptorPropagationTime is insanely high.");
4476  }
4477 
4478  if (options->TestingClientMaxIntervalWithoutRequest < 1) {
4479  REJECT("TestingClientMaxIntervalWithoutRequest is way too low.");
4480  } else if (options->TestingClientMaxIntervalWithoutRequest > 3600) {
4481  COMPLAIN("TestingClientMaxIntervalWithoutRequest is insanely high.");
4482  }
4483 
4484  if (options->TestingDirConnectionMaxStall < 5) {
4485  REJECT("TestingDirConnectionMaxStall is way too low.");
4486  } else if (options->TestingDirConnectionMaxStall > 3600) {
4487  COMPLAIN("TestingDirConnectionMaxStall is insanely high.");
4488  }
4489 
4490  if (options->ClientBootstrapConsensusMaxInProgressTries < 1) {
4491  REJECT("ClientBootstrapConsensusMaxInProgressTries must be greater "
4492  "than 0.");
4493  } else if (options->ClientBootstrapConsensusMaxInProgressTries
4494  > 100) {
4495  COMPLAIN("ClientBootstrapConsensusMaxInProgressTries is insanely "
4496  "high.");
4497  }
4498 
4499  if (options->TestingEnableConnBwEvent &&
4500  !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
4501  REJECT("TestingEnableConnBwEvent may only be changed in testing "
4502  "Tor networks!");
4503  }
4504 
4505  if (options->TestingEnableCellStatsEvent &&
4506  !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
4507  REJECT("TestingEnableCellStatsEvent may only be changed in testing "
4508  "Tor networks!");
4509  }
4510 
4511  if (options->TestingTorNetwork) {
4512  log_warn(LD_CONFIG, "TestingTorNetwork is set. This will make your node "
4513  "almost unusable in the public Tor network, and is "
4514  "therefore only advised if you are building a "
4515  "testing Tor network!");
4516  }
4517 
4518  if (options->AccelName && !options->HardwareAccel)
4519  options->HardwareAccel = 1;
4520  if (options->AccelDir && !options->AccelName)
4521  REJECT("Can't use hardware crypto accelerator dir without engine name.");
4522 
4523  if (options->PublishServerDescriptor)
4524  SMARTLIST_FOREACH(options->PublishServerDescriptor, const char *, pubdes, {
4525  if (!strcmp(pubdes, "1") || !strcmp(pubdes, "0"))
4526  if (smartlist_len(options->PublishServerDescriptor) > 1) {
4527  COMPLAIN("You have passed a list of multiple arguments to the "
4528  "PublishServerDescriptor option that includes 0 or 1. "
4529  "0 or 1 should only be used as the sole argument. "
4530  "This configuration will be rejected in a future release.");
4531  break;
4532  }
4533  });
4534 
4535  if (options->BridgeRelay == 1 && ! options->ORPort_set)
4536  REJECT("BridgeRelay is 1, ORPort is not set. This is an invalid "
4537  "combination.");
4538 
4539  if (options_validate_scheduler(options, msg) < 0) {
4540  return -1;
4541  }
4542 
4543  return 0;
4544 }
4545 
4546 #undef REJECT
4547 #undef COMPLAIN
4548 
4549 /* Given the value that the user has set for MaxMemInQueues, compute the
4550  * actual maximum value. We clip this value if it's too low, and autodetect
4551  * it if it's set to 0. */
4552 STATIC uint64_t
4553 compute_real_max_mem_in_queues(const uint64_t val, int log_guess)
4554 {
4555  uint64_t result;
4556 
4557  if (val == 0) {
4558 #define ONE_GIGABYTE (UINT64_C(1) << 30)
4559 #define ONE_MEGABYTE (UINT64_C(1) << 20)
4560  /* The user didn't pick a memory limit. Choose a very large one
4561  * that is still smaller than the system memory */
4562  static int notice_sent = 0;
4563  size_t ram = 0;
4564  if (get_total_system_memory(&ram) < 0) {
4565  /* We couldn't determine our total system memory! */
4566 #if SIZEOF_VOID_P >= 8
4567  /* 64-bit system. Let's hope for 8 GB. */
4568  result = 8 * ONE_GIGABYTE;
4569 #else
4570  /* (presumably) 32-bit system. Let's hope for 1 GB. */
4571  result = ONE_GIGABYTE;
4572 #endif /* SIZEOF_VOID_P >= 8 */
4573  } else {
4574  /* We detected the amount of memory available. */
4575  uint64_t avail = 0;
4576 
4577 #if SIZEOF_SIZE_T > 4
4578 /* On a 64-bit platform, we consider 8GB "very large". */
4579 #define RAM_IS_VERY_LARGE(x) ((x) >= (8 * ONE_GIGABYTE))
4580 #else
4581 /* On a 32-bit platform, we can't have 8GB of ram. */
4582 #define RAM_IS_VERY_LARGE(x) (0)
4583 #endif
4584 
4585  if (RAM_IS_VERY_LARGE(ram)) {
4586  /* If we have 8 GB, or more, RAM available, we set the MaxMemInQueues
4587  * to 0.4 * RAM. The idea behind this value is that the amount of RAM
4588  * is more than enough for a single relay and should allow the relay
4589  * operator to run two relays if they have additional bandwidth
4590  * available.
4591  */
4592  avail = (ram / 5) * 2;
4593  } else {
4594  /* If we have less than 8 GB of RAM available, we use the "old" default
4595  * for MaxMemInQueues of 0.75 * RAM.
4596  */
4597  avail = (ram / 4) * 3;
4598  }
4599 
4600  /* Make sure it's in range from 0.25 GB to 8 GB for 64-bit and 0.25 to 2
4601  * GB for 32-bit. */
4602  if (avail > MAX_DEFAULT_MEMORY_QUEUE_SIZE) {
4603  /* If you want to use more than this much RAM, you need to configure
4604  it yourself */
4606  } else if (avail < ONE_GIGABYTE / 4) {
4607  result = ONE_GIGABYTE / 4;
4608  } else {
4609  result = avail;
4610  }
4611  }
4612  if (log_guess && ! notice_sent) {
4613  log_notice(LD_CONFIG, "%sMaxMemInQueues is set to %"PRIu64" MB. "
4614  "You can override this by setting MaxMemInQueues by hand.",
4615  ram ? "Based on detected system memory, " : "",
4616  (result / ONE_MEGABYTE));
4617  notice_sent = 1;
4618  }
4619  return result;
4620  } else if (val < ONE_GIGABYTE / 4) {
4621  log_warn(LD_CONFIG, "MaxMemInQueues must be at least 256 MB for now. "
4622  "Ideally, have it as large as you can afford.");
4623  return ONE_GIGABYTE / 4;
4624  } else {
4625  /* The value was fine all along */
4626  return val;
4627  }
4628 }
4629 
4630 /* If we have less than 300 MB suggest disabling dircache */
4631 #define DIRCACHE_MIN_MEM_MB 300
4632 #define DIRCACHE_MIN_MEM_BYTES (DIRCACHE_MIN_MEM_MB*ONE_MEGABYTE)
4633 #define STRINGIFY(val) #val
4634 
4638 STATIC int
4639 have_enough_mem_for_dircache(const or_options_t *options, size_t total_mem,
4640  char **msg)
4641 {
4642  *msg = NULL;
4643  /* XXX We should possibly be looking at MaxMemInQueues here
4644  * unconditionally. Or we should believe total_mem unconditionally. */
4645  if (total_mem == 0) {
4646  if (get_total_system_memory(&total_mem) < 0) {
4647  total_mem = options->MaxMemInQueues >= SIZE_MAX ?
4648  SIZE_MAX : (size_t)options->MaxMemInQueues;
4649  }
4650  }
4651  if (options->DirCache) {
4652  if (total_mem < DIRCACHE_MIN_MEM_BYTES) {
4653  if (options->BridgeRelay) {
4654  tor_asprintf(msg, "Running a Bridge with less than %d MB of memory "
4655  "is not recommended.", DIRCACHE_MIN_MEM_MB);
4656  } else {
4657  tor_asprintf(msg, "Being a directory cache (default) with less than "
4658  "%d MB of memory is not recommended and may consume "
4659  "most of the available resources. Consider disabling "
4660  "this functionality by setting the DirCache option "
4661  "to 0.", DIRCACHE_MIN_MEM_MB);
4662  }
4663  }
4664  } else {
4665  if (total_mem >= DIRCACHE_MIN_MEM_BYTES) {
4666  *msg = tor_strdup("DirCache is disabled and we are configured as a "
4667  "relay. We will not become a Guard.");
4668  }
4669  }
4670  return *msg == NULL ? 0 : -1;
4671 }
4672 #undef STRINGIFY
4673 
4676 static int
4677 opt_streq(const char *s1, const char *s2)
4678 {
4679  return 0 == strcmp_opt(s1, s2);
4680 }
4681 
4683 static int
4685  const or_options_t *new_val,
4686  char **msg)
4687 {
4688  if (!old)
4689  return 0;
4690 
4691 #define BAD_CHANGE_TO(opt, how) do { \
4692  *msg = tor_strdup("While Tor is running"how", changing " #opt \
4693  " is not allowed"); \
4694  return -1; \
4695  } while (0)
4696 
4697 #define NO_CHANGE_BOOL(opt) \
4698  if (! CFG_EQ_BOOL(old, new_val, opt)) BAD_CHANGE_TO(opt,"")
4699 #define NO_CHANGE_INT(opt) \
4700  if (! CFG_EQ_INT(old, new_val, opt)) BAD_CHANGE_TO(opt,"")
4701 #define NO_CHANGE_STRING(opt) \
4702  if (! CFG_EQ_STRING(old, new_val, opt)) BAD_CHANGE_TO(opt,"")
4703 
4704  NO_CHANGE_STRING(PidFile);
4705  NO_CHANGE_BOOL(RunAsDaemon);
4706  NO_CHANGE_BOOL(Sandbox);
4707  NO_CHANGE_STRING(DataDirectory);
4708  NO_CHANGE_STRING(KeyDirectory);
4709  NO_CHANGE_STRING(CacheDirectory);
4710  NO_CHANGE_STRING(User);
4711  NO_CHANGE_BOOL(KeepBindCapabilities);
4712  NO_CHANGE_STRING(SyslogIdentityTag);
4713  NO_CHANGE_STRING(AndroidIdentityTag);
4714  NO_CHANGE_BOOL(HardwareAccel);
4715  NO_CHANGE_STRING(AccelName);
4716  NO_CHANGE_STRING(AccelDir);
4717  NO_CHANGE_BOOL(TestingTorNetwork);
4718  NO_CHANGE_BOOL(DisableAllSwap);
4719  NO_CHANGE_INT(TokenBucketRefillInterval);
4720  NO_CHANGE_BOOL(HiddenServiceSingleHopMode);
4721  NO_CHANGE_BOOL(HiddenServiceNonAnonymousMode);
4722  NO_CHANGE_BOOL(DisableDebuggerAttachment);
4723  NO_CHANGE_BOOL(NoExec);
4724  NO_CHANGE_INT(OwningControllerFD);
4725  NO_CHANGE_BOOL(DisableSignalHandlers);
4726 
4727  if (sandbox_is_active()) {
4728 #define SB_NOCHANGE_STR(opt) \
4729  if (! CFG_EQ_STRING(old, new_val, opt)) \
4730  BAD_CHANGE_TO(opt," with Sandbox active")
4731 #define SB_NOCHANGE_LINELIST(opt) \
4732  if (! CFG_EQ_LINELIST(old, new_val, opt)) \
4733  BAD_CHANGE_TO(opt," with Sandbox active")
4734 #define SB_NOCHANGE_INT(opt) \
4735  if (! CFG_EQ_INT(old, new_val, opt)) \
4736  BAD_CHANGE_TO(opt," with Sandbox active")
4737 
4738  SB_NOCHANGE_STR(Address);
4739  SB_NOCHANGE_STR(ServerDNSResolvConfFile);
4740  SB_NOCHANGE_STR(DirPortFrontPage);
4741  SB_NOCHANGE_STR(CookieAuthFile);
4742  SB_NOCHANGE_STR(ExtORPortCookieAuthFile);
4743  SB_NOCHANGE_LINELIST(Logs);
4744  SB_NOCHANGE_INT(ConnLimit);
4745 
4746  if (server_mode(old) != server_mode(new_val)) {
4747  *msg = tor_strdup("Can't start/stop being a server while "
4748  "Sandbox is active");
4749  return -1;
4750  }
4751  }
4752 
4753 #undef SB_NOCHANGE_LINELIST
4754 #undef SB_NOCHANGE_STR
4755 #undef SB_NOCHANGE_INT
4756 #undef BAD_CHANGE_TO
4757 #undef NO_CHANGE_BOOL
4758 #undef NO_CHANGE_INT
4759 #undef NO_CHANGE_STRING
4760  return 0;
4761 }
4762 
4765 static int
4767  const or_options_t *new_options)
4768 {
4769  YES_IF_CHANGED_STRING(DataDirectory);
4770  YES_IF_CHANGED_INT(NumCPUs);
4771  YES_IF_CHANGED_LINELIST(ORPort_lines);
4772  YES_IF_CHANGED_BOOL(ServerDNSSearchDomains);
4773  YES_IF_CHANGED_BOOL(SafeLogging_);
4774  YES_IF_CHANGED_BOOL(ClientOnly);
4775  YES_IF_CHANGED_BOOL(LogMessageDomains);
4776  YES_IF_CHANGED_LINELIST(Logs);
4777 
4778  if (server_mode(old_options) != server_mode(new_options) ||
4779  public_server_mode(old_options) != public_server_mode(new_options) ||
4780  dir_server_mode(old_options) != dir_server_mode(new_options))
4781  return 1;
4782 
4783  /* Nothing that changed matters. */
4784  return 0;
4785 }
4786 
4789 static int
4791  const or_options_t *new_options)
4792 {
4793  /* XXX We can be smarter here. If your DirPort isn't being
4794  * published and you just turned it off, no need to republish. Etc. */
4795 
4796  YES_IF_CHANGED_STRING(DataDirectory);
4797  YES_IF_CHANGED_STRING(Nickname);
4798  YES_IF_CHANGED_STRING(Address);
4799  YES_IF_CHANGED_LINELIST(ExitPolicy);
4800  YES_IF_CHANGED_BOOL(ExitRelay);
4801  YES_IF_CHANGED_BOOL(ExitPolicyRejectPrivate);
4802  YES_IF_CHANGED_BOOL(ExitPolicyRejectLocalInterfaces);
4803  YES_IF_CHANGED_BOOL(IPv6Exit);
4804  YES_IF_CHANGED_LINELIST(ORPort_lines);
4805  YES_IF_CHANGED_LINELIST(DirPort_lines);
4806  YES_IF_CHANGED_LINELIST(DirPort_lines);
4807  YES_IF_CHANGED_BOOL(ClientOnly);
4808  YES_IF_CHANGED_BOOL(DisableNetwork);
4809  YES_IF_CHANGED_BOOL(PublishServerDescriptor_);
4810  YES_IF_CHANGED_STRING(ContactInfo);
4811  YES_IF_CHANGED_STRING(BridgeDistribution);
4812  YES_IF_CHANGED_LINELIST(MyFamily);
4813  YES_IF_CHANGED_STRING(AccountingStart);
4814  YES_IF_CHANGED_INT(AccountingMax);
4815  YES_IF_CHANGED_INT(AccountingRule);
4816  YES_IF_CHANGED_BOOL(DirCache);
4817  YES_IF_CHANGED_BOOL(AssumeReachable);
4818 
4819  if (get_effective_bwrate(old_options) != get_effective_bwrate(new_options) ||
4820  get_effective_bwburst(old_options) !=
4821  get_effective_bwburst(new_options) ||
4822  public_server_mode(old_options) != public_server_mode(new_options))
4823  return 1;
4824 
4825  return 0;
4826 }
4827 
4828 #ifdef _WIN32
4829 
4831 static char *
4832 get_windows_conf_root(void)
4833 {
4834  static int is_set = 0;
4835  static char path[MAX_PATH*2+1];
4836  TCHAR tpath[MAX_PATH] = {0};
4837 
4838  LPITEMIDLIST idl;
4839  IMalloc *m;
4840  HRESULT result;
4841 
4842  if (is_set)
4843  return path;
4844 
4845  /* Find X:\documents and settings\username\application data\ .
4846  * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
4847  */
4848 #ifdef ENABLE_LOCAL_APPDATA
4849 #define APPDATA_PATH CSIDL_LOCAL_APPDATA
4850 #else
4851 #define APPDATA_PATH CSIDL_APPDATA
4852 #endif
4853  if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, APPDATA_PATH, &idl))) {
4854  getcwd(path,MAX_PATH);
4855  is_set = 1;
4856  log_warn(LD_CONFIG,
4857  "I couldn't find your application data folder: are you "
4858  "running an ancient version of Windows 95? Defaulting to \"%s\"",
4859  path);
4860  return path;
4861  }
4862  /* Convert the path from an "ID List" (whatever that is!) to a path. */
4863  result = SHGetPathFromIDList(idl, tpath);
4864 #ifdef UNICODE
4865  wcstombs(path,tpath,sizeof(path));
4866  path[sizeof(path)-1] = '\0';
4867 #else
4868  strlcpy(path,tpath,sizeof(path));
4869 #endif /* defined(UNICODE) */
4870 
4871  /* Now we need to free the memory that the path-idl was stored in. In
4872  * typical Windows fashion, we can't just call 'free()' on it. */
4873  SHGetMalloc(&m);
4874  if (m) {
4875  m->lpVtbl->Free(m, idl);
4876  m->lpVtbl->Release(m);
4877  }
4878  if (!SUCCEEDED(result)) {
4879  return NULL;
4880  }
4881  strlcat(path,"\\tor",MAX_PATH);
4882  is_set = 1;
4883  return path;
4884 }
4885 #endif /* defined(_WIN32) */
4886 
4889 static const char *
4890 get_default_conf_file(int defaults_file)
4891 {
4892 #ifdef DISABLE_SYSTEM_TORRC
4893  (void) defaults_file;
4894  return NULL;
4895 #elif defined(_WIN32)
4896  if (defaults_file) {
4897  static char defaults_path[MAX_PATH+1];
4898  tor_snprintf(defaults_path, MAX_PATH, "%s\\torrc-defaults",
4899  get_windows_conf_root());
4900  return defaults_path;
4901  } else {
4902  static char path[MAX_PATH+1];
4903  tor_snprintf(path, MAX_PATH, "%s\\torrc",
4904  get_windows_conf_root());
4905  return path;
4906  }
4907 #else
4908  return defaults_file ? CONFDIR "/torrc-defaults" : CONFDIR "/torrc";
4909 #endif /* defined(DISABLE_SYSTEM_TORRC) || ... */
4910 }
4911 
4918 static int
4920  const config_line_t *lst, const char *name,
4921  char **msg)
4922 {
4923  if (!lst)
4924  return 0;
4925 
4926  config_line_t *new_nicknames = NULL;
4927  config_line_t **new_nicknames_next = &new_nicknames;
4928 
4929  const config_line_t *cl;
4930  for (cl = lst; cl; cl = cl->next) {
4931  const char *line = cl->value;
4932  if (!line)
4933  continue;
4934 
4935  int valid_line = 1;
4936  smartlist_t *sl = smartlist_new();
4937  smartlist_split_string(sl, line, ",",
4938  SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK|SPLIT_STRIP_SPACE, 0);
4939  SMARTLIST_FOREACH_BEGIN(sl, char *, s)
4940  {
4941  char *normalized = NULL;
4943  // check if first char is dollar
4944  if (s[0] != '$') {
4945  // Try again but with a dollar symbol prepended
4946  char *prepended;
4947  tor_asprintf(&prepended, "$%s", s);
4948 
4949  if (is_legal_nickname_or_hexdigest(prepended)) {
4950  // The nickname is valid when it's prepended, set it as the
4951  // normalized version
4952  normalized = prepended;
4953  } else {
4954  // Still not valid, free and fallback to error message
4955  tor_free(prepended);
4956  }
4957  }
4958 
4959  if (!normalized) {
4960  tor_asprintf(msg, "Invalid nickname '%s' in %s line", s, name);
4961  valid_line = 0;
4962  break;
4963  }
4964  } else {
4965  normalized = tor_strdup(s);
4966  }
4967 
4968  config_line_t *next = tor_malloc_zero(sizeof(*next));
4969  next->key = tor_strdup(cl->key);
4970  next->value = normalized;
4971  next->next = NULL;
4972 
4973  *new_nicknames_next = next;
4974  new_nicknames_next = &next->next;
4975  } SMARTLIST_FOREACH_END(s);
4976 
4977  SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
4978  smartlist_free(sl);
4979 
4980  if (!valid_line) {
4981  config_free_lines(new_nicknames);
4982  return -1;
4983  }
4984  }
4985 
4986  *normalized_out = new_nicknames;
4987 
4988  return 0;
4989 }
4990 
5002 static char *
5004  int defaults_file,
5005  int *using_default_fname, int *ignore_missing_torrc)
5006 {
5007  char *fname=NULL;
5008  config_line_t *p_index;
5009  const char *fname_opt = defaults_file ? "--defaults-torrc" : "-f";
5010  const char *ignore_opt = defaults_file ? NULL : "--ignore-missing-torrc";
5011 
5012  if (defaults_file)
5013  *ignore_missing_torrc = 1;
5014 
5015  for (p_index = cmd_arg; p_index; p_index = p_index->next) {
5016  if (!strcmp(p_index->key, fname_opt)) {
5017  if (fname) {
5018  log_warn(LD_CONFIG, "Duplicate %s options on command line.",
5019  fname_opt);
5020  tor_free(fname);
5021  }
5022  fname = expand_filename(p_index->value);
5023 
5024  {
5025  char *absfname;
5026  absfname = make_path_absolute(fname);
5027  tor_free(fname);
5028  fname = absfname;
5029  }
5030 
5031  *using_default_fname = 0;
5032  } else if (ignore_opt && !strcmp(p_index->key,ignore_opt)) {
5033  *ignore_missing_torrc = 1;
5034  }
5035  }
5036 
5037  if (*using_default_fname) {
5038  /* didn't find one, try CONFDIR */
5039  const char *dflt = get_default_conf_file(defaults_file);
5040  file_status_t st = file_status(dflt);
5041  if (dflt && (st == FN_FILE || st == FN_EMPTY)) {
5042  fname = tor_strdup(dflt);
5043  } else {
5044 #ifndef _WIN32
5045  char *fn = NULL;
5046  if (!defaults_file) {
5047  fn = expand_filename("~/.torrc");
5048  }
5049  if (fn) {
5050  file_status_t hmst = file_status(fn);
5051  if (hmst == FN_FILE || hmst == FN_EMPTY || dflt == NULL) {
5052  fname = fn;
5053  } else {
5054  tor_free(fn);
5055  fname = tor_strdup(dflt);
5056  }
5057  } else {
5058  fname = dflt ? tor_strdup(dflt) : NULL;
5059  }
5060 #else /* !(!defined(_WIN32)) */
5061  fname = dflt ? tor_strdup(dflt) : NULL;
5062 #endif /* !defined(_WIN32) */
5063  }
5064  }
5065  return fname;
5066 }
5067 
5071 static char *
5073 {
5074  size_t sz_out;
5075 
5076  return read_file_to_str_until_eof(STDIN_FILENO,SIZE_MAX,&sz_out);
5077 }
5078 
5086 static char *
5087 load_torrc_from_disk(config_line_t *cmd_arg, int defaults_file)
5088 {
5089  char *fname=NULL;
5090  char *cf = NULL;
5091  int using_default_torrc = 1;
5092  int ignore_missing_torrc = 0;
5093  char **fname_var = defaults_file ? &torrc_defaults_fname : &torrc_fname;
5094 
5095  if (*fname_var == NULL) {
5096  fname = find_torrc_filename(cmd_arg, defaults_file,
5097  &using_default_torrc, &ignore_missing_torrc);
5098  tor_free(*fname_var);
5099  *fname_var = fname;
5100  } else {
5101  fname = *fname_var;
5102  }
5103  log_debug(LD_CONFIG, "Opening config file \"%s\"", fname?fname:"<NULL>");
5104 
5105  /* Open config file */
5106  file_status_t st = fname ? file_status(fname) : FN_EMPTY;
5107  if (fname == NULL ||
5108  !(st == FN_FILE || st == FN_EMPTY) ||
5109  !(cf = read_file_to_str(fname,0,NULL))) {
5110  if (using_default_torrc == 1 || ignore_missing_torrc) {
5111  if (!defaults_file)
5112  log_notice(LD_CONFIG, "Configuration file \"%s\" not present, "
5113  "using reasonable defaults.", fname);
5114  tor_free(fname); /* sets fname to NULL */
5115  *fname_var = NULL;
5116  cf = tor_strdup("");
5117  } else {
5118  log_warn(LD_CONFIG,
5119  "Unable to open configuration file \"%s\".", fname);
5120  goto err;
5121  }
5122  } else {
5123  log_notice(LD_CONFIG, "Read configuration file \"%s\".", fname);
5124  }
5125 
5126  return cf;
5127  err:
5128  tor_free(fname);
5129  *fname_var = NULL;
5130  return NULL;
5131 }
5132 
5138 int
5139 options_init_from_torrc(int argc, char **argv)
5140 {
5141  char *cf=NULL, *cf_defaults=NULL;
5142  int command;
5143  int retval = -1;
5144  char *command_arg = NULL;
5145  char *errmsg=NULL;
5146  config_line_t *p_index = NULL;
5147  config_line_t *cmdline_only_options = NULL;
5148 
5149  /* Go through command-line variables */
5150  if (! have_parsed_cmdline) {
5151  /* Or we could redo the list every time we pass this place.
5152  * It does not really matter */
5155  goto err;
5156  }
5157  have_parsed_cmdline = 1;
5158  }
5159  cmdline_only_options = global_cmdline_only_options;
5160 
5161  if (config_line_find(cmdline_only_options, "-h") ||
5162  config_line_find(cmdline_only_options, "--help")) {
5163  print_usage();
5164  return 1;
5165  }
5166  if (config_line_find(cmdline_only_options, "--list-torrc-options")) {
5167  /* For validating whether we've documented everything. */
5169  return 1;
5170  }
5171  if (config_line_find(cmdline_only_options, "--list-deprecated-options")) {
5172  /* For validating whether what we have deprecated really exists. */
5174  return 1;
5175  }
5176 
5177  if (config_line_find(cmdline_only_options, "--version")) {
5178  printf("Tor version %s.\n",get_version());
5179  return 1;
5180  }
5181 
5182  if (config_line_find(cmdline_only_options, "--library-versions")) {
5183  printf("Tor version %s. \n", get_version());
5184  printf("Library versions\tCompiled\t\tRuntime\n");
5185  printf("Libevent\t\t%-15s\t\t%s\n",
5188 #ifdef ENABLE_OPENSSL
5189  printf("OpenSSL \t\t%-15s\t\t%s\n",
5190  crypto_openssl_get_header_version_str(),
5191  crypto_openssl_get_version_str());
5192 #endif
5193 #ifdef ENABLE_NSS
5194  printf("NSS \t\t%-15s\t\t%s\n",
5195  crypto_nss_get_header_version_str(),
5196  crypto_nss_get_version_str());
5197 #endif
5198  if (tor_compress_supports_method(ZLIB_METHOD)) {
5199  printf("Zlib \t\t%-15s\t\t%s\n",
5200  tor_compress_version_str(ZLIB_METHOD),
5201  tor_compress_header_version_str(ZLIB_METHOD));
5202  }
5203  if (tor_compress_supports_method(LZMA_METHOD)) {
5204  printf("Liblzma \t\t%-15s\t\t%s\n",
5205  tor_compress_version_str(LZMA_METHOD),
5206  tor_compress_header_version_str(LZMA_METHOD));
5207  }
5208  if (tor_compress_supports_method(ZSTD_METHOD)) {
5209  printf("Libzstd \t\t%-15s\t\t%s\n",
5210  tor_compress_version_str(ZSTD_METHOD),
5211  tor_compress_header_version_str(ZSTD_METHOD));
5212  }
5213  //TODO: Hex versions?
5214  return 1;
5215  }
5216 
5217  command = CMD_RUN_TOR;
5218  for (p_index = cmdline_only_options; p_index; p_index = p_index->next) {
5219  if (!strcmp(p_index->key,"--keygen")) {
5220  command = CMD_KEYGEN;
5221  } else if (!strcmp(p_index->key, "--key-expiration")) {
5222  command = CMD_KEY_EXPIRATION;
5223  command_arg = p_index->value;
5224  } else if (!strcmp(p_index->key,"--list-fingerprint")) {
5225  command = CMD_LIST_FINGERPRINT;
5226  } else if (!strcmp(p_index->key, "--hash-password")) {
5227  command = CMD_HASH_PASSWORD;
5228  command_arg = p_index->value;
5229  } else if (!strcmp(p_index->key, "--dump-config")) {
5230  command = CMD_DUMP_CONFIG;
5231  command_arg = p_index->value;
5232  } else if (!strcmp(p_index->key, "--verify-config")) {
5233  command = CMD_VERIFY_CONFIG;
5234  }
5235  }
5236 
5237  if (command == CMD_HASH_PASSWORD) {
5238  cf_defaults = tor_strdup("");
5239  cf = tor_strdup("");
5240  } else {
5241  cf_defaults = load_torrc_from_disk(cmdline_only_options, 1);
5242 
5243  const config_line_t *f_line = config_line_find(cmdline_only_options,
5244  "-f");
5245 
5246  const int read_torrc_from_stdin =
5247  (f_line != NULL && strcmp(f_line->value, "-") == 0);
5248 
5249  if (read_torrc_from_stdin) {
5250  cf = load_torrc_from_stdin();
5251  } else {
5252  cf = load_torrc_from_disk(cmdline_only_options, 0);
5253  }
5254 
5255  if (!cf) {
5256  if (config_line_find(cmdline_only_options, "--allow-missing-torrc")) {
5257  cf = tor_strdup("");
5258  } else {
5259  goto err;
5260  }
5261  }
5262  }
5263 
5264  retval = options_init_from_string(cf_defaults, cf, command, command_arg,
5265  &errmsg);
5266 
5267  if (retval < 0)
5268  goto err;
5269 
5270  if (config_line_find(cmdline_only_options, "--no-passphrase")) {
5271  if (command == CMD_KEYGEN) {
5272  get_options_mutable()->keygen_force_passphrase = FORCE_PASSPHRASE_OFF;
5273  } else {
5274  log_err(LD_CONFIG, "--no-passphrase specified without --keygen!");
5275  retval = -1;
5276  goto err;
5277  }
5278  }
5279 
5280  if (config_line_find(cmdline_only_options, "--newpass")) {
5281  if (command == CMD_KEYGEN) {
5282  get_options_mutable()->change_key_passphrase = 1;
5283  } else {
5284  log_err(LD_CONFIG, "--newpass specified without --keygen!");
5285  retval = -1;
5286  goto err;
5287  }
5288  }
5289 
5290  {
5291  const config_line_t *fd_line = config_line_find(cmdline_only_options,
5292  "--passphrase-fd");
5293  if (fd_line) {
5294  if (get_options()->keygen_force_passphrase == FORCE_PASSPHRASE_OFF) {
5295  log_err(LD_CONFIG, "--no-passphrase specified with --passphrase-fd!");
5296  retval = -1;
5297  goto err;
5298  } else if (command != CMD_KEYGEN) {
5299  log_err(LD_CONFIG, "--passphrase-fd specified without --keygen!");
5300  retval = -1;
5301  goto err;
5302  } else {
5303  const char *v = fd_line->value;
5304  int ok = 1;
5305  long fd = tor_parse_long(v, 10, 0, INT_MAX, &ok, NULL);
5306  if (fd < 0 || ok == 0) {
5307  log_err(LD_CONFIG, "Invalid --passphrase-fd value %s", escaped(v));
5308  retval = -1;
5309  goto err;
5310  }
5311  get_options_mutable()->keygen_passphrase_fd = (int)fd;
5312  get_options_mutable()->use_keygen_passphrase_fd = 1;
5313  get_options_mutable()->keygen_force_passphrase = FORCE_PASSPHRASE_ON;
5314  }
5315  }
5316  }
5317 
5318  {
5319  const config_line_t *key_line = config_line_find(cmdline_only_options,
5320  "--master-key");
5321  if (key_line) {
5322  if (command != CMD_KEYGEN) {
5323  log_err(LD_CONFIG, "--master-key without --keygen!");
5324  retval = -1;
5325  goto err;
5326  } else {
5327  get_options_mutable()->master_key_fname = tor_strdup(key_line->value);
5328  }
5329  }
5330  }
5331 
5332  err:
5333 
5334  tor_free(cf);
5335  tor_free(cf_defaults);
5336  if (errmsg) {
5337  log_warn(LD_CONFIG,"%s", errmsg);
5338  tor_free(errmsg);
5339  }
5340  return retval < 0 ? -1 : 0;
5341 }
5342 
5353 options_init_from_string(const char *cf_defaults, const char *cf,
5354  int command, const char *command_arg,
5355  char **msg)
5356 {
5357  or_options_t *oldoptions, *newoptions, *newdefaultoptions=NULL;
5358  config_line_t *cl;
5359  int retval;
5360  setopt_err_t err = SETOPT_ERR_MISC;
5361  int cf_has_include = 0;
5362  tor_assert(msg);
5363 
5364  oldoptions = global_options; /* get_options unfortunately asserts if
5365  this is the first time we run*/
5366 
5367  newoptions = tor_malloc_zero(sizeof(or_options_t));
5368  newoptions->magic_ = OR_OPTIONS_MAGIC;
5369  options_init(newoptions);
5370  newoptions->command = command;
5371  newoptions->command_arg = command_arg ? tor_strdup(command_arg) : NULL;
5372 
5373  smartlist_t *opened_files = smartlist_new();
5374  for (int i = 0; i < 2; ++i) {
5375  const char *body = i==0 ? cf_defaults : cf;
5376  if (!body)
5377  continue;
5378 
5379  /* get config lines, assign them */
5380  retval = config_get_lines_include(body, &cl, 1,
5381  body == cf ? &cf_has_include : NULL,
5382  opened_files);
5383  if (retval < 0) {
5384  err = SETOPT_ERR_PARSE;
5385  goto err;
5386  }
5387  retval = config_assign(&options_format, newoptions, cl,
5388  CAL_WARN_DEPRECATIONS, msg);
5389  config_free_lines(cl);
5390  if (retval < 0) {
5391  err = SETOPT_ERR_PARSE;
5392  goto err;
5393  }
5394  if (i==0)
5395  newdefaultoptions = config_dup(&options_format, newoptions);
5396  }
5397 
5398  if (newdefaultoptions == NULL) {
5399  newdefaultoptions = config_dup(&options_format, global_default_options);
5400  }
5401 
5402  /* Go through command-line variables too */
5403  retval = config_assign(&options_format, newoptions,
5404  global_cmdline_options, CAL_WARN_DEPRECATIONS, msg);
5405  if (retval < 0) {
5406  err = SETOPT_ERR_PARSE;
5407  goto err;
5408  }
5409 
5410  newoptions->IncludeUsed = cf_has_include;
5411  newoptions->FilesOpenedByIncludes = opened_files;
5412 
5413  /* If this is a testing network configuration, change defaults
5414  * for a list of dependent config options, re-initialize newoptions
5415  * with the new defaults, and assign all options to it second time. */
5416  if (newoptions->TestingTorNetwork) {
5417  /* XXXX this is a bit of a kludge. perhaps there's a better way to do
5418  * this? We could, for example, make the parsing algorithm do two passes
5419  * over the configuration. If it finds any "suite" options like
5420  * TestingTorNetwork, it could change the defaults before its second pass.
5421  * Not urgent so long as this seems to work, but at any sign of trouble,
5422  * let's clean it up. -NM */
5423 
5424  /* Change defaults. */
5425  for (int i = 0; testing_tor_network_defaults[i].name; ++i) {
5426  const config_var_t *new_var = &testing_tor_network_defaults[i];
5427  config_var_t *old_var =
5429  tor_assert(new_var);
5430  tor_assert(old_var);
5431  old_var->initvalue = new_var->initvalue;
5432 
5433  if ((config_find_deprecation(&options_format, new_var->name))) {
5434  log_warn(LD_GENERAL, "Testing options override the deprecated "
5435  "option %s. Is that intentional?",
5436  new_var->name);
5437  }
5438  }
5439 
5440  /* Clear newoptions and re-initialize them with new defaults. */
5441  or_options_free(newoptions);
5442  or_options_free(newdefaultoptions);
5443  newdefaultoptions = NULL;
5444  newoptions = tor_malloc_zero(sizeof(or_options_t));
5445  newoptions->magic_ = OR_OPTIONS_MAGIC;
5446  options_init(newoptions);
5447  newoptions->command = command;
5448  newoptions->command_arg = command_arg ? tor_strdup(command_arg) : NULL;
5449 
5450  /* Assign all options a second time. */
5451  opened_files = smartlist_new();
5452  for (int i = 0; i < 2; ++i) {
5453  const char *body = i==0 ? cf_defaults : cf;
5454  if (!body)
5455  continue;
5456 
5457  /* get config lines, assign them */
5458  retval = config_get_lines_include(body, &cl, 1,
5459  body == cf ? &cf_has_include : NULL,
5460  opened_files);
5461  if (retval < 0) {
5462  err = SETOPT_ERR_PARSE;
5463  goto err;
5464  }
5465  retval = config_assign(&options_format, newoptions, cl, 0, msg);
5466  config_free_lines(cl);
5467  if (retval < 0) {
5468  err = SETOPT_ERR_PARSE;
5469  goto err;
5470  }
5471  if (i==0)
5472  newdefaultoptions = config_dup(&options_format, newoptions);
5473  }
5474  /* Assign command-line variables a second time too */
5475  retval = config_assign(&options_format, newoptions,
5476  global_cmdline_options, 0, msg);
5477  if (retval < 0) {
5478  err = SETOPT_ERR_PARSE;
5479  goto err;
5480  }
5481  }
5482 
5483  newoptions->IncludeUsed = cf_has_include;
5485  newoptions->FilesOpenedByIncludes = opened_files;
5486 
5487  /* Validate newoptions */
5488  if (options_validate(oldoptions, newoptions, newdefaultoptions,
5489  0, msg) < 0) {
5490  err = SETOPT_ERR_PARSE; /*XXX make this a separate return value.*/
5491  goto err;
5492  }
5493 
5494  if (options_transition_allowed(oldoptions, newoptions, msg) < 0) {
5495  err = SETOPT_ERR_TRANSITION;
5496  goto err;
5497  }
5499 
5500  if (set_options(newoptions, msg)) {
5501  err = SETOPT_ERR_SETTING;
5502  goto err; /* frees and replaces old options */
5503  }
5504 
5505  or_options_free(global_default_options);
5506  global_default_options = newdefaultoptions;
5507 
5508  return SETOPT_OK;
5509 
5510  err:
5512  if (opened_files) {
5513  SMARTLIST_FOREACH(opened_files, char *, f, tor_free(f));
5514  smartlist_free(opened_files);
5515  }
5516  // may have been set to opened_files, avoid double free
5517  newoptions->FilesOpenedByIncludes = NULL;
5518  or_options_free(newoptions);
5519  or_options_free(newdefaultoptions);
5520  if (*msg) {
5521  char *old_msg = *msg;
5522  tor_asprintf(msg, "Failed to parse/validate config: %s", old_msg);
5523  tor_free(old_msg);
5524  }
5525  return err;
5526 }
5527 
5530 const char *
5531 get_torrc_fname(int defaults_fname)
5532 {
5533  const char *fname = defaults_fname ? torrc_defaults_fname : torrc_fname;
5534 
5535  if (fname)
5536  return fname;
5537  else
5538  return get_default_conf_file(defaults_fname);
5539 }
5540 
5544 void
5546 {
5547  smartlist_t *elts;
5548  config_line_t *opt;
5549  const char *from, *to, *msg;
5550 
5552  elts = smartlist_new();
5553  for (opt = options->AddressMap; opt; opt = opt->next) {
5554  smartlist_split_string(elts, opt->value, NULL,
5555  SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
5556  if (smartlist_len(elts) < 2) {
5557  log_warn(LD_CONFIG,"MapAddress '%s' has too few arguments. Ignoring.",
5558  opt->value);
5559  goto cleanup;
5560  }
5561 
5562  from = smartlist_get(elts,0);
5563  to = smartlist_get(elts,1);
5564 
5565  if (to[0] == '.' || from[0] == '.') {
5566  log_warn(LD_CONFIG,"MapAddress '%s' is ambiguous - address starts with a"
5567  "'.'. Ignoring.",opt->value);
5568  goto cleanup;
5569  }
5570 
5571  if (addressmap_register_auto(from, to, 0, ADDRMAPSRC_TORRC, &msg) < 0) {
5572  log_warn(LD_CONFIG,"MapAddress '%s' failed: %s. Ignoring.", opt->value,
5573  msg);
5574  goto cleanup;
5575  }
5576 
5577  if (smartlist_len(elts) > 2)
5578  log_warn(LD_CONFIG,"Ignoring extra arguments to MapAddress.");
5579 
5580  cleanup:
5581  SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
5582  smartlist_clear(elts);
5583  }
5584  smartlist_free(elts);
5585 }
5586 
5589 /* XXXX move to connection_edge.c */
5590 int
5591 addressmap_register_auto(const char *from, const char *to,
5592  time_t expires,
5593  addressmap_entry_source_t addrmap_source,
5594  const char **msg)
5595 {
5596  int from_wildcard = 0, to_wildcard = 0;
5597 
5598  *msg = "whoops, forgot the error message";
5599 
5600  if (!strcmp(to, "*") || !strcmp(from, "*")) {
5601  *msg = "can't remap from or to *";
5602  return -1;
5603  }
5604  /* Detect asterisks in expressions of type: '*.example.com' */
5605  if (!strncmp(from,"*.",2)) {
5606  from += 2;
5607  from_wildcard = 1;
5608  }
5609  if (!strncmp(to,"*.",2)) {
5610  to += 2;
5611  to_wildcard = 1;
5612  }
5613 
5614  if (to_wildcard && !from_wildcard) {
5615  *msg = "can only use wildcard (i.e. '*.') if 'from' address "
5616  "uses wildcard also";
5617  return -1;
5618  }
5619 
5620  if (address_is_invalid_destination(to, 1)) {
5621  *msg = "destination is invalid";
5622  return -1;
5623  }
5624 
5625  addressmap_register(from, tor_strdup(to), expires, addrmap_source,
5626  from_wildcard, to_wildcard);
5627 
5628  return 0;
5629 }
5630 
5634 STATIC int
5636  const char *filename, int truncate_log)
5637 {
5638  int open_flags = O_WRONLY|O_CREAT;
5639  open_flags |= truncate_log ? O_TRUNC : O_APPEND;
5640 
5641  int fd = tor_open_cloexec(filename, open_flags, 0640);
5642  if (fd < 0)
5643  return -1;
5644 
5645  return add_file_log(severity, filename, fd);
5646 }
5647 
5651 static int
5652 options_init_logs(const or_options_t *old_options, or_options_t *options,
5653  int validate_only)
5654 {
5655  config_line_t *opt;
5656  int ok;
5657  smartlist_t *elts;
5658  int run_as_daemon =
5659 #ifdef _WIN32
5660  0;
5661 #else
5662  options->RunAsDaemon;
5663 #endif
5664 
5665  if (options->LogTimeGranularity <= 0) {
5666  log_warn(LD_CONFIG, "Log time granularity '%d' has to be positive.",
5667  options->LogTimeGranularity);
5668  return -1;
5669  } else if (1000 % options->LogTimeGranularity != 0 &&
5670  options->LogTimeGranularity % 1000 != 0) {
5671  int granularity = options->LogTimeGranularity;
5672  if (granularity < 40) {
5673  do granularity++;
5674  while (1000 % granularity != 0);
5675  } else if (granularity < 1000) {
5676  granularity = 1000 / granularity;
5677  while (1000 % granularity != 0)
5678  granularity--;
5679  granularity = 1000 / granularity;
5680  } else {
5681  granularity = 1000 * ((granularity / 1000) + 1);
5682  }
5683  log_warn(LD_CONFIG, "Log time granularity '%d' has to be either a "
5684  "divisor or a multiple of 1 second. Changing to "
5685  "'%d'.",
5686  options->LogTimeGranularity, granularity);
5687  if (!validate_only)
5688  set_log_time_granularity(granularity);
5689  } else {
5690  if (!validate_only)
5692  }
5693 
5694  ok = 1;
5695  elts = smartlist_new();
5696 
5697  for (opt = options->Logs; opt; opt = opt->next) {
5698  log_severity_list_t *severity;
5699  const char *cfg = opt->value;
5700  severity = tor_malloc_zero(sizeof(log_severity_list_t));
5701  if (parse_log_severity_config(&cfg, severity) < 0) {
5702  log_warn(LD_CONFIG, "Couldn't parse log levels in Log option 'Log %s'",
5703  opt->value);
5704  ok = 0; goto cleanup;
5705  }
5706 
5707  smartlist_split_string(elts, cfg, NULL,
5708  SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
5709 
5710  if (smartlist_len(elts) == 0)
5711  smartlist_add_strdup(elts, "stdout");
5712 
5713  if (smartlist_len(elts) == 1 &&
5714  (!strcasecmp(smartlist_get(elts,0), "stdout") ||
5715  !strcasecmp(smartlist_get(elts,0), "stderr"))) {
5716  int err = smartlist_len(elts) &&
5717  !strcasecmp(smartlist_get(elts,0), "stderr");
5718  if (!validate_only) {
5719  if (run_as_daemon) {
5720  log_warn(LD_CONFIG,
5721  "Can't log to %s with RunAsDaemon set; skipping stdout",
5722  err?"stderr":"stdout");
5723  } else {
5724  add_stream_log(severity, err?"<stderr>":"<stdout>",
5725  fileno(err?stderr:stdout));
5726  }
5727  }
5728  goto cleanup;
5729  }
5730  if (smartlist_len(elts) == 1) {
5731  if (!strcasecmp(smartlist_get(elts,0), "syslog")) {
5732 #ifdef HAVE_SYSLOG_H
5733  if (!validate_only) {
5734  add_syslog_log(severity, options->SyslogIdentityTag);
5735  }
5736 #else
5737  log_warn(LD_CONFIG, "Syslog is not supported on this system. Sorry.");
5738 #endif /* defined(HAVE_SYSLOG_H) */
5739  goto cleanup;
5740  }
5741 
5742  if (!strcasecmp(smartlist_get(elts, 0), "android")) {
5743 #ifdef HAVE_ANDROID_LOG_H
5744  if (!validate_only) {
5745  add_android_log(severity, options->AndroidIdentityTag);
5746  }
5747 #else
5748  log_warn(LD_CONFIG, "Android logging is not supported"
5749  " on this system. Sorry.");
5750 #endif // HAVE_ANDROID_LOG_H.
5751  goto cleanup;
5752  }
5753  }
5754 
5755  if (smartlist_len(elts) == 2 &&
5756  !strcasecmp(smartlist_get(elts,0), "file")) {
5757  if (!validate_only) {
5758  char *fname = expand_filename(smartlist_get(elts, 1));
5759  /* Truncate if TruncateLogFile is set and we haven't seen this option
5760  line before. */
5761  int truncate_log = 0;
5762  if (options->TruncateLogFile) {
5763  truncate_log = 1;
5764  if (old_options) {
5765  config_line_t *opt2;
5766  for (opt2 = old_options->Logs; opt2; opt2 = opt2->next)
5767  if (!strcmp(opt->value, opt2->value)) {
5768  truncate_log = 0;
5769  break;
5770  }
5771  }
5772  }
5773  if (open_and_add_file_log(severity, fname, truncate_log) < 0) {
5774  log_warn(LD_CONFIG, "Couldn't open file for 'Log %s': %s",
5775  opt->value, strerror(errno));
5776  ok = 0;
5777  }
5778  tor_free(fname);
5779  }
5780  goto cleanup;
5781  }
5782 
5783  log_warn(LD_CONFIG, "Bad syntax on file Log option 'Log %s'",
5784  opt->value);
5785  ok = 0; goto cleanup;
5786 
5787  cleanup:
5788  SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
5789  smartlist_clear(elts);
5790  tor_free(severity);
5791  }
5792  smartlist_free(elts);
5793 
5794  if (ok && !validate_only)
5796 
5797  return ok?0:-1;
5798 }
5799 
5803 static int
5805 {
5806  char *socks_string = NULL;
5807  size_t socks_string_len;
5808 
5809  tor_assert(args);
5810  tor_assert(smartlist_len(args) > 0);
5811 
5812  SMARTLIST_FOREACH_BEGIN(args, const char *, s) {
5813  if (!string_is_key_value(LOG_WARN, s)) { /* items should be k=v items */
5814  log_warn(LD_CONFIG, "'%s' is not a k=v item.", s);
5815  return -1;
5816  }
5817  } SMARTLIST_FOREACH_END(s);
5818 
5819  socks_string = pt_stringify_socks_args(args);
5820  if (!socks_string)
5821  return -1;
5822 
5823  socks_string_len = strlen(socks_string);
5824  tor_free(socks_string);
5825 
5826  if (socks_string_len > MAX_SOCKS5_AUTH_SIZE_TOTAL) {
5827  log_warn(LD_CONFIG, "SOCKS arguments can't be more than %u bytes (%lu).",
5829  (unsigned long) socks_string_len);
5830  return -1;
5831  }
5832 
5833  return 0;
5834 }
5835 
5837 /* private */ void
5839 {
5840  if (!bridge_line)
5841  return;
5842 
5843  if (bridge_line->socks_args) {
5844  SMARTLIST_FOREACH(bridge_line->socks_args, char*, s, tor_free(s));
5845  smartlist_free(bridge_line->socks_args);
5846  }
5847  tor_free(bridge_line->transport_name);
5848  tor_free(bridge_line);
5849 }
5850 
5863 /* private */ bridge_line_t *
5864 parse_bridge_line(const char *line)
5865 {
5866  smartlist_t *items = NULL;
5867  char *addrport=NULL, *fingerprint=NULL;
5868  char *field=NULL;
5869  bridge_line_t *bridge_line = tor_malloc_zero(sizeof(bridge_line_t));
5870 
5871  items = smartlist_new();
5872  smartlist_split_string(items, line, NULL,
5873  SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
5874  if (smartlist_len(items) < 1) {
5875  log_warn(LD_CONFIG, "Too few arguments to Bridge line.");
5876  goto err;
5877  }
5878 
5879  /* first field is either a transport name or addrport */
5880  field = smartlist_get(items, 0);
5881  smartlist_del_keeporder(items, 0);
5882 
5883  if (string_is_C_identifier(field)) {
5884  /* It's a transport name. */
5885  bridge_line->transport_name = field;
5886  if (smartlist_len(items) < 1) {
5887  log_warn(LD_CONFIG, "Too few items to Bridge line.");
5888  goto err;
5889  }
5890  addrport = smartlist_get(items, 0); /* Next field is addrport then. */
5891  smartlist_del_keeporder(items, 0);
5892  } else {
5893  addrport = field;
5894  }
5895 
5896  if (tor_addr_port_parse(LOG_INFO, addrport,
5897  &bridge_line->addr, &bridge_line->port, 443)<0) {
5898  log_warn(LD_CONFIG, "Error parsing Bridge address '%s'", addrport);
5899  goto err;
5900  }
5901 
5902  /* If transports are enabled, next field could be a fingerprint or a
5903  socks argument. If transports are disabled, next field must be
5904  a fingerprint. */
5905  if (smartlist_len(items)) {
5906  if (bridge_line->transport_name) { /* transports enabled: */
5907  field = smartlist_get(items, 0);
5908  smartlist_del_keeporder(items, 0);
5909 
5910  /* If it's a key=value pair, then it's a SOCKS argument for the
5911  transport proxy... */
5912  if (string_is_key_value(LOG_DEBUG, field)) {
5913  bridge_line->socks_args = smartlist_new();
5914  smartlist_add(bridge_line->socks_args, field);
5915  } else { /* ...otherwise, it's the bridge fingerprint. */
5916  fingerprint = field;
5917  }
5918 
5919  } else { /* transports disabled: */
5920  fingerprint = smartlist_join_strings(items, "", 0, NULL);
5921  }
5922  }
5923 
5924  /* Handle fingerprint, if it was provided. */
5925  if (fingerprint) {
5926  if (strlen(fingerprint) != HEX_DIGEST_LEN) {
5927  log_warn(LD_CONFIG, "Key digest for Bridge is wrong length.");
5928  goto err;
5929  }
5930  if (base16_decode(bridge_line->digest, DIGEST_LEN,
5931  fingerprint, HEX_DIGEST_LEN) != DIGEST_LEN) {
5932  log_warn(LD_CONFIG, "Unable to decode Bridge key digest.");
5933  goto err;
5934  }
5935  }
5936 
5937  /* If we are using transports, any remaining items in the smartlist
5938  should be k=v values. */
5939  if (bridge_line->transport_name && smartlist_len(items)) {
5940  if (!bridge_line->socks_args)
5941  bridge_line->socks_args = smartlist_new();
5942 
5943  /* append remaining items of 'items' to 'socks_args' */
5944  smartlist_add_all(bridge_line->socks_args, items);
5945  smartlist_clear(items);
5946 
5947  tor_assert(smartlist_len(bridge_line->socks_args) > 0);
5948  }
5949 
5950  if (bridge_line->socks_args) {
5951  if (validate_transport_socks_arguments(bridge_line->socks_args) < 0)
5952  goto err;
5953  }
5954 
5955  goto done;
5956 
5957  err:
5958  bridge_line_free(bridge_line);
5959  bridge_line = NULL;
5960 
5961  done:
5962  SMARTLIST_FOREACH(items, char*, s, tor_free(s));
5963  smartlist_free(items);
5964  tor_free(addrport);
5965  tor_free(fingerprint);
5966 
5967  return bridge_line;
5968 }
5969 
5981 STATIC int
5983  const char *line, int validate_only,
5984  int server)
5985 {
5986 
5987  smartlist_t *items = NULL;
5988  int r;
5989  const char *transports = NULL;
5990  smartlist_t *transport_list = NULL;
5991  char *type = NULL;
5992  char *addrport = NULL;
5993  tor_addr_t addr;
5994  uint16_t port = 0;
5995  int socks_ver = PROXY_NONE;
5996 
5997  /* managed proxy options */
5998  int is_managed = 0;
5999  char **proxy_argv = NULL;
6000  char **tmp = NULL;
6001  int proxy_argc, i;
6002  int is_useless_proxy = 1;
6003 
6004  int line_length;
6005 
6006  /* Split the line into space-separated tokens */
6007  items = smartlist_new();
6008  smartlist_split_string(items, line, NULL,
6009  SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
6010  line_length = smartlist_len(items);
6011 
6012  if (line_length < 3) {
6013  log_warn(LD_CONFIG,
6014  "Too few arguments on %sTransportPlugin line.",
6015  server ? "Server" : "Client");
6016  goto err;
6017  }
6018 
6019  /* Get the first line element, split it to commas into
6020  transport_list (in case it's multiple transports) and validate
6021  the transport names. */
6022  transports = smartlist_get(items, 0);
6023  transport_list = smartlist_new();
6024  smartlist_split_string(transport_list, transports, ",",
6025  SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
6026  SMARTLIST_FOREACH_BEGIN(transport_list, const char *, transport_name) {
6027  /* validate transport names */
6028  if (!string_is_C_identifier(transport_name)) {
6029  log_warn(LD_CONFIG, "Transport name is not a C identifier (%s).",
6030  transport_name);
6031  goto err;
6032  }
6033 
6034  /* see if we actually need the transports provided by this proxy */
6035  if (!validate_only && transport_is_needed(transport_name))
6036  is_useless_proxy = 0;
6037  } SMARTLIST_FOREACH_END(transport_name);
6038 
6039  type = smartlist_get(items, 1);
6040  if (!strcmp(type, "exec")) {
6041  is_managed = 1;
6042  } else if (server && !strcmp(type, "proxy")) {
6043  /* 'proxy' syntax only with ServerTransportPlugin */
6044  is_managed = 0;
6045  } else if (!server && !strcmp(type, "socks4")) {
6046  /* 'socks4' syntax only with ClientTransportPlugin */
6047  is_managed = 0;
6048  socks_ver = PROXY_SOCKS4;
6049  } else if (!server && !strcmp(type, "socks5")) {
6050  /* 'socks5' syntax only with ClientTransportPlugin */
6051  is_managed = 0;
6052  socks_ver = PROXY_SOCKS5;
6053  } else {
6054  log_warn(LD_CONFIG,
6055  "Strange %sTransportPlugin type '%s'",
6056  server ? "Server" : "Client", type);
6057  goto err;
6058  }
6059 
6060  if (is_managed && options->Sandbox) {
6061  log_warn(LD_CONFIG,
6062  "Managed proxies are not compatible with Sandbox mode."
6063  "(%sTransportPlugin line was %s)",
6064  server ? "Server" : "Client", escaped(line));
6065  goto err;
6066  }
6067 
6068  if (is_managed && options->NoExec) {
6069  log_warn(LD_CONFIG,
6070  "Managed proxies are not compatible with NoExec mode; ignoring."
6071  "(%sTransportPlugin line was %s)",
6072  server ? "Server" : "Client", escaped(line));
6073  r = 0;
6074  goto done;
6075  }
6076 
6077  if (is_managed) {
6078  /* managed */
6079 
6080  if (!server && !validate_only && is_useless_proxy) {
6081  log_info(LD_GENERAL,
6082  "Pluggable transport proxy (%s) does not provide "
6083  "any needed transports and will not be launched.",
6084  line);
6085  }
6086 
6087  /*
6088  * If we are not just validating, use the rest of the line as the
6089  * argv of the proxy to be launched. Also, make sure that we are
6090  * only launching proxies that contribute useful transports.
6091  */
6092 
6093  if (!validate_only && (server || !is_useless_proxy)) {
6094  proxy_argc = line_length - 2;
6095  tor_assert(proxy_argc > 0);
6096  proxy_argv = tor_calloc((proxy_argc + 1), sizeof(char *));
6097  tmp = proxy_argv;
6098 
6099  for (i = 0; i < proxy_argc; i++) {
6100  /* store arguments */
6101  *tmp++ = smartlist_get(items, 2);
6102  smartlist_del_keeporder(items, 2);
6103  }
6104  *tmp = NULL; /* terminated with NULL, just like execve() likes it */
6105 
6106  /* kickstart the thing */
6107  if (server) {
6108  pt_kickstart_server_proxy(transport_list, proxy_argv);
6109  } else {
6110  pt_kickstart_client_proxy(transport_list, proxy_argv);
6111  }
6112  }
6113  } else {
6114  /* external */
6115 
6116  /* ClientTransportPlugins connecting through a proxy is managed only. */
6117  if (!server && (options->Socks4Proxy || options->Socks5Proxy ||
6118  options->HTTPSProxy)) {
6119  log_warn(LD_CONFIG, "You have configured an external proxy with another "
6120  "proxy type. (Socks4Proxy|Socks5Proxy|HTTPSProxy)");
6121  goto err;
6122  }
6123 
6124  if (smartlist_len(transport_list) != 1) {
6125  log_warn(LD_CONFIG,
6126  "You can't have an external proxy with more than "
6127  "one transport.");
6128  goto err;
6129  }
6130 
6131  addrport = smartlist_get(items, 2);
6132 
6133  if (tor_addr_port_lookup(addrport, &addr, &port) < 0) {
6134  log_warn(LD_CONFIG,
6135  "Error parsing transport address '%s'", addrport);
6136  goto err;
6137  }
6138 
6139  if (!port) {
6140  log_warn(LD_CONFIG,
6141  "Transport address '%s' has no port.", addrport);
6142  goto err;
6143  }
6144 
6145  if (!validate_only) {
6146  log_info(LD_DIR, "%s '%s' at %s.",
6147  server ? "Server transport" : "Transport",
6148  transports, fmt_addrport(&addr, port));
6149 
6150  if (!server) {
6151  transport_add_from_config(&addr, port,
6152  smartlist_get(transport_list, 0),
6153  socks_ver);
6154  }
6155  }
6156  }
6157 
6158  r = 0;
6159  goto done;
6160 
6161  err:
6162  r = -1;
6163 
6164  done:
6165  SMARTLIST_FOREACH(items, char*, s, tor_free(s));
6166  smartlist_free(items);
6167  if (transport_list) {
6168  SMARTLIST_FOREACH(transport_list, char*, s, tor_free(s));
6169  smartlist_free(transport_list);
6170  }
6171 
6172  return r;
6173 }
6174 
6184 static char *
6185 get_bindaddr_from_transport_listen_line(const char *line,const char *transport)
6186 {
6187  smartlist_t *items = NULL;
6188  const char *parsed_transport = NULL;
6189  char *addrport = NULL;
6190  tor_addr_t addr;
6191  uint16_t port = 0;
6192 
6193  items = smartlist_new();
6194  smartlist_split_string(items, line, NULL,
6195  SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
6196 
6197  if (smartlist_len(items) < 2) {
6198  log_warn(LD_CONFIG,"Too few arguments on ServerTransportListenAddr line.");
6199  goto err;
6200  }
6201 
6202  parsed_transport = smartlist_get(items, 0);
6203  addrport = tor_strdup(smartlist_get(items, 1));
6204 
6205  /* If 'transport' is given, check if it matches the one on the line */
6206  if (transport && strcmp(transport, parsed_transport))
6207  goto err;
6208 
6209  /* Validate addrport */
6210  if (tor_addr_port_parse(LOG_WARN, addrport, &addr, &port, -1)<0) {
6211  log_warn(LD_CONFIG, "Error parsing ServerTransportListenAddr "
6212  "address '%s'", addrport);
6213  goto err;
6214  }
6215 
6216  goto done;
6217 
6218  err:
6219  tor_free(addrport);
6220  addrport = NULL;
6221 
6222  done:
6223  SMARTLIST_FOREACH(items, char*, s, tor_free(s));
6224  smartlist_free(items);
6225 
6226  return addrport;
6227 }
6228 
6237 smartlist_t *
6238 get_options_from_transport_options_line(const char *line,const char *transport)
6239 {
6240  smartlist_t *items = smartlist_new();
6241  smartlist_t *options = smartlist_new();
6242  const char *parsed_transport = NULL;
6243 
6244  smartlist_split_string(items, line, NULL,
6245  SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
6246 
6247  if (smartlist_len(items) < 2) {
6248  log_warn(LD_CONFIG,"Too few arguments on ServerTransportOptions line.");
6249  goto err;
6250  }
6251 
6252  parsed_transport = smartlist_get(items, 0);
6253  /* If 'transport' is given, check if it matches the one on the line */
6254  if (transport && strcmp(transport, parsed_transport))
6255  goto err;
6256 
6257  SMARTLIST_FOREACH_BEGIN(items, const char *, option) {
6258  if (option_sl_idx == 0) /* skip the transport field (first field)*/
6259  continue;
6260 
6261  /* validate that it's a k=v value */
6262  if (!string_is_key_value(LOG_WARN, option)) {
6263  log_warn(LD_CONFIG, "%s is not a k=v value.", escaped(option));
6264  goto err;
6265  }
6266 
6267  /* add it to the options smartlist */
6268  smartlist_add_strdup(options, option);
6269  log_debug(LD_CONFIG, "Added %s to the list of options", escaped(option));
6270  } SMARTLIST_FOREACH_END(option);
6271 
6272  goto done;
6273 
6274  err:
6275  SMARTLIST_FOREACH(options, char*, s, tor_free(s));
6276  smartlist_free(options);
6277  options = NULL;
6278 
6279  done:
6280  SMARTLIST_FOREACH(items, char*, s, tor_free(s));
6281  smartlist_free(items);
6282 
6283  return options;
6284 }
6285 
6290 char *
6292 {
6293  config_line_t *cl;
6294  const or_options_t *options = get_options();
6295 
6296  for (cl = options->ServerTransportListenAddr; cl; cl = cl->next) {
6297  char *bindaddr =
6298  get_bindaddr_from_transport_listen_line(cl->value, transport);
6299  if (bindaddr)
6300  return bindaddr;
6301  }
6302 
6303  return NULL;
6304 }
6305 
6310 smartlist_t *
6311 get_options_for_server_transport(const char *transport)
6312 {
6313  config_line_t *cl;
6314  const or_options_t *options = get_options();
6315 
6316  for (cl = options->ServerTransportOptions; cl; cl = cl->next) {
6317  smartlist_t *options_sl =
6318  get_options_from_transport_options_line(cl->value, transport);
6319  if (options_sl)
6320  return options_sl;
6321  }
6322 
6323  return NULL;
6324 }
6325 
6333 STATIC int
6334 parse_dir_authority_line(const char *line, dirinfo_type_t required_type,
6335  int validate_only)
6336 {
6337  smartlist_t *items = NULL;
6338  int r;
6339  char *addrport=NULL, *address=NULL, *nickname=NULL, *fingerprint=NULL;
6340  tor_addr_port_t ipv6_addrport, *ipv6_addrport_ptr = NULL;
6341  uint16_t dir_port = 0, or_port = 0;
6342  char digest[DIGEST_LEN];
6343  char v3_digest[DIGEST_LEN];
6344  dirinfo_type_t type = 0;
6345  double weight = 1.0;
6346 
6347  memset(v3_digest, 0, sizeof(v3_digest));
6348 
6349  items = smartlist_new();
6350  smartlist_split_string(items, line, NULL,
6351  SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
6352  if (smartlist_len(items) < 1) {
6353  log_warn(LD_CONFIG, "No arguments on DirAuthority line.");
6354  goto err;
6355  }
6356 
6357  if (is_legal_nickname(smartlist_get(items, 0))) {
6358  nickname = smartlist_get(items, 0);
6359  smartlist_del_keeporder(items, 0);
6360  }
6361 
6362  while (smartlist_len(items)) {
6363  char *flag = smartlist_get(items, 0);
6364  if (TOR_ISDIGIT(flag[0]))
6365  break;
6366  if (!strcasecmp(flag, "hs") ||
6367  !strcasecmp(flag, "no-hs")) {
6368  log_warn(LD_CONFIG, "The DirAuthority options 'hs' and 'no-hs' are "
6369  "obsolete; you don't need them any more.");
6370  } else if (!strcasecmp(flag, "bridge")) {
6371  type |= BRIDGE_DIRINFO;
6372  } else if (!strcasecmp(flag, "no-v2")) {
6373  /* obsolete, but may still be contained in DirAuthority lines generated
6374  by various tools */;
6375  } else if (!strcasecmpstart(flag, "orport=")) {
6376  int ok;
6377  char *portstring = flag + strlen("orport=");
6378  or_port = (uint16_t) tor_parse_long(portstring, 10, 1, 65535, &ok, NULL);
6379  if (!ok)
6380  log_warn(LD_CONFIG, "Invalid orport '%s' on DirAuthority line.",
6381  portstring);
6382  } else if (!strcmpstart(flag, "weight=")) {
6383  int ok;
6384  const char *wstring = flag + strlen("weight=");
6385  weight = tor_parse_double(wstring, 0, (double)UINT64_MAX, &ok, NULL);
6386  if (!ok) {
6387  log_warn(LD_CONFIG, "Invalid weight '%s' on DirAuthority line.",flag);
6388  weight=1.0;
6389  }
6390  } else if (!strcasecmpstart(flag, "v3ident=")) {
6391  char *idstr = flag + strlen("v3ident=");
6392  if (strlen(idstr) != HEX_DIGEST_LEN ||
6393  base16_decode(v3_digest, DIGEST_LEN,
6394  idstr, HEX_DIGEST_LEN) != DIGEST_LEN) {
6395  log_warn(LD_CONFIG, "Bad v3 identity digest '%s' on DirAuthority line",