config.c 169 KB
Newer Older
Roger Dingledine's avatar
Roger Dingledine committed
1
2
/* Copyright (c) 2001 Matej Pfajfar.
 * Copyright (c) 2001-2004, Roger Dingledine.
3
 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4
 * Copyright (c) 2007-2010, The Tor Project, Inc. */
5
/* See LICENSE for licensing information */
6

Nick Mathewson's avatar
Nick Mathewson committed
7
/**
8
9
 * \file config.c
 * \brief Code to parse and interpret configuration files.
Nick Mathewson's avatar
Nick Mathewson committed
10
11
 **/

12
13
#define CONFIG_PRIVATE

Roger Dingledine's avatar
Roger Dingledine committed
14
#include "or.h"
15
16
17
#ifdef MS_WINDOWS
#include <shlobj.h>
#endif
Roger Dingledine's avatar
Roger Dingledine committed
18

Nick Mathewson's avatar
Nick Mathewson committed
19
20
/** Enumeration of types which option values can take */
typedef enum config_type_t {
21
  CONFIG_TYPE_STRING = 0,   /**< An arbitrary string. */
22
  CONFIG_TYPE_FILENAME,     /**< A filename: some prefixes get expanded. */
23
  CONFIG_TYPE_UINT,         /**< A non-negative integer less than MAX_INT */
24
25
  CONFIG_TYPE_INTERVAL,     /**< A number of seconds, with optional units*/
  CONFIG_TYPE_MEMUNIT,      /**< A number of bytes, with optional units*/
26
27
  CONFIG_TYPE_DOUBLE,       /**< A floating-point value */
  CONFIG_TYPE_BOOL,         /**< A boolean value, expressed as 0 or 1. */
Nick Mathewson's avatar
Nick Mathewson committed
28
  CONFIG_TYPE_ISOTIME,      /**< An ISO-formatted time relative to GMT. */
29
30
  CONFIG_TYPE_CSV,          /**< A list of strings, separated by commas and
                              * optional whitespace. */
31
  CONFIG_TYPE_LINELIST,     /**< Uninterpreted config lines */
32
33
34
35
36
  CONFIG_TYPE_LINELIST_S,   /**< Uninterpreted, context-sensitive config lines,
                             * mixed with other keywords. */
  CONFIG_TYPE_LINELIST_V,   /**< Catch-all "virtual" option to summarize
                             * context-sensitive config lines when fetching.
                             */
37
38
  CONFIG_TYPE_ROUTERSET,    /**< A list of router names, addrs, and fps,
                             * parsed into a routerset_t. */
39
  CONFIG_TYPE_OBSOLETE,     /**< Obsolete (ignored) option. */
Nick Mathewson's avatar
Nick Mathewson committed
40
} config_type_t;
41

42
/** An abbreviation for a configuration option allowed on the command line. */
43
typedef struct config_abbrev_t {
44
45
  const char *abbreviated;
  const char *full;
46
  int commandline_only;
47
  int warn;
48
49
} config_abbrev_t;

50
51
/* Handy macro for declaring "In the config file or on the command line,
 * you can abbreviate <b>tok</b>s as <b>tok</b>". */
52
#define PLURAL(tok) { #tok, #tok "s", 0, 0 }
53

54
55
/** A list of abbreviations and aliases to map command-line options, obsolete
 * option names, or alternative option names, to their current values. */
56
static config_abbrev_t _option_abbrevs[] = {
57
  PLURAL(ExitNode),
58
  PLURAL(EntryNode),
59
60
  PLURAL(ExcludeNode),
  PLURAL(FirewallPort),
61
  PLURAL(LongLivedPort),
62
63
  PLURAL(HiddenServiceNode),
  PLURAL(HiddenServiceExcludeNode),
64
  PLURAL(NumCpu),
65
66
  PLURAL(RendNode),
  PLURAL(RendExcludeNode),
67
68
  PLURAL(StrictEntryNode),
  PLURAL(StrictExitNode),
69
  PLURAL(StrictNode),
70
  { "l", "Log", 1, 0},
71
  { "AllowUnverifiedNodes", "AllowInvalidNodes", 0, 0},
72
73
  { "AutomapHostSuffixes", "AutomapHostsSuffixes", 0, 0},
  { "AutomapHostOnResolve", "AutomapHostsOnResolve", 0, 0},
74
75
76
77
  { "BandwidthRateBytes", "BandwidthRate", 0, 0},
  { "BandwidthBurstBytes", "BandwidthBurst", 0, 0},
  { "DirFetchPostPeriod", "StatusFetchPeriod", 0, 0},
  { "MaxConn", "ConnLimit", 0, 1},
78
79
80
  { "ORBindAddress", "ORListenAddress", 0, 0},
  { "DirBindAddress", "DirListenAddress", 0, 0},
  { "SocksBindAddress", "SocksListenAddress", 0, 0},
81
82
83
84
  { "UseHelperNodes", "UseEntryGuards", 0, 0},
  { "NumHelperNodes", "NumEntryGuards", 0, 0},
  { "UseEntryNodes", "UseEntryGuards", 0, 0},
  { "NumEntryNodes", "NumEntryGuards", 0, 0},
85
86
  { "ResolvConf", "ServerDNSResolvConfFile", 0, 1},
  { "SearchDomains", "ServerDNSSearchDomains", 0, 1},
87
  { "ServerDNSAllowBrokenResolvConf", "ServerDNSAllowBrokenConfig", 0, 0},
88
  { "PreferTunnelledDirConns", "PreferTunneledDirConns", 0, 0},
89
  { "BridgeAuthoritativeDirectory", "BridgeAuthoritativeDir", 0, 0},
90
  { "HashedControlPassword", "__HashedControlSessionPassword", 1, 0},
91
92
  { "StrictEntryNodes", "StrictNodes", 0, 1},
  { "StrictExitNodes", "StrictNodes", 0, 1},
93
94
  { NULL, NULL, 0, 0},
};
95
96

/** A list of state-file "abbreviations," for compatibility. */
97
static config_abbrev_t _state_abbrevs[] = {
98
  { "AccountingBytesReadInterval", "AccountingBytesReadInInterval", 0, 0 },
99
100
101
102
103
104
  { "HelperNode", "EntryGuard", 0, 0 },
  { "HelperNodeDownSince", "EntryGuardDownSince", 0, 0 },
  { "HelperNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
  { "EntryNode", "EntryGuard", 0, 0 },
  { "EntryNodeDownSince", "EntryGuardDownSince", 0, 0 },
  { "EntryNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
105
  { NULL, NULL, 0, 0},
106
};
107
#undef PLURAL
108

109
/** A variable allowed in the configuration file or on the command line. */
110
typedef struct config_var_t {
111
  const char *name; /**< The full keyword (case insensitive). */
112
113
  config_type_t type; /**< How to interpret the type and turn it into a
                       * value. */
114
115
  off_t var_offset; /**< Offset of the corresponding member of or_options_t. */
  const char *initvalue; /**< String (or null) describing initial value. */
116
117
} config_var_t;

Nick Mathewson's avatar
Nick Mathewson committed
118
119
120
121
/** An entry for config_vars: "The option <b>name</b> has type
 * CONFIG_TYPE_<b>conftype</b>, and corresponds to
 * or_options_t.<b>member</b>"
 */
122
123
#define VAR(name,conftype,member,initvalue)                             \
  { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_options_t, member), \
124
      initvalue }
125
126
127
/** As VAR, but the option name and member name are the same. */
#define V(member,conftype,initvalue)                                    \
  VAR(#member, conftype, member, initvalue)
Nick Mathewson's avatar
Nick Mathewson committed
128
/** An entry for config_vars: "The option <b>name</b> is obsolete." */
129
#define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL }
130

Nick Mathewson's avatar
Nick Mathewson committed
131
132
133
134
/** Array of configuration options.  Until we disallow nonstandard
 * abbreviations, order is significant, since the first matching option will
 * be chosen first.
 */
135
static config_var_t _option_vars[] = {
136
  OBSOLETE("AccountingMaxKB"),
137
138
139
  V(AccountingMax,               MEMUNIT,  "0 bytes"),
  V(AccountingStart,             STRING,   NULL),
  V(Address,                     STRING,   NULL),
140
  V(AllowDotExit,                BOOL,     "0"),
141
142
  V(AllowInvalidNodes,           CSV,      "middle,rendezvous"),
  V(AllowNonRFC953Hostnames,     BOOL,     "0"),
143
144
  V(AllowSingleHopCircuits,      BOOL,     "0"),
  V(AllowSingleHopExits,         BOOL,     "0"),
145
146
147
  V(AlternateBridgeAuthority,    LINELIST, NULL),
  V(AlternateDirAuthority,       LINELIST, NULL),
  V(AlternateHSAuthority,        LINELIST, NULL),
148
  V(AssumeReachable,             BOOL,     "0"),
149
  V(AuthDirBadDir,               LINELIST, NULL),
150
151
152
153
  V(AuthDirBadExit,              LINELIST, NULL),
  V(AuthDirInvalid,              LINELIST, NULL),
  V(AuthDirReject,               LINELIST, NULL),
  V(AuthDirRejectUnlisted,       BOOL,     "0"),
154
  V(AuthDirListBadDirs,          BOOL,     "0"),
155
  V(AuthDirListBadExits,         BOOL,     "0"),
156
157
  V(AuthDirMaxServersPerAddr,    UINT,     "2"),
  V(AuthDirMaxServersPerAuthAddr,UINT,     "5"),
158
159
160
161
  VAR("AuthoritativeDirectory",  BOOL, AuthoritativeDir,    "0"),
  V(AutomapHostsOnResolve,       BOOL,     "0"),
  V(AutomapHostsSuffixes,        CSV,      ".onion,.exit"),
  V(AvoidDiskWrites,             BOOL,     "0"),
162
163
  V(BandwidthBurst,              MEMUNIT,  "10 MB"),
  V(BandwidthRate,               MEMUNIT,  "5 MB"),
164
165
  V(BridgeAuthoritativeDir,      BOOL,     "0"),
  VAR("Bridge",                  LINELIST, Bridges,    NULL),
166
  V(BridgePassword,              STRING,   NULL),
167
  V(BridgeRecordUsageByCountry,  BOOL,     "1"),
168
  V(BridgeRelay,                 BOOL,     "0"),
169
  V(CellStatistics,              BOOL,     "0"),
170
  V(LearnCircuitBuildTimeout,    BOOL,     "1"),
171
  V(CircuitBuildTimeout,         INTERVAL, "0"),
172
  V(CircuitIdleTimeout,          INTERVAL, "1 hour"),
173
  V(CircuitStreamTimeout,        INTERVAL, "0"),
174
  V(CircuitPriorityHalflife,     DOUBLE,  "-100.0"), /*negative:'Use default'*/
175
176
  V(ClientDNSRejectInternalAddresses, BOOL,"1"),
  V(ClientOnly,                  BOOL,     "0"),
177
  V(ConsensusParams,             STRING,   NULL),
178
179
180
181
182
183
184
185
186
187
  V(ConnLimit,                   UINT,     "1000"),
  V(ConstrainedSockets,          BOOL,     "0"),
  V(ConstrainedSockSize,         MEMUNIT,  "8192"),
  V(ContactInfo,                 STRING,   NULL),
  V(ControlListenAddress,        LINELIST, NULL),
  V(ControlPort,                 UINT,     "0"),
  V(ControlSocket,               LINELIST, NULL),
  V(CookieAuthentication,        BOOL,     "0"),
  V(CookieAuthFileGroupReadable, BOOL,     "0"),
  V(CookieAuthFile,              STRING,   NULL),
188
  V(DataDirectory,               FILENAME, NULL),
189
  OBSOLETE("DebugLogFile"),
190
  V(DirAllowPrivateAddresses,    BOOL,     NULL),
191
  V(TestingAuthDirTimeToLearnReachability, INTERVAL, "30 minutes"),
192
  V(DirListenAddress,            LINELIST, NULL),
193
  OBSOLETE("DirFetchPeriod"),
194
195
  V(DirPolicy,                   LINELIST, NULL),
  V(DirPort,                     UINT,     "0"),
196
  V(DirPortFrontPage,            FILENAME, NULL),
197
  OBSOLETE("DirPostPeriod"),
198
199
200
201
  OBSOLETE("DirRecordUsageByCountry"),
  OBSOLETE("DirRecordUsageGranularity"),
  OBSOLETE("DirRecordUsageRetainIPs"),
  OBSOLETE("DirRecordUsageSaveInterval"),
Karsten Loesing's avatar
Karsten Loesing committed
202
  V(DirReqStatistics,            BOOL,     "0"),
203
  VAR("DirServer",               LINELIST, DirServers, NULL),
204
  V(DisableAllSwap,              BOOL,     "0"),
205
206
207
208
  V(DNSPort,                     UINT,     "0"),
  V(DNSListenAddress,            LINELIST, NULL),
  V(DownloadExtraInfo,           BOOL,     "0"),
  V(EnforceDistinctSubnets,      BOOL,     "1"),
209
  V(EntryNodes,                  ROUTERSET,   NULL),
210
  V(EntryStatistics,             BOOL,     "0"),
211
  V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "10 minutes"),
212
213
  V(ExcludeNodes,                ROUTERSET, NULL),
  V(ExcludeExitNodes,            ROUTERSET, NULL),
214
  V(ExcludeSingleHopRelays,      BOOL,     "1"),
215
  V(ExitNodes,                   ROUTERSET, NULL),
216
217
  V(ExitPolicy,                  LINELIST, NULL),
  V(ExitPolicyRejectPrivate,     BOOL,     "1"),
218
  V(ExitPortStatistics,          BOOL,     "0"),
219
  V(ExtraInfoStatistics,         BOOL,     "0"),
220

221
  V(FallbackNetworkstatusFile,   FILENAME,
222
    SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "fallback-consensus"),
223
224
225
  V(FascistFirewall,             BOOL,     "0"),
  V(FirewallPorts,               CSV,      ""),
  V(FastFirstHopPK,              BOOL,     "1"),
226
  V(FetchDirInfoEarly,           BOOL,     "0"),
227
  V(FetchDirInfoExtraEarly,      BOOL,     "0"),
228
229
230
  V(FetchServerDescriptors,      BOOL,     "1"),
  V(FetchHidServDescriptors,     BOOL,     "1"),
  V(FetchUselessDescriptors,     BOOL,     "0"),
231
#ifdef WIN32
232
  V(GeoIPFile,                   FILENAME, "<default>"),
233
#else
234
235
  V(GeoIPFile,                   FILENAME,
    SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip"),
236
#endif
237
  OBSOLETE("Group"),
238
  V(HardwareAccel,               BOOL,     "0"),
239
240
  V(AccelName,                   STRING,   NULL),
  V(AccelDir,                    FILENAME, NULL),
241
  V(HashedControlPassword,       LINELIST, NULL),
242
  V(HidServDirectoryV2,          BOOL,     "1"),
Nick Mathewson's avatar
Nick Mathewson committed
243
  VAR("HiddenServiceDir",    LINELIST_S, RendConfigLines,    NULL),
244
245
  OBSOLETE("HiddenServiceExcludeNodes"),
  OBSOLETE("HiddenServiceNodes"),
Nick Mathewson's avatar
Nick Mathewson committed
246
247
  VAR("HiddenServiceOptions",LINELIST_V, RendConfigLines,    NULL),
  VAR("HiddenServicePort",   LINELIST_S, RendConfigLines,    NULL),
248
  VAR("HiddenServiceVersion",LINELIST_S, RendConfigLines,    NULL),
249
  VAR("HiddenServiceAuthorizeClient",LINELIST_S,RendConfigLines, NULL),
250
  V(HidServAuth,                 LINELIST, NULL),
251
  V(HSAuthoritativeDir,          BOOL,     "0"),
252
  OBSOLETE("HSAuthorityRecordStats"),
253
254
255
256
  V(HttpProxy,                   STRING,   NULL),
  V(HttpProxyAuthenticator,      STRING,   NULL),
  V(HttpsProxy,                  STRING,   NULL),
  V(HttpsProxyAuthenticator,     STRING,   NULL),
257
258
259
260
  V(Socks4Proxy,                 STRING,   NULL),
  V(Socks5Proxy,                 STRING,   NULL),
  V(Socks5ProxyUsername,         STRING,   NULL),
  V(Socks5ProxyPassword,         STRING,   NULL),
261
  OBSOLETE("IgnoreVersion"),
262
263
  V(KeepalivePeriod,             INTERVAL, "5 minutes"),
  VAR("Log",                     LINELIST, Logs,             NULL),
264
  OBSOLETE("LinkPadding"),
265
266
  OBSOLETE("LogLevel"),
  OBSOLETE("LogFile"),
267
  V(LongLivedPorts,              CSV,
268
                         "21,22,706,1863,5050,5190,5222,5223,6667,6697,8300"),
269
270
271
272
  VAR("MapAddress",              LINELIST, AddressMap,           NULL),
  V(MaxAdvertisedBandwidth,      MEMUNIT,  "1 GB"),
  V(MaxCircuitDirtiness,         INTERVAL, "10 minutes"),
  V(MaxOnionsPending,            UINT,     "100"),
273
  OBSOLETE("MonthlyAccountingStart"),
274
275
  V(MyFamily,                    STRING,   NULL),
  V(NewCircuitPeriod,            INTERVAL, "30 seconds"),
276
  VAR("NamingAuthoritativeDirectory",BOOL, NamingAuthoritativeDir, "0"),
277
278
279
280
281
282
283
284
285
286
  V(NatdListenAddress,           LINELIST, NULL),
  V(NatdPort,                    UINT,     "0"),
  V(Nickname,                    STRING,   NULL),
  V(NoPublish,                   BOOL,     "0"),
  VAR("NodeFamily",              LINELIST, NodeFamilies,         NULL),
  V(NumCpus,                     UINT,     "1"),
  V(NumEntryGuards,              UINT,     "3"),
  V(ORListenAddress,             LINELIST, NULL),
  V(ORPort,                      UINT,     "0"),
  V(OutboundBindAddress,         STRING,   NULL),
287
  OBSOLETE("PathlenCoinWeight"),
288
289
  V(PerConnBWBurst,              MEMUNIT,  "0"),
  V(PerConnBWRate,               MEMUNIT,  "0"),
290
  V(PidFile,                     STRING,   NULL),
291
  V(TestingTorNetwork,           BOOL,     "0"),
Roger Dingledine's avatar
Roger Dingledine committed
292
  V(PreferTunneledDirConns,      BOOL,     "1"),
293
  V(ProtocolWarnings,            BOOL,     "0"),
294
  V(PublishServerDescriptor,     CSV,      "1"),
295
296
297
298
299
300
301
  V(PublishHidServDescriptors,   BOOL,     "1"),
  V(ReachableAddresses,          LINELIST, NULL),
  V(ReachableDirAddresses,       LINELIST, NULL),
  V(ReachableORAddresses,        LINELIST, NULL),
  V(RecommendedVersions,         LINELIST, NULL),
  V(RecommendedClientVersions,   LINELIST, NULL),
  V(RecommendedServerVersions,   LINELIST, NULL),
302
  OBSOLETE("RedirectExit"),
303
  V(RefuseUnknownExits,          BOOL,     "0"),
304
  V(RejectPlaintextPorts,        CSV,      ""),
305
306
  V(RelayBandwidthBurst,         MEMUNIT,  "0"),
  V(RelayBandwidthRate,          MEMUNIT,  "0"),
307
308
  OBSOLETE("RendExcludeNodes"),
  OBSOLETE("RendNodes"),
309
310
  V(RendPostPeriod,              INTERVAL, "1 hour"),
  V(RephistTrackTime,            INTERVAL, "24 hours"),
311
  OBSOLETE("RouterFile"),
312
313
  V(RunAsDaemon,                 BOOL,     "0"),
  V(RunTesting,                  BOOL,     "0"),
314
  V(SafeLogging,                 STRING,   "1"),
315
  V(SafeSocks,                   BOOL,     "0"),
316
  V(ServerDNSAllowBrokenConfig,  BOOL,     "1"),
317
318
  V(ServerDNSAllowNonRFC953Hostnames, BOOL,"0"),
  V(ServerDNSDetectHijacking,    BOOL,     "1"),
319
  V(ServerDNSRandomizeCase,      BOOL,     "1"),
320
321
322
  V(ServerDNSResolvConfFile,     STRING,   NULL),
  V(ServerDNSSearchDomains,      BOOL,     "0"),
  V(ServerDNSTestAddresses,      CSV,
323
      "www.google.com,www.mit.edu,www.yahoo.com,www.slashdot.org"),
324
325
326
327
328
  V(ShutdownWaitLength,          INTERVAL, "30 seconds"),
  V(SocksListenAddress,          LINELIST, NULL),
  V(SocksPolicy,                 LINELIST, NULL),
  V(SocksPort,                   UINT,     "9050"),
  V(SocksTimeout,                INTERVAL, "2 minutes"),
329
  OBSOLETE("StatusFetchPeriod"),
330
  V(StrictNodes,                 BOOL,     "0"),
331
  OBSOLETE("SysLog"),
332
  V(TestSocks,                   BOOL,     "0"),
333
  OBSOLETE("TestVia"),
334
335
  V(TrackHostExits,              CSV,      NULL),
  V(TrackHostExitsExpire,        INTERVAL, "30 minutes"),
336
  OBSOLETE("TrafficShaping"),
337
338
  V(TransListenAddress,          LINELIST, NULL),
  V(TransPort,                   UINT,     "0"),
Roger Dingledine's avatar
Roger Dingledine committed
339
  V(TunnelDirConns,              BOOL,     "1"),
340
341
342
343
  V(UpdateBridgesFromAuthority,  BOOL,     "0"),
  V(UseBridges,                  BOOL,     "0"),
  V(UseEntryGuards,              BOOL,     "1"),
  V(User,                        STRING,   NULL),
344
  VAR("V1AuthoritativeDirectory",BOOL, V1AuthoritativeDir,   "0"),
345
  VAR("V2AuthoritativeDirectory",BOOL, V2AuthoritativeDir,   "0"),
346
  VAR("V3AuthoritativeDirectory",BOOL, V3AuthoritativeDir,   "0"),
347
348
349
  V(TestingV3AuthInitialVotingInterval, INTERVAL, "30 minutes"),
  V(TestingV3AuthInitialVoteDelay, INTERVAL, "5 minutes"),
  V(TestingV3AuthInitialDistDelay, INTERVAL, "5 minutes"),
350
351
352
353
  V(V3AuthVotingInterval,        INTERVAL, "1 hour"),
  V(V3AuthVoteDelay,             INTERVAL, "5 minutes"),
  V(V3AuthDistDelay,             INTERVAL, "5 minutes"),
  V(V3AuthNIntervalsValid,       UINT,     "3"),
354
  V(V3AuthUseLegacyKey,          BOOL,     "0"),
355
  V(V3BandwidthsFile,            FILENAME, NULL),
356
  VAR("VersioningAuthoritativeDirectory",BOOL,VersioningAuthoritativeDir, "0"),
357
  V(VirtualAddrNetwork,          STRING,   "127.192.0.0/10"),
358
  V(WarnPlaintextPorts,          CSV,      "23,109,110,143"),
359
  VAR("__ReloadTorrcOnSIGHUP",   BOOL,  ReloadTorrcOnSIGHUP,      "1"),
360
361
362
  VAR("__AllDirActionsPrivate",  BOOL,  AllDirActionsPrivate,     "0"),
  VAR("__DisablePredictedCircuits",BOOL,DisablePredictedCircuits, "0"),
  VAR("__LeaveStreamsUnattached",BOOL,  LeaveStreamsUnattached,   "0"),
363
364
  VAR("__HashedControlSessionPassword", LINELIST, HashedControlSessionPassword,
      NULL),
365
  V(MinUptimeHidServDirectoryV2, INTERVAL, "24 hours"),
366

367
  { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
368
};
369

370
371
/** Override default values with these if the user sets the TestingTorNetwork
 * option. */
372
static config_var_t testing_tor_network_defaults[] = {
373
  V(ServerDNSAllowBrokenConfig,  BOOL,  "1"),
374
375
376
377
378
379
380
381
382
383
  V(DirAllowPrivateAddresses,    BOOL,     "1"),
  V(EnforceDistinctSubnets,      BOOL,     "0"),
  V(AssumeReachable,             BOOL,     "1"),
  V(AuthDirMaxServersPerAddr,    UINT,     "0"),
  V(AuthDirMaxServersPerAuthAddr,UINT,     "0"),
  V(ClientDNSRejectInternalAddresses, BOOL,"0"),
  V(ExitPolicyRejectPrivate,     BOOL,     "0"),
  V(V3AuthVotingInterval,        INTERVAL, "5 minutes"),
  V(V3AuthVoteDelay,             INTERVAL, "20 seconds"),
  V(V3AuthDistDelay,             INTERVAL, "20 seconds"),
384
385
386
387
388
  V(TestingV3AuthInitialVotingInterval, INTERVAL, "5 minutes"),
  V(TestingV3AuthInitialVoteDelay, INTERVAL, "20 seconds"),
  V(TestingV3AuthInitialDistDelay, INTERVAL, "20 seconds"),
  V(TestingAuthDirTimeToLearnReachability, INTERVAL, "0 minutes"),
  V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "0 minutes"),
389
390
  { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
};
391
392
#undef VAR

393
394
#define VAR(name,conftype,member,initvalue)                             \
  { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_state_t, member),  \
395
      initvalue }
396
397

/** Array of "state" variables saved to the ~/.tor/state file. */
398
static config_var_t _state_vars[] = {
399
400
401
402
403
  V(AccountingBytesReadInInterval,    MEMUNIT,  NULL),
  V(AccountingBytesWrittenInInterval, MEMUNIT,  NULL),
  V(AccountingExpectedUsage,          MEMUNIT,  NULL),
  V(AccountingIntervalStart,          ISOTIME,  NULL),
  V(AccountingSecondsActive,          INTERVAL, NULL),
Roger Dingledine's avatar
Roger Dingledine committed
404

405
406
407
  VAR("EntryGuard",              LINELIST_S,  EntryGuards,             NULL),
  VAR("EntryGuardDownSince",     LINELIST_S,  EntryGuards,             NULL),
  VAR("EntryGuardUnlistedSince", LINELIST_S,  EntryGuards,             NULL),
408
  VAR("EntryGuardAddedBy",       LINELIST_S,  EntryGuards,             NULL),
409
  V(EntryGuards,                 LINELIST_V,  NULL),
Nick Mathewson's avatar
Nick Mathewson committed
410

411
412
413
414
415
416
  V(BWHistoryReadEnds,                ISOTIME,  NULL),
  V(BWHistoryReadInterval,            UINT,     "900"),
  V(BWHistoryReadValues,              CSV,      ""),
  V(BWHistoryWriteEnds,               ISOTIME,  NULL),
  V(BWHistoryWriteInterval,           UINT,     "900"),
  V(BWHistoryWriteValues,             CSV,      ""),
417

418
  V(TorVersion,                       STRING,   NULL),
419

420
421
  V(LastRotatedOnionKey,              ISOTIME,  NULL),
  V(LastWritten,                      ISOTIME,  NULL),
422

423
  V(TotalBuildTimes,                  UINT,     NULL),
Mike Perry's avatar
Mike Perry committed
424
  V(CircuitBuildTimeoutCount,         UINT,     "0"),
425
426
  VAR("CircuitBuildTimeBin",          LINELIST_S, BuildtimeHistogram, NULL),
  VAR("BuildtimeHistogram",           LINELIST_V, BuildtimeHistogram, NULL),
427

428
  { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
429
430
};

431
#undef VAR
432
#undef V
433
434
#undef OBSOLETE

435
436
/** Represents an English description of a configuration variable; used when
 * generating configuration file comments. */
437
438
439
440
441
typedef struct config_var_description_t {
  const char *name;
  const char *description;
} config_var_description_t;

442
/** Type of a callback to validate whether a given configuration is
Roger Dingledine's avatar
Roger Dingledine committed
443
 * well-formed and consistent. See options_trial_assign() for documentation
444
 * of arguments. */
445
typedef int (*validate_fn_t)(void*,void*,int,char**);
446

447
448
449
/** Information on the keys, value types, key-to-struct-member mappings,
 * variable descriptions, validation functions, and abbreviations for a
 * configuration or storage format. */
450
typedef struct {
451
452
453
  size_t size; /**< Size of the struct that everything gets parsed into. */
  uint32_t magic; /**< Required 'magic value' to make sure we have a struct
                   * of the right type. */
Roger Dingledine's avatar
Roger Dingledine committed
454
  off_t magic_offset; /**< Offset of the magic value within the struct. */
455
  config_abbrev_t *abbrevs; /**< List of abbreviations that we expand when
Roger Dingledine's avatar
Roger Dingledine committed
456
                             * parsing this format. */
457
458
459
  config_var_t *vars; /**< List of variables we recognize, their default
                       * values, and where we stick them in the structure. */
  validate_fn_t validate_fn; /**< Function to validate config. */
Roger Dingledine's avatar
Roger Dingledine committed
460
461
462
  /** If present, extra is a LINELIST variable for unrecognized
   * lines.  Otherwise, unrecognized lines are an error. */
  config_var_t *extra;
463
464
} config_format_t;

465
466
/** Macro: assert that <b>cfg</b> has the right magic field for format
 * <b>fmt</b>. */
467
#define CHECK(fmt, cfg) STMT_BEGIN                                      \
468
    tor_assert(fmt && cfg);                                             \
469
    tor_assert((fmt)->magic ==                                          \
470
               *(uint32_t*)STRUCT_VAR_P(cfg,fmt->magic_offset));        \
471
  STMT_END
472

473
474
475
#ifdef MS_WINDOWS
static char *get_windows_conf_root(void);
#endif
476
static void config_line_append(config_line_t **lst,
477
                               const char *key, const char *val);
478
479
static void option_clear(config_format_t *fmt, or_options_t *options,
                         config_var_t *var);
480
static void option_reset(config_format_t *fmt, or_options_t *options,
481
                         config_var_t *var, int use_defaults);
482
static void config_free(config_format_t *fmt, void *options);
483
static int config_lines_eq(config_line_t *a, config_line_t *b);
484
static int option_is_same(config_format_t *fmt,
485
486
                          or_options_t *o1, or_options_t *o2,
                          const char *name);
487
static or_options_t *options_dup(config_format_t *fmt, or_options_t *old);
488
489
490
static int options_validate(or_options_t *old_options, or_options_t *options,
                            int from_setconf, char **msg);
static int options_act_reversible(or_options_t *old_options, char **msg);
491
static int options_act(or_options_t *old_options);
492
493
static int options_transition_allowed(or_options_t *old, or_options_t *new,
                                      char **msg);
494
495
496
497
static int options_transition_affects_workers(or_options_t *old_options,
                                              or_options_t *new_options);
static int options_transition_affects_descriptor(or_options_t *old_options,
                                                 or_options_t *new_options);
498
static int check_nickname_list(const char *lst, const char *name, char **msg);
499
static void config_register_addressmaps(or_options_t *options);
500

501
static int parse_bridge_line(const char *line, int validate_only);
502
503
504
static int parse_dir_server_line(const char *line,
                                 authority_type_t required_type,
                                 int validate_only);
505
static int validate_data_directory(or_options_t *options);
506
static int write_configuration_file(const char *fname, or_options_t *options);
507
static config_line_t *get_assigned_option(config_format_t *fmt,
508
509
                                          void *options, const char *key,
                                          int escape_val);
510
static void config_init(config_format_t *fmt, void *options);
511
static int or_state_validate(or_state_t *old_options, or_state_t *options,
512
                             int from_setconf, char **msg);
513
514
static int or_state_load(void);
static int options_init_logs(or_options_t *options, int validate_only);
515

516
517
518
static int is_listening_on_low_port(uint16_t port_option,
                                    const config_line_t *listen_options);

519
520
static uint64_t config_parse_memunit(const char *s, int *ok);
static int config_parse_interval(const char *s, int *ok);
521
static void init_libevent(void);
522
static int opt_streq(const char *s1, const char *s2);
523

524
/** Magic value for or_options_t. */
525
526
#define OR_OPTIONS_MAGIC 9090909

527
/** Configuration format for or_options_t. */
528
static config_format_t options_format = {
529
530
531
  sizeof(or_options_t),
  OR_OPTIONS_MAGIC,
  STRUCT_OFFSET(or_options_t, _magic),
532
533
534
  _option_abbrevs,
  _option_vars,
  (validate_fn_t)options_validate,
535
  NULL
536
537
};

538
/** Magic value for or_state_t. */
539
540
#define OR_STATE_MAGIC 0x57A73f57

541
542
/** "Extra" variable in the state that receives lines we can't parse. This
 * lets us preserve options from versions of Tor newer than us. */
543
544
545
546
static config_var_t state_extra_var = {
  "__extra", CONFIG_TYPE_LINELIST, STRUCT_OFFSET(or_state_t, ExtraLines), NULL
};

547
/** Configuration format for or_state_t. */
548
549
550
551
static config_format_t state_format = {
  sizeof(or_state_t),
  OR_STATE_MAGIC,
  STRUCT_OFFSET(or_state_t, _magic),
552
  _state_abbrevs,
553
554
  _state_vars,
  (validate_fn_t)or_state_validate,
555
  &state_extra_var,
556
557
};

558
559
560
561
562
/*
 * Functions to read and write the global options pointer.
 */

/** Command-line and config-file options. */
563
static or_options_t *global_options = NULL;
Roger Dingledine's avatar
Roger Dingledine committed
564
/** Name of most recently read torrc file. */
565
static char *torrc_fname = NULL;
566
/** Persistent serialized state. */
567
static or_state_t *global_state = NULL;
568
569
/** Configuration Options set by command line. */
static config_line_t *global_cmdline_options = NULL;
Roger Dingledine's avatar
Roger Dingledine committed
570
/** Contents of most recently read DirPortFrontPage file. */
571
572
573
574
575
576
577
578
static char *global_dirfrontpagecontents = NULL;

/** Return the contents of our frontpage string, or NULL if not configured. */
const char *
get_dirportfrontpage(void)
{
  return global_dirfrontpagecontents;
}
579

580
/** Allocate an empty configuration object of a given format type. */
581
582
583
static void *
config_alloc(config_format_t *fmt)
{
584
  void *opts = tor_malloc_zero(fmt->size);
585
  *(uint32_t*)STRUCT_VAR_P(opts, fmt->magic_offset) = fmt->magic;
586
587
588
589
  CHECK(fmt, opts);
  return opts;
}

590
591
/** Return the currently configured options. */
or_options_t *
592
593
get_options(void)
{
594
595
596
  tor_assert(global_options);
  return global_options;
}
597

598
599
/** Change the current global options to contain <b>new_val</b> instead of
 * their current value; take action based on the new value; free the old value
600
 * as necessary.  Returns 0 on success, -1 on failure.
601
 */
602
int
603
set_options(or_options_t *new_val, char **msg)
604
{
605
  or_options_t *old_options = global_options;
606
  global_options = new_val;
607
608
  /* Note that we pass the *old* options below, for comparison. It
   * pulls the new options directly out of global_options. */
609
610
  if (options_act_reversible(old_options, msg)<0) {
    tor_assert(*msg);
611
612
613
    global_options = old_options;
    return -1;
  }
614
  if (options_act(old_options) < 0) { /* acting on the options failed. die. */
615
    log_err(LD_BUG,
Roger Dingledine's avatar
Roger Dingledine committed
616
            "Acting on config options left us in a broken state. Dying.");
617
618
    exit(1);
  }
619
620

  config_free(&options_format, old_options);
621
622

  return 0;
623
624
}

625
extern const char tor_git_revision[]; /* from tor_main.c */
626

627
/** The version of this Tor process, as parsed. */
628
629
static char *_version = NULL;

630
/** Return the current Tor version. */
631
632
633
const char *
get_version(void)
{
634
  if (_version == NULL) {
635
636
    if (strlen(tor_git_revision)) {
      size_t len = strlen(VERSION)+strlen(tor_git_revision)+16;
637
      _version = tor_malloc(len);
638
      tor_snprintf(_version, len, "%s (git-%s)", VERSION, tor_git_revision);
639
    } else {
640
      _version = tor_strdup(VERSION);
641
642
    }
  }
643
  return _version;
644
645
}

646
647
648
649
650
/** Release additional memory allocated in options
 */
static void
or_options_free(or_options_t *options)
{
651
652
653
  if (!options)
    return;

654
  routerset_free(options->_ExcludeExitNodesUnion);
655
656
657
  config_free(&options_format, options);
}

658
659
/** Release all memory and resources held by global configuration structures.
 */
660
661
662
void
config_free_all(void)
{
663
664
665
666
667
668
669
670
671
  or_options_free(global_options);
  global_options = NULL;

  config_free(&state_format, global_state);
  global_state = NULL;

  config_free_lines(global_cmdline_options);
  global_cmdline_options = NULL;

672
  tor_free(torrc_fname);
673
  tor_free(_version);
674
  tor_free(global_dirfrontpagecontents);
675
676
}

677
678
679
680
681
/** Make <b>address</b> -- a piece of information related to our operation as
 * a client -- safe to log according to the settings in options->SafeLogging,
 * and return it.
 *
 * (We return "[scrubbed]" if SafeLogging is "1", and address otherwise.)
682
683
 */
const char *
684
safe_str_client(const char *address)
685
{
686
  tor_assert(address);
687
  if (get_options()->_SafeLogging == SAFELOG_SCRUB_ALL)
688
689
690
691
692
    return "[scrubbed]";
  else
    return address;
}

693
694
695
696
697
698
/** Make <b>address</b> -- a piece of information of unspecified sensitivity
 * -- safe to log according to the settings in options->SafeLogging, and
 * return it.
 *
 * (We return "[scrubbed]" if SafeLogging is anything besides "0", and address
 * otherwise.)
699
700
 */
const char *
701
702
safe_str(const char *address)
{
703
  tor_assert(address);
704
  if (get_options()->_SafeLogging != SAFELOG_SCRUB_NONE)
705
706
707
708
709
    return "[scrubbed]";
  else
    return address;
}

710
/** Equivalent to escaped(safe_str_client(address)).  See reentrancy note on
711
712
 * escaped(): don't use this outside the main thread, or twice in the same
 * log statement. */
713
const char *
714
escaped_safe_str_client(const char *address)
715
{
716
  if (get_options()->_SafeLogging == SAFELOG_SCRUB_ALL)
717
718
719
720
721
    return "[scrubbed]";
  else
    return escaped(address);
}

722
/** Equivalent to escaped(safe_str(address)).  See reentrancy note on
723
724
 * escaped(): don't use this outside the main thread, or twice in the same
 * log statement. */
725
726
727
const char *
escaped_safe_str(const char *address)
{
728
  if (get_options()->_SafeLogging != SAFELOG_SCRUB_NONE)
729
730
731
732
733
    return "[scrubbed]";
  else
    return escaped(address);
}

734
735
/** Add the default directory authorities directly into the trusted dir list,
 * but only add them insofar as they share bits with <b>type</b>. */
736
static void
737
add_default_trusted_dir_authorities(authority_type_t type)
738
{
739
  int i;
740
  const char *dirservers[] = {
741
742
743
    "moria1 orport=9101 no-v2 "
      "v3ident=D586D18309DED4CD6D57C18FDB97EFA96D330566 "
      "128.31.0.39:9131 9695 DFC3 5FFE B861 329B 9F1A B04C 4639 7020 CE31",
744
    "tor26 v1 orport=443 v3ident=14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4 "
Peter Palfrader's avatar
Peter Palfrader committed
745
      "86.59.21.38:80 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D",
Roger Dingledine's avatar
Roger Dingledine committed
746
747
    "dizum orport=443 v3ident=E8A9C45EDE6D711294FADF8E7951F4DE6CA56B58 "
      "194.109.206.212:80 7EA6 EAD6 FD83 083C 538F 4403 8BBF A077 587D D755",
748
    "Tonga orport=443 bridge no-v2 82.94.251.203:80 "
749
      "4A0C CD2D DC79 9508 3D73 F5D6 6710 0C8A 5831 F16D",
750
751
    "ides orport=9090 no-v2 v3ident=27B6B5996C426270A5C95488AA5BCEB6BCC86956 "
      "216.224.124.114:9030 F397 038A DC51 3361 35E7 B80B D99C A384 4360 292B",
752
753
754
    "gabelmoo orport=8080 no-v2 "
      "v3ident=ED03BB616EB2F60BEC80151114BB25CEF515B226 "
      "80.190.246.100:8180 F204 4413 DAC2 E02E 3D6B CF47 35A1 9BCA 1DE9 7281",
755
756
    "dannenberg orport=443 no-v2 "
      "v3ident=585769C78764D58426B8B52B6651A5A71137189A "
757
      "193.23.244.244:80 7BE6 83E6 5D48 1413 21C5 ED92 F075 C553 64AC 7123",
758
759
    "urras orport=80 no-v2 v3ident=80550987E1D626E3EBA5E5E75A458DE0626D088C "
      "208.83.223.34:443 0AD3 FA88 4D18 F89E EA2D 89C0 1937 9E0E 7FD9 4417",
760
    NULL
761
  };
762
763
764
765
766
767
  for (i=0; dirservers[i]; i++) {
    if (parse_dir_server_line(dirservers[i], type, 0)<0) {
      log_err(LD_BUG, "Couldn't parse internal dirserver line %s",
              dirservers[i]);
    }
  }
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
}

/** Look at all the config options for using alternate directory
 * authorities, and make sure none of them are broken. Also, warn the
 * user if we changed any dangerous ones.
 */
static int
validate_dir_authorities(or_options_t *options, or_options_t *old_options)
{
  config_line_t *cl;

  if (options->DirServers &&
      (options->AlternateDirAuthority || options->AlternateBridgeAuthority ||
       options->AlternateHSAuthority)) {
    log_warn(LD_CONFIG,
             "You cannot set both DirServers and Alternate*Authority.");
    return -1;
  }

  /* do we want to complain to the user about being partitionable? */
  if ((options->DirServers &&
       (!old_options ||
        !config_lines_eq(options->DirServers, old_options->DirServers))) ||
      (options->AlternateDirAuthority &&
       (!old_options ||
        !config_lines_eq(options->AlternateDirAuthority,
                         old_options->AlternateDirAuthority)))) {
    log_warn(LD_CONFIG,
             "You have used DirServer or AlternateDirAuthority to "
             "specify alternate directory authorities in "
             "your configuration. This is potentially dangerous: it can "
             "make you look different from all other Tor users, and hurt "
             "your anonymity. Even if you've specified the same "
             "authorities as Tor uses by default, the defaults could "
             "change in the future. Be sure you know what you're doing.");
  }

  /* Now go through the four ways you can configure an alternate
   * set of directory authorities, and make sure none are broken. */
  for (cl = options->DirServers; cl; cl = cl->next)
808
    if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
809
810
      return -1;
  for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
811
    if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
812
813
      return -1;
  for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
814
    if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
815
816
      return -1;
  for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
817
    if (parse_dir_server_line(cl->value, NO_AUTHORITY, 1)<0)
818
819
820
821
822
823
824
825
826
827
828
829
830
      return -1;
  return 0;
}

/** Look at all the config options and assign new dir authorities
 * as appropriate.
 */
static int
consider_adding_dir_authorities(or_options_t *options,
                                or_options_t *old_options)
{
  config_line_t *cl;
  int need_to_update =
831
    !smartlist_len(router_get_trusted_dir_servers()) || !old_options ||
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
    !config_lines_eq(options->DirServers, old_options->DirServers) ||
    !config_lines_eq(options->AlternateBridgeAuthority,
                     old_options->AlternateBridgeAuthority) ||
    !config_lines_eq(options->AlternateDirAuthority,
                     old_options->AlternateDirAuthority) ||
    !config_lines_eq(options->AlternateHSAuthority,
                     old_options->AlternateHSAuthority);

  if (!need_to_update)
    return 0; /* all done */

  /* Start from a clean slate. */
  clear_trusted_dir_servers();

  if (!options->DirServers) {
    /* then we may want some of the defaults */
    authority_type_t type = NO_AUTHORITY;
    if (!options->AlternateBridgeAuthority)
      type |= BRIDGE_AUTHORITY;
    if (!options->AlternateDirAuthority)
852
      type |= V1_AUTHORITY | V2_AUTHORITY | V3_AUTHORITY;
853
854
855
856
857
858
    if (!options->AlternateHSAuthority)
      type |= HIDSERV_AUTHORITY;
    add_default_trusted_dir_authorities(type);
  }

  for (cl = options->DirServers; cl; cl = cl->next)
859
    if (parse_dir_server_line(cl->value, NO_AUTHORITY, 0)<0)
860