config.c 36.8 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

29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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
/*DOCDOC*/
typedef struct config_abbrev_t {
  char *abbreviated;
  char *full;
} config_abbrev_t;

static config_abbrev_t config_abbrevs[] = {
  { "l", "LogLevel" },
  { NULL, NULL },
};

typedef struct config_var_t {
  char *name;
  config_type_t type;
  off_t var_offset;
} config_var_t;

#define STRUCT_OFFSET(tp, member) ((off_t) &(((tp*)0)->member))
#define VAR(name,conftype,member) \
  { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_options_t, member) }
#define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0 }

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),
  { NULL, NULL, NULL }
};
#undef VAR
#undef OBSOLETE


Nick Mathewson's avatar
Nick Mathewson committed
116
/** Largest allowed config line */
117
#define CONFIG_LINE_T_MAXLEN 4096
118

119
static struct config_line_t *config_get_commandlines(int argc, char **argv);
120
static int config_get_lines(FILE *f, struct config_line_t **result);
121
static void config_free_lines(struct config_line_t *front);
122
static int config_compare(struct config_line_t *c, const char *key, config_type_t type, void *arg);
123
static int config_assign(or_options_t *options, struct config_line_t *list);
124
static int parse_dir_server_line(const char *line);
Roger Dingledine's avatar
Roger Dingledine committed
125
126
static int parse_redirect_line(or_options_t *options,
                               struct config_line_t *line);
127
128
static const char *expand_abbrev(const char *option);
static config_var_t *config_find_option(const char *key);
129

130
131
132
133
134
135
136
137
138
139
140
141
/** DOCDOC */
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
142

Nick Mathewson's avatar
Nick Mathewson committed
143
/** Helper: Read a list of configuration options from the command line. */
144
145
146
static struct config_line_t *
config_get_commandlines(int argc, char **argv)
{
147
148
  struct config_line_t *new;
  struct config_line_t *front = NULL;
149
150
151
  char *s;
  int i = 1;

152
153
  while (i < argc-1) {
    if (!strcmp(argv[i],"-f")) {
154
//      log(LOG_DEBUG,"Commandline: skipping over -f.");
155
      i += 2; /* this is the config file option. ignore it. */
156
157
158
      continue;
    }

159
    new = tor_malloc(sizeof(struct config_line_t));
160
    s = argv[i];
161

162
163
    while(*s == '-')
      s++;
164

165
    new->key = tor_strdup(expand_abbrev(s));
166
    new->value = tor_strdup(argv[i+1]);
167
168

    log(LOG_DEBUG,"Commandline: parsed keyword '%s', value '%s'",
169
        new->key, new->value);
170
171
172
173
174
175
176
    new->next = front;
    front = new;
    i += 2;
  }
  return front;
}

Nick Mathewson's avatar
Nick Mathewson committed
177
178
/** Helper: allocate a new configuration option mapping 'key' to 'val',
 * prepend it to 'front', and return the newly allocated config_line_t */
179
180
181
182
183
184
static struct config_line_t *
config_line_prepend(struct config_line_t *front,
                    const char *key,
                    const char *val)
{
  struct config_line_t *newline;
185

186
187
188
189
190
191
192
  newline = tor_malloc(sizeof(struct config_line_t));
  newline->key = tor_strdup(key);
  newline->value = tor_strdup(val);
  newline->next = front;
  return newline;
}

193
/** Helper: parse the config file and strdup into key/value
194
195
196
 * 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. */
197
198
199
static int
config_get_lines(FILE *f, struct config_line_t **result)
{
200
201
  struct config_line_t *front = NULL;
  char line[CONFIG_LINE_T_MAXLEN];
202
  int r;
203
  char *key, *value;
204

205
  while ((r = parse_line_from_file(line, sizeof(line), f, &key, &value)) > 0) {
206
    front = config_line_prepend(front, key, value);
Roger Dingledine's avatar
Roger Dingledine committed
207
  }
208
209

  if (r < 0) {
210
211
212
213
214
215
    *result = NULL;
    return -1;
  } else {
    *result = front;
    return 0;
  }
Roger Dingledine's avatar
Roger Dingledine committed
216
217
}

Nick Mathewson's avatar
Nick Mathewson committed
218
219
220
/**
 * Free all the configuration lines on the linked list <b>front</b>.
 */
221
222
223
static void
config_free_lines(struct config_line_t *front)
{
224
  struct config_line_t *tmp;
225

226
  while (front) {
227
228
229
    tmp = front;
    front = tmp->next;

Roger Dingledine's avatar
Roger Dingledine committed
230
231
232
    tor_free(tmp->key);
    tor_free(tmp->value);
    tor_free(tmp);
233
234
235
  }
}

236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
static config_var_t *config_find_option(const char *key)
{
  int i;
  for (i=0; config_vars[i].name; ++i) {
    if (!strcasecmp(key, config_vars[i].name)) {
      return &config_vars[i];
    } else if (!strncasecmp(key, config_vars[i].name, strlen(key))) {
      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];
    }
  }
  return NULL;
}

252
static int
253
config_assign_line(or_options_t *options, struct config_line_t *c)
254
{
255
  int i, ok;
256
257
  config_var_t *var;
  void *lvalue;
258

259
260
261
262
263
  var = config_find_option(c->key);
  if (!var) {
    log_fn(LOG_WARN, "Unknown option '%s'.  Failing.", c->key);
    return -1;
  }
264

265
266
  /* Put keyword into canonical case. */
  if (strcmp(var->name, c->key)) {
267
    tor_free(c->key);
268
    c->key = tor_strdup(var->name);
269
270
  }

271
272
  lvalue = ((void*)options) + var->var_offset;
  switch(var->type) {
273

274
275
276
277
278
279
280
  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;
    }
281
    *(int *)lvalue = i;
282
283
284
285
286
287
288
289
    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;
    }
290
    *(int *)lvalue = i;
291
292
293
    break;

  case CONFIG_TYPE_STRING:
294
295
    tor_free(*(char **)lvalue);
    *(char **)lvalue = tor_strdup(c->value);
296
297
298
    break;

  case CONFIG_TYPE_DOUBLE:
299
    *(double *)lvalue = atof(c->value);
300
301
302
    break;

  case CONFIG_TYPE_CSV:
303
304
    if (*(smartlist_t**)lvalue == NULL)
      *(smartlist_t**)lvalue = smartlist_create();
305

306
    smartlist_split_string(*(smartlist_t**)lvalue, c->value, ",",
307
308
309
                           SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
    break;

310
311
312
313
    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. */
314
315
      *(struct config_line_t**)lvalue =
        config_line_prepend(*(struct config_line_t**)lvalue, c->key, c->value);
316
      break;
317
318
319
320

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

323
  return 0;
324
325
}

Nick Mathewson's avatar
Nick Mathewson committed
326
327
/** Iterate through the linked list of options <b>list</b>.
 * For each item, convert as appropriate and assign to <b>options</b>.
328
329
 * If an item is unrecognized, return -1 immediately,
 * else return 0 for success. */
330
331
332
333
static int
config_assign(or_options_t *options, struct config_line_t *list)
{
  while (list) {
334
    if (config_assign_line(options, list))
335
      return -1;
336
    list = list->next;
Roger Dingledine's avatar
Roger Dingledine committed
337
  }
338

339
  return 0;
340
341
}

342
343
344
static void
add_default_trusted_dirservers(void)
{
Nick Mathewson's avatar
Nick Mathewson committed
345
346
347
348
  /* moria1 */
  parse_dir_server_line("18.244.0.188:9031 "
                        "FFCB 46DB 1339 DA84 674C 70D7 CB58 6434 C437 0441");
  /* moria2 */
349
  parse_dir_server_line("18.244.0.114:80 "
Nick Mathewson's avatar
Nick Mathewson committed
350
351
352
353
                        "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");
354
355
}

Nick Mathewson's avatar
Nick Mathewson committed
356
357
/** Set <b>options</b> to a reasonable default.
 *
358
 * Call this function before we parse the torrc file.
359
 */
360
361
362
static int
config_assign_defaults(or_options_t *options)
{
363
364
365
  /* set them up as a client only */
  options->SocksPort = 9050;

366
367
368
369
  options->AllowUnverifiedNodes = smartlist_create();
  smartlist_add(options->AllowUnverifiedNodes, "middle");
  smartlist_add(options->AllowUnverifiedNodes, "rendezvous");

Roger Dingledine's avatar
Roger Dingledine committed
370
  config_free_lines(options->ExitPolicy);
371
  options->ExitPolicy = NULL;
Roger Dingledine's avatar
Roger Dingledine committed
372

373
374
375
  return 0;
}

Nick Mathewson's avatar
Nick Mathewson committed
376
/** Print a usage message for tor. */
377
378
379
static void
print_usage(void)
{
380
  printf("tor -f <torrc> [args]\n"
381
         "See man page for more options. This -h is probably obsolete.\n\n"
382
         "-b <bandwidth>\t\tbytes/second rate limiting\n"
383
         "-d <file>\t\tDebug file\n"
384
//         "-m <max>\t\tMax number of connections\n"
385
386
387
388
         "-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"
389
         "-s <IP>\t\t\tPort to bind to for Socks\n");
390
391
  printf("\nServer options:\n"
         "-n <nick>\t\tNickname of router\n"
392
         "-o <port>\t\tOR port to bind to\n"
393
         "-p <file>\t\tPID file\n");
394
395
}

Nick Mathewson's avatar
Nick Mathewson committed
396
/**
397
398
 * Based on <b>address</b>, guess our public IP address and put it
 * in <b>addr</b>.
Nick Mathewson's avatar
Nick Mathewson committed
399
 */
400
401
402
int
resolve_my_address(const char *address, uint32_t *addr)
{
403
404
  struct in_addr in;
  struct hostent *rent;
405
  char hostname[256];
406
  int explicit_ip=1;
407

408
409
  tor_assert(addr);

410
411
  if (address) {
    strlcpy(hostname, address, sizeof(hostname));
412
  } else { /* then we need to guess our address */
413
    explicit_ip = 0; /* it's implicit */
414

415
    if (gethostname(hostname, sizeof(hostname)) < 0) {
416
417
418
      log_fn(LOG_WARN,"Error obtaining local hostname");
      return -1;
    }
419
    log_fn(LOG_DEBUG,"Guessed local host name as '%s'",hostname);
420
421
  }

422
  /* now we know hostname. resolve it and keep only the IP */
423

424
  if (tor_inet_aton(hostname, &in) == 0) {
425
426
    /* then we have to resolve it */
    explicit_ip = 0;
427
    rent = (struct hostent *)gethostbyname(hostname);
428
    if (!rent) {
429
      log_fn(LOG_WARN,"Could not resolve local Address %s. Failing.", hostname);
430
431
      return -1;
    }
Roger Dingledine's avatar
Roger Dingledine committed
432
    tor_assert(rent->h_length == 4);
433
    memcpy(&in.s_addr, rent->h_addr, rent->h_length);
434
  }
435
436

  if (!explicit_ip && is_internal_IP(htonl(in.s_addr))) {
437
    log_fn(LOG_WARN,"Address '%s' resolves to private IP '%s'. "
438
           "Please set the Address config option to be the IP you want to use.",
439
           hostname, inet_ntoa(in));
440
441
    return -1;
  }
442
443

  log_fn(LOG_DEBUG, "Resolved Address to %s.", inet_ntoa(in));
444
  *addr = ntohl(in.s_addr);
445
446
447
  return 0;
}

448
449
static char *
get_default_nickname(void)
450
451
452
453
{
  char localhostname[256];
  char *cp, *out, *outp;

454
  if (gethostname(localhostname, sizeof(localhostname)) < 0) {
455
456
457
    log_fn(LOG_WARN,"Error obtaining local hostname");
    return NULL;
  }
458

459
  /* Put it in lowercase; stop at the first dot. */
460
  for (cp = localhostname; *cp; ++cp) {
461
462
463
464
465
466
    if (*cp == '.') {
      *cp = '\0';
      break;
    }
    *cp = tolower(*cp);
  }
467

468
469
  /* Strip invalid characters. */
  cp = localhostname;
470
  out = outp = tor_malloc(strlen(localhostname) + 1);
471
472
473
474
475
476
477
  while (*cp) {
    if (strchr(LEGAL_NICKNAME_CHARACTERS, *cp))
      *outp++ = *cp++;
    else
      cp++;
  }
  *outp = '\0';
478

479
480
481
482
483
484
485
  /* Enforce length. */
  if (strlen(out) > MAX_NICKNAME_LEN)
    out[MAX_NICKNAME_LEN]='\0';

  return out;
}

Nick Mathewson's avatar
Nick Mathewson committed
486
/** Release storage held by <b>options</b> */
487
488
489
static void
free_options(or_options_t *options)
{
490
  config_free_lines(options->LogOptions);
491
  tor_free(options->ContactInfo);
492
493
494
495
496
  tor_free(options->DebugLogFile);
  tor_free(options->DataDirectory);
  tor_free(options->Nickname);
  tor_free(options->Address);
  tor_free(options->PidFile);
497
498
  tor_free(options->ExitNodes);
  tor_free(options->EntryNodes);
499
  tor_free(options->ExcludeNodes);
500
501
  tor_free(options->RendNodes);
  tor_free(options->RendExcludeNodes);
502
  tor_free(options->OutboundBindAddress);
503
504
  tor_free(options->User);
  tor_free(options->Group);
505
  tor_free(options->HttpProxy);
506
  config_free_lines(options->RendConfigLines);
507
508
509
510
511
  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);
512
  config_free_lines(options->DirPolicy);
513
  config_free_lines(options->DirServers);
514
  config_free_lines(options->RecommendedVersions);
515
  config_free_lines(options->NodeFamilies);
516
517
  config_free_lines(options->RedirectExit);
  if (options->RedirectExitList) {
Nick Mathewson's avatar
Nick Mathewson committed
518
519
    SMARTLIST_FOREACH(options->RedirectExitList,
                      exit_redirect_t *, p, tor_free(p));
Roger Dingledine's avatar
Roger Dingledine committed
520
    smartlist_free(options->RedirectExitList);
521
    options->RedirectExitList = NULL;
522
  }
523
524
525
  if (options->FirewallPorts) {
    SMARTLIST_FOREACH(options->FirewallPorts, char *, cp, tor_free(cp));
    smartlist_free(options->FirewallPorts);
526
    options->FirewallPorts = NULL;
527
  }
528
}
529

530
531
532
533
534
/** Set <b>options</b> to hold reasonable defaults for most options.
 * Each option defaults to zero. */
static void
init_options(or_options_t *options)
{
535
  memset(options,0,sizeof(or_options_t));
536
537
  options->ExitNodes = tor_strdup("");
  options->EntryNodes = tor_strdup("");
538
  options->StrictEntryNodes = options->StrictExitNodes = 0;
539
  options->ExcludeNodes = tor_strdup("");
540
541
  options->RendNodes = tor_strdup("");
  options->RendExcludeNodes = tor_strdup("");
542
  /* options->PidFile = tor_strdup("tor.pid"); */
543
  options->PathlenCoinWeight = 0.3;
544
  options->MaxConn = 900;
545
  options->DirFetchPostPeriod = 600;
546
  options->KeepalivePeriod = 300;
547
  options->MaxOnionsPending = 100;
548
  options->NewCircuitPeriod = 30; /* twice a minute */
549
550
  options->BandwidthRate = 800000; /* at most 800kB/s total sustained incoming */
  options->BandwidthBurst = 10000000; /* max burst on the token bucket */
551
  options->NumCpus = 1;
552
553
}

554
#ifdef MS_WINDOWS
555
556
557
558
559
static char *get_windows_conf_root(void)
{
  static int is_set = 0;
  static char path[MAX_PATH+1];

560
561
562
  LPITEMIDLIST idl;
  IMalloc *m;
  HRESULT result;
563
564
565

  if (is_set)
    return path;
566

567
568
569
570
571
  /* 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))) {
572
573
574
575
    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;
576
577
578
579
580
581
582
583
584
585
  }
  /* 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
586
    return NULL;
587
  }
588
  strlcat(path,"\\tor",MAX_PATH);
589
590
591
592
593
594
595
596
597
598
599
  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);
600
  strlcat(path,"\\torrc",MAX_PATH);
601
602
  return path;
#else
603
  return tor_strdup(CONFDIR "/torrc");
604
605
606
#endif
}

607
608
609
610
/** 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)
611
{
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
  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));
627
  smartlist_free(sl);
628
629
630
  return r;
}

Nick Mathewson's avatar
Nick Mathewson committed
631
632
633
/** 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. */
634
635
636
int
getconfig(int argc, char **argv, or_options_t *options)
{
637
  struct config_line_t *cl;
638
639
640
641
  FILE *cf;
  char *fname;
  int i;
  int result = 0;
642
643
644
645
646
  static int first_load = 1;
  static char **backup_argv;
  static int backup_argc;
  char *previous_pidfile = NULL;
  int previous_runasdaemon = 0;
647
  int previous_orport = -1;
648
  int using_default_torrc;
649

650
  if (first_load) { /* first time we're called. save commandline args */
651
652
653
654
655
656
657
658
    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 */
659
    if (options->PidFile)
660
      previous_pidfile = tor_strdup(options->PidFile);
661
    previous_runasdaemon = options->RunAsDaemon;
662
    previous_orport = options->ORPort;
663
664
    free_options(options);
  }
Roger Dingledine's avatar
Roger Dingledine committed
665
  init_options(options);
666

667
  if (argc > 1 && (!strcmp(argv[1], "-h") || !strcmp(argv[1],"--help"))) {
668
669
670
671
    print_usage();
    exit(0);
  }

672
  if (argc > 1 && (!strcmp(argv[1],"--version"))) {
673
674
675
676
    printf("Tor version %s.\n",VERSION);
    exit(0);
  }

677
678
/* learn config file name, get config lines, assign them */
  i = 1;
679
  while (i < argc-1 && strcmp(argv[i],"-f")) {
680
681
    i++;
  }
682
683

  if (i < argc-1) { /* we found one */
684
    fname = tor_strdup(argv[i+1]);
685
    using_default_torrc = 0;
686
  } else {
687
    /* didn't find one, try CONFDIR */
Nick Mathewson's avatar
Nick Mathewson committed
688
689
690
    char *fn;
    using_default_torrc = 1;
    fn = get_default_conf_file();
691
    if (fn && file_status(fn) == FN_FILE) {
Nick Mathewson's avatar
Nick Mathewson committed
692
693
694
695
      fname = fn;
    } else {
      tor_free(fn);
      fn = expand_filename("~/.torrc");
696
      if (fn && file_status(fn) == FN_FILE) {
Nick Mathewson's avatar
Nick Mathewson committed
697
698
699
700
701
702
        fname = fn;
      } else {
        tor_free(fn);
        fname = get_default_conf_file();
      }
    }
703
  }
704
  tor_assert(fname);
705
  log(LOG_DEBUG, "Opening config file '%s'", fname);
706

707
  if (config_assign_defaults(options) < 0) {
708
709
    return -1;
  }
710

711
  cf = fopen(fname, "r");
712
713
714
715
  if (!cf) {
    if (using_default_torrc == 1) {
      log(LOG_NOTICE, "Configuration file '%s' not present, "
          "using reasonable defaults.", fname);
716
      tor_free(fname);
717
    } else {
718
      log(LOG_WARN, "Unable to open configuration file '%s'.", fname);
719
      tor_free(fname);
720
721
722
      return -1;
    }
  } else { /* it opened successfully. use it. */
723
    tor_free(fname);
724
725
    if (config_get_lines(cf, &cl)<0)
      return -1;
726
    if (config_assign(options,cl) < 0)
727
      return -1;
728
    config_free_lines(cl);
729
    fclose(cf);
730
  }
731

732
733
/* go through command-line variables too */
  cl = config_get_commandlines(argc,argv);
734
  if (config_assign(options,cl) < 0)
735
    return -1;
736
737
738
739
  config_free_lines(cl);

/* Validate options */

740
  /* first check if any of the previous options have changed but aren't allowed to */
741
  if (previous_pidfile && strcmp(previous_pidfile,options->PidFile)) {
742
743
744
745
746
747
    log_fn(LOG_WARN,"During reload, PidFile changed from %s to %s. Failing.",
           previous_pidfile, options->PidFile);
    return -1;
  }
  tor_free(previous_pidfile);

748
  if (previous_runasdaemon && !options->RunAsDaemon) {
749
750
751
752
    log_fn(LOG_WARN,"During reload, change from RunAsDaemon=1 to =0 not allowed. Failing.");
    return -1;
  }

753
  if (previous_orport == 0 && options->ORPort > 0) {
Roger Dingledine's avatar
Roger Dingledine committed
754
    log_fn(LOG_WARN,"During reload, change from ORPort=0 to >0 not allowed. Failing.");
755
756
757
    return -1;
  }

758
759
  if (options->ORPort < 0 || options->ORPort > 65535) {
    log(LOG_WARN, "ORPort option out of bounds.");
760
761
762
    result = -1;
  }

763
  if (options->Nickname == NULL) {
764
    if (server_mode()) {
765
766
767
768
      if (!(options->Nickname = get_default_nickname()))
        return -1;
      log_fn(LOG_NOTICE, "Choosing default nickname %s", options->Nickname);
    }
769
770
771
772
773
774
  } else {
    if (strspn(options->Nickname, LEGAL_NICKNAME_CHARACTERS) !=
        strlen(options->Nickname)) {
      log_fn(LOG_WARN, "Nickname '%s' contains illegal characters.", options->Nickname);
      result = -1;
    }
775
776
777
778
    if (strlen(options->Nickname) == 0) {
      log_fn(LOG_WARN, "Nickname must have at least one character");
      result = -1;
    }
779
780
781
782
    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;
783
    }
784
785
  }

786
  if (server_mode()) {
787
788
    /* confirm that our address isn't broken, so we can complain now */
    uint32_t tmp;
789
    if (resolve_my_address(options->Address, &tmp) < 0)
790
      result = -1;
791
792
  }

793
794
  if (options->SocksPort < 0 || options->SocksPort > 65535) {
    log(LOG_WARN, "SocksPort option out of bounds.");
795
796
797
    result = -1;
  }

798
799
  if (options->SocksPort == 0 && options->ORPort == 0) {
    log(LOG_WARN, "SocksPort and ORPort are both undefined? Quitting.");
800
    result = -1;
Roger Dingledine's avatar
Roger Dingledine committed
801
  }
802

803
804
  if (options->DirPort < 0 || options->DirPort > 65535) {
    log(LOG_WARN, "DirPort option out of bounds.");
805
806
807
    result = -1;
  }

808
809
  if (options->StrictExitNodes && !strlen(options->ExitNodes)) {
    log(LOG_WARN, "StrictExitNodes set, but no ExitNodes listed.");
810
811
  }

812
813
  if (options->StrictEntryNodes && !strlen(options->EntryNodes)) {
    log(LOG_WARN, "StrictEntryNodes set, but no EntryNodes listed.");
814
815
  }

816
817
  if (options->AuthoritativeDir && options->RecommendedVersions == NULL) {
    log(LOG_WARN, "Directory servers must configure RecommendedVersions.");
818
819
820
    result = -1;
  }

821
822
  if (options->AuthoritativeDir && !options->DirPort) {
    log(LOG_WARN, "Running as authoritative directory, but no DirPort set.");
823
824
825
    result = -1;
  }

826
827
  if (options->AuthoritativeDir && !options->ORPort) {
    log(LOG_WARN, "Running as authoritative directory, but no ORPort set.");
Roger Dingledine's avatar
Roger Dingledine committed
828
829
    result = -1;
  }
830

831
832
  if (options->AuthoritativeDir && options->ClientOnly) {
    log(LOG_WARN, "Running as authoritative directory, but ClientOnly also set.");
Roger Dingledine's avatar
Roger Dingledine committed
833
834
    result = -1;
  }
835

836
  if (options->FascistFirewall && !options->FirewallPorts) {
837
    options->FirewallPorts = smartlist_create();
838
839
    smartlist_add(options->FirewallPorts, tor_strdup("80"));
    smartlist_add(options->FirewallPorts, tor_strdup("443"));
840
  }
841
  if (options->FirewallPorts) {
842
    SMARTLIST_FOREACH(options->FirewallPorts, const char *, cp,
843
844
    {
      i = atoi(cp);
845
      if (i < 1 || i > 65535) {
846
847
848
849
850
851
        log(LOG_WARN, "Port '%s' out of range in FirewallPorts", cp);
        result=-1;
      }
    });
  }
  options->_AllowUnverified = 0;
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
  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.");
875
876
877
    result = -1;
  }

878
879
  if (options->MaxConn < 1) {
    log(LOG_WARN, "MaxConn option must be a non-zero positive integer.");
880
881
882
    result = -1;
  }

883
884
  if (options->MaxConn >= MAXCONNECTIONS) {
    log(LOG_WARN, "MaxConn option must be less than %d.", MAXCONNECTIONS);
885
886
887
    result = -1;
  }

888
#define MIN_DIRFETCHPOSTPERIOD 60
889
890
  if (options->DirFetchPostPeriod < MIN_DIRFETCHPOSTPERIOD) {
    log(LOG_WARN, "DirFetchPostPeriod option must be at least %d.", MIN_DIRFETCHPOSTPERIOD);
891
892
    result = -1;
  }
893
894
895
  if (options->DirFetchPostPeriod > MIN_ONION_KEY_LIFETIME / 2) {
    log(LOG_WARN, "DirFetchPostPeriod is too large; clipping.");
    options->DirFetchPostPeriod = MIN_ONION_KEY_LIFETIME / 2;
896
  }
897

898
  if (options->KeepalivePeriod < 1) {
Roger Dingledine's avatar
Roger Dingledine committed
899
    log(LOG_WARN,"KeepalivePeriod option must be positive.");
900
901
902
    result = -1;
  }

903
904
905
  if (options->HttpProxy) { /* parse it now */
    if (parse_addr_port(options->HttpProxy, NULL,
                        &options->HttpProxyAddr, &options->HttpProxyPort) < 0) {
906
907
908
      log(LOG_WARN,"HttpProxy failed to parse or resolve. Please fix.");
      result = -1;
    }
909
    if (options->HttpProxyPort == 0) { /* give it a default */
910
911
912
913
      options->HttpProxyPort = 80;
    }
  }

914
915
916
917
918
919
920
921
922
923
924
925
  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;
926
927
928
929
930
  for (cl = options->NodeFamilies; cl; cl = cl->next) {
    if (check_nickname_list(cl->value, "NodeFamily"))
      return -1;
  }

931
932
933
934
935
936
937
  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
938
939
940
941
942
943
944
945
  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;
    }
946
947
  }

948
949
950
  if (rend_config_services(options) < 0) {
    result = -1;
  }
951
  return result;
952
953
}

954
955
956
static int
add_single_log(struct config_line_t *level_opt,
               struct config_line_t *file_opt, int isDaemon)
957
{
958
  int levelMin = -1, levelMax = -1;
959
960
961
962
963
964
965
  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);
966
967
968
      if (levelMin < 0) {
        log_fn(LOG_WARN, "Unrecognized log severity '%s': must be one of "
               "err|warn|notice|info|debug", tmp_sev);
969
        return -1;
970
971
972
      }
      tor_free(tmp_sev);
      levelMax = parse_log_level(cp+1);
973
974
975
      if (levelMax < 0) {
        log_fn(LOG_WARN, "Unrecognized log severity '%s': must be one of "
               "err|warn|notice|info|debug", cp+1);
976
        return -1;
977
978
979
      }
    } else {
      levelMin = parse_log_level(level_opt->value);
980
981
982
      if (levelMin < 0) {
        log_fn(LOG_WARN, "Unrecognized log severity '%s': must be one of "
               "err|warn|notice|info|debug", level_opt->value);
983
984
        return -1;

985
986
987
988
989
990
991
992
993
994
995
      }
    }
  }
  if (levelMin < 0 && levelMax < 0) {
    levelMin = LOG_NOTICE;
    levelMax = LOG_ERR;
  } else if (levelMin < 0) {
    levelMin = levelMax;
  } else {
    levelMax = LOG_ERR;
  }
996
997

  if (file_opt && !strcasecmp(file_opt->key, "LogFile")) {
998
999
1000
    if (add_file_log(levelMin, levelMax, file_opt->value) < 0) {
      log_fn(LOG_WARN, "Cannot write to LogFile '%s': %s.", file_opt->value,
             strerror(errno));
For faster browsing, not all history is shown. View entire blame