config.c 38.2 KB
Newer Older
1
/* Copyright 2001,2002,2003 Roger Dingledine, Matej Pfajfar. */
2
3
4
/* See LICENSE for licensing information */
/* $Id$ */

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

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

Nick Mathewson's avatar
Nick Mathewson committed
17
18
/** Enumeration of types which option values can take */
typedef enum config_type_t {
19
20
21
22
23
24
25
26
  CONFIG_TYPE_STRING = 0,   /**< An arbitrary string. */
  CONFIG_TYPE_UINT,         /**< A non-negative integer less than MAX_INT */
  CONFIG_TYPE_DOUBLE,       /**< A floating-point value */
  CONFIG_TYPE_BOOL,         /**< A boolean value, expressed as 0 or 1. */
  CONFIG_TYPE_CSV,          /**< A list of strings, separated by commas and optional
                              * whitespace. */
  CONFIG_TYPE_LINELIST,     /**< Uninterpreted config lines */
  CONFIG_TYPE_OBSOLETE,     /**< Obsolete (ignored) option. */
Nick Mathewson's avatar
Nick Mathewson committed
27
} config_type_t;
28

Nick Mathewson's avatar
Nick Mathewson committed
29
/* An abbreviation for a configuration option allowed on the command line */
30
31
32
33
34
typedef struct config_abbrev_t {
  char *abbreviated;
  char *full;
} config_abbrev_t;

Nick Mathewson's avatar
Nick Mathewson committed
35
/* A list of command-line abbreviations. */
36
37
38
39
40
static config_abbrev_t config_abbrevs[] = {
  { "l", "LogLevel" },
  { NULL, NULL },
};

Nick Mathewson's avatar
Nick Mathewson committed
41
/* A variable allowed in the configuration file or on the command line */
42
typedef struct config_var_t {
Nick Mathewson's avatar
Nick Mathewson committed
43
44
45
  char *name; /**< The full keyword (case insensitive) */
  config_type_t type; /**< How to interpret the type and turn it into a value */
  off_t var_offset; /**< Offset of the corresponding member of or_options_t */
46
47
} config_var_t;

Nick Mathewson's avatar
Nick Mathewson committed
48
/** Return the offset of <b>member</b> within the type <b>tp</b>, in bytes */
49
#define STRUCT_OFFSET(tp, member) ((off_t) &(((tp*)0)->member))
Nick Mathewson's avatar
Nick Mathewson committed
50
51
52
53
/** 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>"
 */
54
55
#define VAR(name,conftype,member) \
  { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_options_t, member) }
Nick Mathewson's avatar
Nick Mathewson committed
56
/** An entry for config_vars: "The option <b>name</b> is obsolete." */
57
58
#define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0 }

Nick Mathewson's avatar
Nick Mathewson committed
59
60
61
62
/** Array of configuration options.  Until we disallow nonstandard
 * abbreviations, order is significant, since the first matching option will
 * be chosen first.
 */
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
static config_var_t config_vars[] = {
  VAR("Address",             STRING,   Address),
  VAR("AllowUnverifiedNodes",CSV,      AllowUnverifiedNodes),
  VAR("AuthoritativeDirectory",BOOL,   AuthoritativeDir),
  VAR("BandwidthRate",       UINT,     BandwidthRate),
  VAR("BandwidthBurst",      UINT,     BandwidthBurst),
  VAR("ClientOnly",          BOOL,     ClientOnly),
  VAR("ContactInfo",         STRING,   ContactInfo),
  VAR("DebugLogFile",        STRING,   DebugLogFile),
  VAR("DataDirectory",       STRING,   DataDirectory),
  VAR("DirPort",             UINT,     DirPort),
  VAR("DirBindAddress",      LINELIST, DirBindAddress),
  VAR("DirFetchPostPeriod",  UINT,     DirFetchPostPeriod),
  VAR("DirPolicy",           LINELIST, DirPolicy),
  VAR("DirServer",           LINELIST, DirServers),
  VAR("ExitNodes",           STRING,   ExitNodes),
  VAR("EntryNodes",          STRING,   EntryNodes),
  VAR("StrictExitNodes",     BOOL,     StrictExitNodes),
  VAR("StrictEntryNodes",    BOOL,     StrictEntryNodes),
  VAR("ExitPolicy",          LINELIST, ExitPolicy),
  VAR("ExcludeNodes",        STRING,   ExcludeNodes),
  VAR("FascistFirewall",     BOOL,     FascistFirewall),
  VAR("FirewallPorts",       CSV,      FirewallPorts),
  VAR("MyFamily",            STRING,   MyFamily),
  VAR("NodeFamily",          LINELIST, NodeFamilies),
  VAR("Group",               STRING,   Group),
  VAR("HttpProxy",           STRING,   HttpProxy),
  VAR("HiddenServiceDir",    LINELIST, RendConfigLines),
  VAR("HiddenServicePort",   LINELIST, RendConfigLines),
  VAR("HiddenServiceNodes",  LINELIST, RendConfigLines),
  VAR("HiddenServiceExcludeNodes", LINELIST, RendConfigLines),
  VAR("IgnoreVersion",       BOOL,     IgnoreVersion),
  VAR("KeepalivePeriod",     UINT,     KeepalivePeriod),
  VAR("LogLevel",            LINELIST, LogOptions),
  VAR("LogFile",             LINELIST, LogOptions),
  OBSOLETE("LinkPadding"),
  VAR("MaxConn",             UINT,     MaxConn),
  VAR("MaxOnionsPending",    UINT,     MaxOnionsPending),
  VAR("Nickname",            STRING,   Nickname),
  VAR("NewCircuitPeriod",    UINT,     NewCircuitPeriod),
  VAR("NumCpus",             UINT,     NumCpus),
  VAR("ORPort",              UINT,     ORPort),
  VAR("ORBindAddress",       LINELIST, ORBindAddress),
  VAR("OutboundBindAddress", STRING,   OutboundBindAddress),
  VAR("PidFile",             STRING,   PidFile),
  VAR("PathlenCoinWeight",   DOUBLE,   PathlenCoinWeight),
  VAR("RedirectExit",        LINELIST, RedirectExit),
  OBSOLETE("RouterFile"),
  VAR("RunAsDaemon",         BOOL,     RunAsDaemon),
  VAR("RunTesting",          BOOL,     RunTesting),
  VAR("RecommendedVersions", LINELIST, RecommendedVersions),
  VAR("RendNodes",           STRING,   RendNodes),
  VAR("RendExcludeNodes",    STRING,   RendExcludeNodes),
  VAR("SocksPort",           UINT,     SocksPort),
  VAR("SocksBindAddress",    LINELIST, SocksBindAddress),
  VAR("SocksPolicy",         LINELIST, SocksPolicy),
  VAR("SysLog",              LINELIST, LogOptions),
  OBSOLETE("TrafficShaping"),
  VAR("User",                STRING,   User),
Nick Mathewson's avatar
Nick Mathewson committed
122
  { NULL, CONFIG_TYPE_OBSOLETE, 0 }
123
124
125
126
};
#undef VAR
#undef OBSOLETE

Nick Mathewson's avatar
Nick Mathewson committed
127
/** Largest allowed config line */
128
#define CONFIG_LINE_T_MAXLEN 4096
129

130
static struct config_line_t *config_get_commandlines(int argc, char **argv);
131
static int config_get_lines(FILE *f, struct config_line_t **result);
132
static void config_free_lines(struct config_line_t *front);
Nick Mathewson's avatar
Nick Mathewson committed
133
static int config_assign_line(or_options_t *options, struct config_line_t *c);
134
static int config_assign(or_options_t *options, struct config_line_t *list);
135
static int parse_dir_server_line(const char *line);
Roger Dingledine's avatar
Roger Dingledine committed
136
137
static int parse_redirect_line(or_options_t *options,
                               struct config_line_t *line);
138
139
static const char *expand_abbrev(const char *option);
static config_var_t *config_find_option(const char *key);
140

Nick Mathewson's avatar
Nick Mathewson committed
141
142
/** If <b>option</b> is an official abbreviation for a longer option,
 * return the longer option.  Otherwise return <b>option</b> */
143
144
145
146
147
148
149
150
151
152
153
static const char *
expand_abbrev(const char *option)
{
  int i;
  for (i=0; config_abbrevs[i].abbreviated; ++i) {
    /* Abbreviations aren't casei. */
    if (!strcmp(option,config_abbrevs[i].abbreviated))
      return config_abbrevs[i].full;
  }
  return option;
}
Nick Mathewson's avatar
Nick Mathewson committed
154

Nick Mathewson's avatar
Nick Mathewson committed
155
/** Helper: Read a list of configuration options from the command line. */
156
157
158
static struct config_line_t *
config_get_commandlines(int argc, char **argv)
{
159
160
  struct config_line_t *new;
  struct config_line_t *front = NULL;
161
162
163
  char *s;
  int i = 1;

164
165
  while (i < argc-1) {
    if (!strcmp(argv[i],"-f")) {
166
//      log(LOG_DEBUG,"Commandline: skipping over -f.");
167
      i += 2; /* this is the config file option. ignore it. */
168
169
170
      continue;
    }

171
    new = tor_malloc(sizeof(struct config_line_t));
172
    s = argv[i];
173

174
175
    while(*s == '-')
      s++;
176

177
    new->key = tor_strdup(expand_abbrev(s));
178
    new->value = tor_strdup(argv[i+1]);
179
180

    log(LOG_DEBUG,"Commandline: parsed keyword '%s', value '%s'",
181
        new->key, new->value);
182
183
184
185
186
187
188
    new->next = front;
    front = new;
    i += 2;
  }
  return front;
}

Nick Mathewson's avatar
Nick Mathewson committed
189
190
/** Helper: allocate a new configuration option mapping 'key' to 'val',
 * prepend it to 'front', and return the newly allocated config_line_t */
191
192
193
194
195
196
static struct config_line_t *
config_line_prepend(struct config_line_t *front,
                    const char *key,
                    const char *val)
{
  struct config_line_t *newline;
197

198
199
200
201
202
203
204
  newline = tor_malloc(sizeof(struct config_line_t));
  newline->key = tor_strdup(key);
  newline->value = tor_strdup(val);
  newline->next = front;
  return newline;
}

205
/** Helper: parse the config file and strdup into key/value
206
207
208
 * strings. Set *result to the list, or NULL if parsing the file
 * failed.  Return 0 on success, -1 on failure. Warn and ignore any
 * misformatted lines. */
209
210
211
static int
config_get_lines(FILE *f, struct config_line_t **result)
{
212
213
  struct config_line_t *front = NULL;
  char line[CONFIG_LINE_T_MAXLEN];
214
  int r;
215
  char *key, *value;
216

217
  while ((r = parse_line_from_file(line, sizeof(line), f, &key, &value)) > 0) {
218
    front = config_line_prepend(front, key, value);
Roger Dingledine's avatar
Roger Dingledine committed
219
  }
220
221

  if (r < 0) {
222
223
224
225
226
227
    *result = NULL;
    return -1;
  } else {
    *result = front;
    return 0;
  }
Roger Dingledine's avatar
Roger Dingledine committed
228
229
}

Nick Mathewson's avatar
Nick Mathewson committed
230
231
232
/**
 * Free all the configuration lines on the linked list <b>front</b>.
 */
233
234
235
static void
config_free_lines(struct config_line_t *front)
{
236
  struct config_line_t *tmp;
237

238
  while (front) {
239
240
241
    tmp = front;
    front = tmp->next;

Roger Dingledine's avatar
Roger Dingledine committed
242
243
244
    tor_free(tmp->key);
    tor_free(tmp->value);
    tor_free(tmp);
245
246
247
  }
}

Nick Mathewson's avatar
Nick Mathewson committed
248
249
250
251
/** If <b>key</b> is a configuration option, return the corresponding
 * config_var_t.  Otherwise, if <b>key</b> is a non-standard abbreviation,
 * warn, and return the corresponding config_var_t.  Otherwise return NULL.
 */
252
253
254
static config_var_t *config_find_option(const char *key)
{
  int i;
Nick Mathewson's avatar
Nick Mathewson committed
255
  /* First, check for an exact (case-insensitive) match */
256
  for (i=0; config_vars[i].name; ++i) {
Nick Mathewson's avatar
Nick Mathewson committed
257
    if (!strcasecmp(key, config_vars[i].name))
258
      return &config_vars[i];
Nick Mathewson's avatar
Nick Mathewson committed
259
260
261
262
  }
  /* If none, check for an abbreviated match */
  for (i=0; config_vars[i].name; ++i) {
    if (!strncasecmp(key, config_vars[i].name, strlen(key))) {
263
264
265
266
267
268
      log_fn(LOG_WARN, "The abbreviation '%s' is deprecated. "
          "Tell Nick and Roger to make it official, or just use '%s' instead",
             key, config_vars[i].name);
      return &config_vars[i];
    }
  }
Nick Mathewson's avatar
Nick Mathewson committed
269
  /* Okay, unrecogized options */
270
271
272
  return NULL;
}

Nick Mathewson's avatar
Nick Mathewson committed
273
274
/** If <b>c</b> is a syntactically valid configuration line, update
 * <b>options</b> with its value and return 0.  Otherwise return -1. */
275
static int
276
config_assign_line(or_options_t *options, struct config_line_t *c)
277
{
278
  int i, ok;
279
280
  config_var_t *var;
  void *lvalue;
281

282
283
284
285
286
  var = config_find_option(c->key);
  if (!var) {
    log_fn(LOG_WARN, "Unknown option '%s'.  Failing.", c->key);
    return -1;
  }
287

288
289
  /* Put keyword into canonical case. */
  if (strcmp(var->name, c->key)) {
290
    tor_free(c->key);
291
    c->key = tor_strdup(var->name);
292
293
  }

294
295
  lvalue = ((void*)options) + var->var_offset;
  switch(var->type) {
296

297
298
299
300
301
302
303
  case CONFIG_TYPE_UINT:
    i = tor_parse_long(c->value, 10, 0, INT_MAX, &ok, NULL);
    if (!ok) {
      log(LOG_WARN, "Int keyword '%s %s' is malformed or out of bounds. Skipping.",
          c->key,c->value);
      return 0;
    }
304
    *(int *)lvalue = i;
305
306
307
308
309
310
311
312
    break;

  case CONFIG_TYPE_BOOL:
    i = tor_parse_long(c->value, 10, 0, 1, &ok, NULL);
    if (!ok) {
      log(LOG_WARN, "Boolean keyword '%s' expects 0 or 1. Skipping.", c->key);
      return 0;
    }
313
    *(int *)lvalue = i;
314
315
316
    break;

  case CONFIG_TYPE_STRING:
317
318
    tor_free(*(char **)lvalue);
    *(char **)lvalue = tor_strdup(c->value);
319
320
321
    break;

  case CONFIG_TYPE_DOUBLE:
322
    *(double *)lvalue = atof(c->value);
323
324
325
    break;

  case CONFIG_TYPE_CSV:
326
327
    if (*(smartlist_t**)lvalue == NULL)
      *(smartlist_t**)lvalue = smartlist_create();
328

329
    smartlist_split_string(*(smartlist_t**)lvalue, c->value, ",",
330
331
332
                           SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
    break;

333
334
335
336
    case CONFIG_TYPE_LINELIST:
      /* Note: this reverses the order that the lines appear in.  That's
       * just fine, since we build up the list of lines reversed in the
       * first place. */
337
338
      *(struct config_line_t**)lvalue =
        config_line_prepend(*(struct config_line_t**)lvalue, c->key, c->value);
339
      break;
340
341
342
343

  case CONFIG_TYPE_OBSOLETE:
    log_fn(LOG_WARN, "Skipping obsolete configuration option '%s'", c->key);
    break;
344
  }
345

346
  return 0;
347
348
}

Nick Mathewson's avatar
Nick Mathewson committed
349
350
/** Iterate through the linked list of options <b>list</b>.
 * For each item, convert as appropriate and assign to <b>options</b>.
351
352
 * If an item is unrecognized, return -1 immediately,
 * else return 0 for success. */
353
354
355
356
static int
config_assign(or_options_t *options, struct config_line_t *list)
{
  while (list) {
357
    if (config_assign_line(options, list))
358
      return -1;
359
    list = list->next;
Roger Dingledine's avatar
Roger Dingledine committed
360
  }
361

362
  return 0;
363
364
}

365
366
367
static void
add_default_trusted_dirservers(void)
{
Nick Mathewson's avatar
Nick Mathewson committed
368
369
370
371
  /* moria1 */
  parse_dir_server_line("18.244.0.188:9031 "
                        "FFCB 46DB 1339 DA84 674C 70D7 CB58 6434 C437 0441");
  /* moria2 */
372
  parse_dir_server_line("18.244.0.114:80 "
Nick Mathewson's avatar
Nick Mathewson committed
373
374
375
376
                        "719B E45D E224 B607 C537 07D0 E214 3E2D 423E 74CF");
  /* tor26 */
  parse_dir_server_line("62.116.124.106:9030 "
                        "847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D");
377
378
}

Nick Mathewson's avatar
Nick Mathewson committed
379
380
/** Set <b>options</b> to a reasonable default.
 *
381
 * Call this function before we parse the torrc file.
382
 */
383
384
385
static int
config_assign_defaults(or_options_t *options)
{
386
387
388
  /* set them up as a client only */
  options->SocksPort = 9050;

389
390
391
392
  options->AllowUnverifiedNodes = smartlist_create();
  smartlist_add(options->AllowUnverifiedNodes, "middle");
  smartlist_add(options->AllowUnverifiedNodes, "rendezvous");

Roger Dingledine's avatar
Roger Dingledine committed
393
  config_free_lines(options->ExitPolicy);
394
  options->ExitPolicy = NULL;
Roger Dingledine's avatar
Roger Dingledine committed
395

396
397
398
  return 0;
}

Nick Mathewson's avatar
Nick Mathewson committed
399
/** Print a usage message for tor. */
400
401
402
static void
print_usage(void)
{
403
  printf("tor -f <torrc> [args]\n"
404
         "See man page for more options. This -h is probably obsolete.\n\n"
405
         "-b <bandwidth>\t\tbytes/second rate limiting\n"
406
         "-d <file>\t\tDebug file\n"
407
//         "-m <max>\t\tMax number of connections\n"
408
409
410
411
         "-l <level>\t\tLog level\n"
         "-r <file>\t\tList of known routers\n");
  printf("\nClient options:\n"
         "-e \"nick1 nick2 ...\"\t\tExit nodes\n"
412
         "-s <IP>\t\t\tPort to bind to for Socks\n");
413
414
  printf("\nServer options:\n"
         "-n <nick>\t\tNickname of router\n"
415
         "-o <port>\t\tOR port to bind to\n"
416
         "-p <file>\t\tPID file\n");
417
418
}

Nick Mathewson's avatar
Nick Mathewson committed
419
/**
420
421
 * Based on <b>address</b>, guess our public IP address and put it
 * in <b>addr</b>.
Nick Mathewson's avatar
Nick Mathewson committed
422
 */
423
424
425
int
resolve_my_address(const char *address, uint32_t *addr)
{
426
427
  struct in_addr in;
  struct hostent *rent;
428
  char hostname[256];
429
  int explicit_ip=1;
430

431
432
  tor_assert(addr);

433
434
  if (address) {
    strlcpy(hostname, address, sizeof(hostname));
435
  } else { /* then we need to guess our address */
436
    explicit_ip = 0; /* it's implicit */
437

438
    if (gethostname(hostname, sizeof(hostname)) < 0) {
439
440
441
      log_fn(LOG_WARN,"Error obtaining local hostname");
      return -1;
    }
442
    log_fn(LOG_DEBUG,"Guessed local host name as '%s'",hostname);
443
444
  }

445
  /* now we know hostname. resolve it and keep only the IP */
446

447
  if (tor_inet_aton(hostname, &in) == 0) {
448
449
    /* then we have to resolve it */
    explicit_ip = 0;
450
    rent = (struct hostent *)gethostbyname(hostname);
451
    if (!rent) {
452
      log_fn(LOG_WARN,"Could not resolve local Address %s. Failing.", hostname);
453
454
      return -1;
    }
Roger Dingledine's avatar
Roger Dingledine committed
455
    tor_assert(rent->h_length == 4);
456
    memcpy(&in.s_addr, rent->h_addr, rent->h_length);
457
  }
458
459

  if (!explicit_ip && is_internal_IP(htonl(in.s_addr))) {
460
    log_fn(LOG_WARN,"Address '%s' resolves to private IP '%s'. "
461
           "Please set the Address config option to be the IP you want to use.",
462
           hostname, inet_ntoa(in));
463
464
    return -1;
  }
465
466

  log_fn(LOG_DEBUG, "Resolved Address to %s.", inet_ntoa(in));
467
  *addr = ntohl(in.s_addr);
468
469
470
  return 0;
}

471
472
static char *
get_default_nickname(void)
473
474
475
476
{
  char localhostname[256];
  char *cp, *out, *outp;

477
  if (gethostname(localhostname, sizeof(localhostname)) < 0) {
478
479
480
    log_fn(LOG_WARN,"Error obtaining local hostname");
    return NULL;
  }
481

482
  /* Put it in lowercase; stop at the first dot. */
483
  for (cp = localhostname; *cp; ++cp) {
484
485
486
487
488
489
    if (*cp == '.') {
      *cp = '\0';
      break;
    }
    *cp = tolower(*cp);
  }
490

491
492
  /* Strip invalid characters. */
  cp = localhostname;
493
  out = outp = tor_malloc(strlen(localhostname) + 1);
494
495
496
497
498
499
500
  while (*cp) {
    if (strchr(LEGAL_NICKNAME_CHARACTERS, *cp))
      *outp++ = *cp++;
    else
      cp++;
  }
  *outp = '\0';
501

502
503
504
505
506
507
508
  /* Enforce length. */
  if (strlen(out) > MAX_NICKNAME_LEN)
    out[MAX_NICKNAME_LEN]='\0';

  return out;
}

Nick Mathewson's avatar
Nick Mathewson committed
509
/** Release storage held by <b>options</b> */
510
511
512
static void
free_options(or_options_t *options)
{
513
  config_free_lines(options->LogOptions);
514
  tor_free(options->ContactInfo);
515
516
517
518
519
  tor_free(options->DebugLogFile);
  tor_free(options->DataDirectory);
  tor_free(options->Nickname);
  tor_free(options->Address);
  tor_free(options->PidFile);
520
521
  tor_free(options->ExitNodes);
  tor_free(options->EntryNodes);
522
  tor_free(options->ExcludeNodes);
523
524
  tor_free(options->RendNodes);
  tor_free(options->RendExcludeNodes);
525
  tor_free(options->OutboundBindAddress);
526
527
  tor_free(options->User);
  tor_free(options->Group);
528
  tor_free(options->HttpProxy);
529
  config_free_lines(options->RendConfigLines);
530
531
532
533
534
  config_free_lines(options->SocksBindAddress);
  config_free_lines(options->ORBindAddress);
  config_free_lines(options->DirBindAddress);
  config_free_lines(options->ExitPolicy);
  config_free_lines(options->SocksPolicy);
535
  config_free_lines(options->DirPolicy);
536
  config_free_lines(options->DirServers);
537
  config_free_lines(options->RecommendedVersions);
538
  config_free_lines(options->NodeFamilies);
539
540
  config_free_lines(options->RedirectExit);
  if (options->RedirectExitList) {
Nick Mathewson's avatar
Nick Mathewson committed
541
542
    SMARTLIST_FOREACH(options->RedirectExitList,
                      exit_redirect_t *, p, tor_free(p));
Roger Dingledine's avatar
Roger Dingledine committed
543
    smartlist_free(options->RedirectExitList);
544
    options->RedirectExitList = NULL;
545
  }
546
547
548
  if (options->FirewallPorts) {
    SMARTLIST_FOREACH(options->FirewallPorts, char *, cp, tor_free(cp));
    smartlist_free(options->FirewallPorts);
549
    options->FirewallPorts = NULL;
550
  }
551
}
552

553
554
555
556
557
/** Set <b>options</b> to hold reasonable defaults for most options.
 * Each option defaults to zero. */
static void
init_options(or_options_t *options)
{
558
  memset(options,0,sizeof(or_options_t));
559
560
  options->ExitNodes = tor_strdup("");
  options->EntryNodes = tor_strdup("");
561
  options->StrictEntryNodes = options->StrictExitNodes = 0;
562
  options->ExcludeNodes = tor_strdup("");
563
564
  options->RendNodes = tor_strdup("");
  options->RendExcludeNodes = tor_strdup("");
565
  /* options->PidFile = tor_strdup("tor.pid"); */
566
  options->PathlenCoinWeight = 0.3;
567
  options->MaxConn = 900;
568
  options->DirFetchPostPeriod = 600;
569
  options->KeepalivePeriod = 300;
570
  options->MaxOnionsPending = 100;
571
  options->NewCircuitPeriod = 30; /* twice a minute */
572
573
  options->BandwidthRate = 800000; /* at most 800kB/s total sustained incoming */
  options->BandwidthBurst = 10000000; /* max burst on the token bucket */
574
  options->NumCpus = 1;
575
576
}

577
#ifdef MS_WINDOWS
578
579
580
581
582
static char *get_windows_conf_root(void)
{
  static int is_set = 0;
  static char path[MAX_PATH+1];

583
584
585
  LPITEMIDLIST idl;
  IMalloc *m;
  HRESULT result;
586
587
588

  if (is_set)
    return path;
589

590
591
592
593
594
  /* Find X:\documents and settings\username\applicatation data\ .
   * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
   */
  if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, CSIDL_APPDATA,
                                            &idl))) {
595
596
597
598
    GetCurrentDirectory(MAX_PATH, path);
    is_set = 1;
    log_fn(LOG_WARN, "I couldn't find your application data folder: are you running an ancient version of Windows 95? Defaulting to '%s'", path);
    return path;
599
600
601
602
603
604
605
606
607
608
  }
  /* Convert the path from an "ID List" (whatever that is!) to a path. */
  result = SHGetPathFromIDList(idl, path);
  /* Now we need to free the */
  SHGetMalloc(&m);
  if (m) {
    m->lpVtbl->Free(m, idl);
    m->lpVtbl->Release(m);
  }
  if (!SUCCEEDED(result)) {
Nick Mathewson's avatar
Nick Mathewson committed
609
    return NULL;
610
  }
611
  strlcat(path,"\\tor",MAX_PATH);
612
613
614
615
616
617
618
619
620
621
622
  is_set = 1;
  return path;
}
#endif

static char *
get_default_conf_file(void)
{
#ifdef MS_WINDOWS
  char *path = tor_malloc(MAX_PATH);
  strlcpy(path, get_windows_conf_root(), MAX_PATH);
623
  strlcat(path,"\\torrc",MAX_PATH);
624
625
  return path;
#else
626
  return tor_strdup(CONFDIR "/torrc");
627
628
629
#endif
}

630
631
632
633
/** Verify whether lst is a string containing valid-looking space-separated
 * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
 */
static int check_nickname_list(const char *lst, const char *name)
634
{
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
  int r = 0;
  smartlist_t *sl;

  if (!lst)
    return 0;
  sl = smartlist_create();
  smartlist_split_string(sl, lst, ",", SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  SMARTLIST_FOREACH(sl, const char *, s,
    {
      if (!is_legal_nickname_or_hexdigest(s)) {
        log_fn(LOG_WARN, "Invalid nickname '%s' in %s line", s, name);
        r = -1;
      }
    });
  SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
650
  smartlist_free(sl);
651
652
653
  return r;
}

Nick Mathewson's avatar
Nick Mathewson committed
654
655
656
/** Read a configuration file into <b>options</b>, finding the configuration
 * file location based on the command line.  After loading the options,
 * validate them for consistency. Return 0 if success, <0 if failure. */
657
658
659
int
getconfig(int argc, char **argv, or_options_t *options)
{
660
  struct config_line_t *cl;
661
662
663
664
  FILE *cf;
  char *fname;
  int i;
  int result = 0;
665
666
667
668
669
  static int first_load = 1;
  static char **backup_argv;
  static int backup_argc;
  char *previous_pidfile = NULL;
  int previous_runasdaemon = 0;
670
  int previous_orport = -1;
671
  int using_default_torrc;
672

673
  if (first_load) { /* first time we're called. save commandline args */
674
675
676
677
678
679
680
681
    backup_argv = argv;
    backup_argc = argc;
    first_load = 0;
  } else { /* we're reloading. need to clean up old ones first. */
    argv = backup_argv;
    argc = backup_argc;

    /* record some previous values, so we can fail if they change */
682
    if (options->PidFile)
683
      previous_pidfile = tor_strdup(options->PidFile);
684
    previous_runasdaemon = options->RunAsDaemon;
685
    previous_orport = options->ORPort;
686
687
    free_options(options);
  }
Roger Dingledine's avatar
Roger Dingledine committed
688
  init_options(options);
689

690
  if (argc > 1 && (!strcmp(argv[1], "-h") || !strcmp(argv[1],"--help"))) {
691
692
693
694
    print_usage();
    exit(0);
  }

695
  if (argc > 1 && (!strcmp(argv[1],"--version"))) {
696
697
698
699
    printf("Tor version %s.\n",VERSION);
    exit(0);
  }

700
701
/* learn config file name, get config lines, assign them */
  i = 1;
702
  while (i < argc-1 && strcmp(argv[i],"-f")) {
703
704
    i++;
  }
705
706

  if (i < argc-1) { /* we found one */
707
    fname = tor_strdup(argv[i+1]);
708
    using_default_torrc = 0;
709
  } else {
710
    /* didn't find one, try CONFDIR */
Nick Mathewson's avatar
Nick Mathewson committed
711
712
713
    char *fn;
    using_default_torrc = 1;
    fn = get_default_conf_file();
714
    if (fn && file_status(fn) == FN_FILE) {
Nick Mathewson's avatar
Nick Mathewson committed
715
716
717
718
      fname = fn;
    } else {
      tor_free(fn);
      fn = expand_filename("~/.torrc");
719
      if (fn && file_status(fn) == FN_FILE) {
Nick Mathewson's avatar
Nick Mathewson committed
720
721
722
723
724
725
        fname = fn;
      } else {
        tor_free(fn);
        fname = get_default_conf_file();
      }
    }
726
  }
727
  tor_assert(fname);
728
  log(LOG_DEBUG, "Opening config file '%s'", fname);
729

730
  if (config_assign_defaults(options) < 0) {
731
732
    return -1;
  }
733

734
  cf = fopen(fname, "r");
735
736
737
738
  if (!cf) {
    if (using_default_torrc == 1) {
      log(LOG_NOTICE, "Configuration file '%s' not present, "
          "using reasonable defaults.", fname);
739
      tor_free(fname);
740
    } else {
741
      log(LOG_WARN, "Unable to open configuration file '%s'.", fname);
742
      tor_free(fname);
743
744
745
      return -1;
    }
  } else { /* it opened successfully. use it. */
746
    tor_free(fname);
747
748
    if (config_get_lines(cf, &cl)<0)
      return -1;
749
    if (config_assign(options,cl) < 0)
750
      return -1;
751
    config_free_lines(cl);
752
    fclose(cf);
753
  }
754

755
756
/* go through command-line variables too */
  cl = config_get_commandlines(argc,argv);
757
  if (config_assign(options,cl) < 0)
758
    return -1;
759
760
761
762
  config_free_lines(cl);

/* Validate options */

763
  /* first check if any of the previous options have changed but aren't allowed to */
764
  if (previous_pidfile && strcmp(previous_pidfile,options->PidFile)) {
765
766
767
768
769
770
    log_fn(LOG_WARN,"During reload, PidFile changed from %s to %s. Failing.",
           previous_pidfile, options->PidFile);
    return -1;
  }
  tor_free(previous_pidfile);

771
  if (previous_runasdaemon && !options->RunAsDaemon) {
772
773
774
775
    log_fn(LOG_WARN,"During reload, change from RunAsDaemon=1 to =0 not allowed. Failing.");
    return -1;
  }

776
  if (previous_orport == 0 && options->ORPort > 0) {
Roger Dingledine's avatar
Roger Dingledine committed
777
    log_fn(LOG_WARN,"During reload, change from ORPort=0 to >0 not allowed. Failing.");
778
779
780
    return -1;
  }

781
782
  if (options->ORPort < 0 || options->ORPort > 65535) {
    log(LOG_WARN, "ORPort option out of bounds.");
783
784
785
    result = -1;
  }

786
  if (options->Nickname == NULL) {
787
    if (server_mode()) {
788
789
790
791
      if (!(options->Nickname = get_default_nickname()))
        return -1;
      log_fn(LOG_NOTICE, "Choosing default nickname %s", options->Nickname);
    }
792
793
794
795
796
797
  } else {
    if (strspn(options->Nickname, LEGAL_NICKNAME_CHARACTERS) !=
        strlen(options->Nickname)) {
      log_fn(LOG_WARN, "Nickname '%s' contains illegal characters.", options->Nickname);
      result = -1;
    }
798
799
800
801
    if (strlen(options->Nickname) == 0) {
      log_fn(LOG_WARN, "Nickname must have at least one character");
      result = -1;
    }
802
803
804
805
    if (strlen(options->Nickname) > MAX_NICKNAME_LEN) {
      log_fn(LOG_WARN, "Nickname '%s' has more than %d characters.",
             options->Nickname, MAX_NICKNAME_LEN);
      result = -1;
806
    }
807
808
  }

809
  if (server_mode()) {
810
811
    /* confirm that our address isn't broken, so we can complain now */
    uint32_t tmp;
812
    if (resolve_my_address(options->Address, &tmp) < 0)
813
      result = -1;
814
815
  }

816
817
  if (options->SocksPort < 0 || options->SocksPort > 65535) {
    log(LOG_WARN, "SocksPort option out of bounds.");
818
819
820
    result = -1;
  }

821
822
  if (options->SocksPort == 0 && options->ORPort == 0) {
    log(LOG_WARN, "SocksPort and ORPort are both undefined? Quitting.");
823
    result = -1;
Roger Dingledine's avatar
Roger Dingledine committed
824
  }
825

826
827
  if (options->DirPort < 0 || options->DirPort > 65535) {
    log(LOG_WARN, "DirPort option out of bounds.");
828
829
830
    result = -1;
  }

831
832
  if (options->StrictExitNodes && !strlen(options->ExitNodes)) {
    log(LOG_WARN, "StrictExitNodes set, but no ExitNodes listed.");
833
834
  }

835
836
  if (options->StrictEntryNodes && !strlen(options->EntryNodes)) {
    log(LOG_WARN, "StrictEntryNodes set, but no EntryNodes listed.");
837
838
  }

839
840
  if (options->AuthoritativeDir && options->RecommendedVersions == NULL) {
    log(LOG_WARN, "Directory servers must configure RecommendedVersions.");
841
842
843
    result = -1;
  }

844
845
  if (options->AuthoritativeDir && !options->DirPort) {
    log(LOG_WARN, "Running as authoritative directory, but no DirPort set.");
846
847
848
    result = -1;
  }

849
850
  if (options->AuthoritativeDir && !options->ORPort) {
    log(LOG_WARN, "Running as authoritative directory, but no ORPort set.");
Roger Dingledine's avatar
Roger Dingledine committed
851
852
    result = -1;
  }
853

854
855
  if (options->AuthoritativeDir && options->ClientOnly) {
    log(LOG_WARN, "Running as authoritative directory, but ClientOnly also set.");
Roger Dingledine's avatar
Roger Dingledine committed
856
857
    result = -1;
  }
858

859
  if (options->FascistFirewall && !options->FirewallPorts) {
860
    options->FirewallPorts = smartlist_create();
861
862
    smartlist_add(options->FirewallPorts, tor_strdup("80"));
    smartlist_add(options->FirewallPorts, tor_strdup("443"));
863
  }
864
  if (options->FirewallPorts) {
865
    SMARTLIST_FOREACH(options->FirewallPorts, const char *, cp,
866
867
    {
      i = atoi(cp);
868
      if (i < 1 || i > 65535) {
869
870
871
872
873
874
        log(LOG_WARN, "Port '%s' out of range in FirewallPorts", cp);
        result=-1;
      }
    });
  }
  options->_AllowUnverified = 0;
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
  if (options->AllowUnverifiedNodes) {
    SMARTLIST_FOREACH(options->AllowUnverifiedNodes, const char *, cp, {
        if (!strcasecmp(cp, "entry"))
          options->_AllowUnverified |= ALLOW_UNVERIFIED_ENTRY;
        else if (!strcasecmp(cp, "exit"))
          options->_AllowUnverified |= ALLOW_UNVERIFIED_EXIT;
        else if (!strcasecmp(cp, "middle"))
          options->_AllowUnverified |= ALLOW_UNVERIFIED_MIDDLE;
        else if (!strcasecmp(cp, "introduction"))
          options->_AllowUnverified |= ALLOW_UNVERIFIED_INTRODUCTION;
        else if (!strcasecmp(cp, "rendezvous"))
          options->_AllowUnverified |= ALLOW_UNVERIFIED_RENDEZVOUS;
        else {
          log(LOG_WARN, "Unrecognized value '%s' in AllowUnverifiedNodes",
              cp);
          result=-1;
        }
      });
  }

  if (options->SocksPort >= 1 &&
      (options->PathlenCoinWeight < 0.0 || options->PathlenCoinWeight >= 1.0)) {
    log(LOG_WARN, "PathlenCoinWeight option must be >=0.0 and <1.0.");
898
899
900
    result = -1;
  }

901
902
  if (options->MaxConn < 1) {
    log(LOG_WARN, "MaxConn option must be a non-zero positive integer.");
903
904
905
    result = -1;
  }

906
907
  if (options->MaxConn >= MAXCONNECTIONS) {
    log(LOG_WARN, "MaxConn option must be less than %d.", MAXCONNECTIONS);
908
909
910
    result = -1;
  }

911
#define MIN_DIRFETCHPOSTPERIOD 60
912
913
  if (options->DirFetchPostPeriod < MIN_DIRFETCHPOSTPERIOD) {
    log(LOG_WARN, "DirFetchPostPeriod option must be at least %d.", MIN_DIRFETCHPOSTPERIOD);
914
915
    result = -1;
  }
916
917
918
  if (options->DirFetchPostPeriod > MIN_ONION_KEY_LIFETIME / 2) {
    log(LOG_WARN, "DirFetchPostPeriod is too large; clipping.");
    options->DirFetchPostPeriod = MIN_ONION_KEY_LIFETIME / 2;
919
  }
920

921
  if (options->KeepalivePeriod < 1) {
Roger Dingledine's avatar
Roger Dingledine committed
922
    log(LOG_WARN,"KeepalivePeriod option must be positive.");
923
924
925
    result = -1;
  }

926
927
928
  if (options->HttpProxy) { /* parse it now */
    if (parse_addr_port(options->HttpProxy, NULL,
                        &options->HttpProxyAddr, &options->HttpProxyPort) < 0) {
929
930
931
      log(LOG_WARN,"HttpProxy failed to parse or resolve. Please fix.");
      result = -1;
    }
932
    if (options->HttpProxyPort == 0) { /* give it a default */
933
934
935
936
      options->HttpProxyPort = 80;
    }
  }

937
938
939
940
941
942
943
944
945
946
947
948
  if (check_nickname_list(options->ExitNodes, "ExitNodes"))
    return -1;
  if (check_nickname_list(options->EntryNodes, "EntryNodes"))
    return -1;
  if (check_nickname_list(options->ExcludeNodes, "ExcludeNodes"))
    return -1;
  if (check_nickname_list(options->RendNodes, "RendNodes"))
    return -1;
  if (check_nickname_list(options->RendNodes, "RendExcludeNodes"))
    return -1;
  if (check_nickname_list(options->MyFamily, "MyFamily"))
    return -1;
949
950
951
952
953
  for (cl = options->NodeFamilies; cl; cl = cl->next) {
    if (check_nickname_list(cl->value, "NodeFamily"))
      return -1;
  }

954
955
956
957
958
959
960
  if (!options->RedirectExitList)
    options->RedirectExitList = smartlist_create();
  for (cl = options->RedirectExit; cl; cl = cl->next) {
    if (parse_redirect_line(options, cl)<0)
      return -1;
  }

Nick Mathewson's avatar
Nick Mathewson committed
961
962
963
964
965
966
967
968
  clear_trusted_dir_servers();
  if (!options->DirServers) {
    add_default_trusted_dirservers();
  } else {
    for (cl = options->DirServers; cl; cl = cl->next) {
      if (parse_dir_server_line(cl->value)<0)
        return -1;
    }
969
970
  }

971
972
973
  if (rend_config_services(options) < 0) {
    result = -1;
  }
974
  return result;
975
976
}

977
978
979
static int
add_single_log(struct config_line_t *level_opt,
               struct config_line_t *file_opt, int isDaemon)
980
{
981
  int levelMin = -1, levelMax = -1;
982
983
984
985
986
987
988
  char *cp, *tmp_sev;

  if (level_opt) {
    cp = strchr(level_opt->value, '-');
    if (cp) {
      tmp_sev = tor_strndup(level_opt->value, cp - level_opt->value);
      levelMin = parse_log_level(tmp_sev);
989
990
991
      if (levelMin < 0) {
        log_fn(LOG_WARN, "Unrecognized log severity '%s': must be one of "
               "err|warn|notice|info|debug", tmp_sev);
992
        return -1;
993
994
995
      }
      tor_free(tmp_sev);