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