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