config.c 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125
  1. /* Copyright 2001,2002,2003 Roger Dingledine, Matej Pfajfar. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. /**
  5. * /file config.c
  6. *
  7. * /brief Code to parse and interpret configuration files.
  8. *
  9. **/
  10. #include "or.h"
  11. #ifdef MS_WINDOWS
  12. #include <shlobj.h>
  13. #endif
  14. /** Enumeration of types which option values can take */
  15. typedef enum config_type_t {
  16. CONFIG_TYPE_STRING = 0, /**< An arbitrary string. */
  17. CONFIG_TYPE_UINT, /**< A non-negative integer less than MAX_INT */
  18. CONFIG_TYPE_DOUBLE, /**< A floating-point value */
  19. CONFIG_TYPE_BOOL, /**< A boolean value, expressed as 0 or 1. */
  20. CONFIG_TYPE_CSV, /**< A list of strings, separated by commas and optional
  21. * whitespace. */
  22. CONFIG_TYPE_LINELIST, /**< Uninterpreted config lines */
  23. CONFIG_TYPE_OBSOLETE, /**< Obsolete (ignored) option. */
  24. } config_type_t;
  25. /** Largest allowed config line */
  26. #define CONFIG_LINE_T_MAXLEN 4096
  27. static struct config_line_t *config_get_commandlines(int argc, char **argv);
  28. static int config_get_lines(FILE *f, struct config_line_t **result);
  29. static void config_free_lines(struct config_line_t *front);
  30. static int config_compare(struct config_line_t *c, const char *key, config_type_t type, void *arg);
  31. static int config_assign(or_options_t *options, struct config_line_t *list);
  32. static int parse_dir_server_line(const char *line);
  33. /** Helper: Read a list of configuration options from the command line. */
  34. static struct config_line_t *
  35. config_get_commandlines(int argc, char **argv)
  36. {
  37. struct config_line_t *new;
  38. struct config_line_t *front = NULL;
  39. char *s;
  40. int i = 1;
  41. while (i < argc-1) {
  42. if (!strcmp(argv[i],"-f")) {
  43. // log(LOG_DEBUG,"Commandline: skipping over -f.");
  44. i += 2; /* this is the config file option. ignore it. */
  45. continue;
  46. }
  47. new = tor_malloc(sizeof(struct config_line_t));
  48. s = argv[i];
  49. while(*s == '-')
  50. s++;
  51. new->key = tor_strdup(s);
  52. new->value = tor_strdup(argv[i+1]);
  53. log(LOG_DEBUG,"Commandline: parsed keyword '%s', value '%s'",
  54. new->key, new->value);
  55. new->next = front;
  56. front = new;
  57. i += 2;
  58. }
  59. return front;
  60. }
  61. /** Helper: allocate a new configuration option mapping 'key' to 'val',
  62. * prepend it to 'front', and return the newly allocated config_line_t */
  63. static struct config_line_t *
  64. config_line_prepend(struct config_line_t *front,
  65. const char *key,
  66. const char *val)
  67. {
  68. struct config_line_t *newline;
  69. newline = tor_malloc(sizeof(struct config_line_t));
  70. newline->key = tor_strdup(key);
  71. newline->value = tor_strdup(val);
  72. newline->next = front;
  73. return newline;
  74. }
  75. /** Helper: parse the config file and strdup into key/value
  76. * strings. Set *result to the list, or NULL if parsing the file
  77. * failed. Return 0 on success, -1 on failure. Warn and ignore any
  78. * misformatted lines. */
  79. static int
  80. config_get_lines(FILE *f, struct config_line_t **result)
  81. {
  82. struct config_line_t *front = NULL;
  83. char line[CONFIG_LINE_T_MAXLEN];
  84. int r;
  85. char *key, *value;
  86. while ((r = parse_line_from_file(line, sizeof(line), f, &key, &value)) > 0) {
  87. front = config_line_prepend(front, key, value);
  88. }
  89. if (r < 0) {
  90. *result = NULL;
  91. return -1;
  92. } else {
  93. *result = front;
  94. return 0;
  95. }
  96. }
  97. /**
  98. * Free all the configuration lines on the linked list <b>front</b>.
  99. */
  100. static void
  101. config_free_lines(struct config_line_t *front)
  102. {
  103. struct config_line_t *tmp;
  104. while (front) {
  105. tmp = front;
  106. front = tmp->next;
  107. tor_free(tmp->key);
  108. tor_free(tmp->value);
  109. tor_free(tmp);
  110. }
  111. }
  112. /** Search the linked list <b>c</b> for any option whose key is <b>key</b>.
  113. * If such an option is found, interpret it as of type <b>type</b>, and store
  114. * the result in <b>arg</b>. If the option is misformatted, log a warning and
  115. * skip it.
  116. */
  117. static int
  118. config_compare(struct config_line_t *c, const char *key,
  119. config_type_t type, void *arg)
  120. {
  121. int i, ok;
  122. if (strncasecmp(c->key, key, strlen(c->key)))
  123. return 0;
  124. if (strcasecmp(c->key, key)) {
  125. tor_free(c->key);
  126. c->key = tor_strdup(key);
  127. }
  128. /* it's a match. cast and assign. */
  129. log_fn(LOG_DEBUG, "Recognized keyword '%s' as %s, using value '%s'.",
  130. c->key, key, c->value);
  131. switch(type) {
  132. case CONFIG_TYPE_UINT:
  133. i = tor_parse_long(c->value, 10, 0, INT_MAX, &ok, NULL);
  134. if (!ok) {
  135. log(LOG_WARN, "Int keyword '%s %s' is malformed or out of bounds. Skipping.",
  136. c->key,c->value);
  137. return 0;
  138. }
  139. *(int *)arg = i;
  140. break;
  141. case CONFIG_TYPE_BOOL:
  142. i = tor_parse_long(c->value, 10, 0, 1, &ok, NULL);
  143. if (!ok) {
  144. log(LOG_WARN, "Boolean keyword '%s' expects 0 or 1. Skipping.", c->key);
  145. return 0;
  146. }
  147. *(int *)arg = i;
  148. break;
  149. case CONFIG_TYPE_STRING:
  150. tor_free(*(char **)arg);
  151. *(char **)arg = tor_strdup(c->value);
  152. break;
  153. case CONFIG_TYPE_DOUBLE:
  154. *(double *)arg = atof(c->value);
  155. break;
  156. case CONFIG_TYPE_CSV:
  157. if (*(smartlist_t**)arg == NULL)
  158. *(smartlist_t**)arg = smartlist_create();
  159. smartlist_split_string(*(smartlist_t**)arg, c->value, ",",
  160. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  161. break;
  162. case CONFIG_TYPE_LINELIST:
  163. /* Note: this reverses the order that the lines appear in. That's
  164. * just fine, since we build up the list of lines reversed in the
  165. * first place. */
  166. *(struct config_line_t**)arg =
  167. config_line_prepend(*(struct config_line_t**)arg, c->key, c->value);
  168. break;
  169. case CONFIG_TYPE_OBSOLETE:
  170. log_fn(LOG_WARN, "Skipping obsolete configuration option '%s'", c->key);
  171. break;
  172. }
  173. return 1;
  174. }
  175. /** Iterate through the linked list of options <b>list</b>.
  176. * For each item, convert as appropriate and assign to <b>options</b>.
  177. * If an item is unrecognized, return -1 immediately,
  178. * else return 0 for success. */
  179. static int
  180. config_assign(or_options_t *options, struct config_line_t *list)
  181. {
  182. while (list) {
  183. if (
  184. /* order matters here! abbreviated arguments use the first match. */
  185. /* string options */
  186. config_compare(list, "Address", CONFIG_TYPE_STRING, &options->Address) ||
  187. config_compare(list, "AllowUnverifiedNodes", CONFIG_TYPE_CSV, &options->AllowUnverifiedNodes) ||
  188. config_compare(list, "AuthoritativeDirectory",CONFIG_TYPE_BOOL, &options->AuthoritativeDir) ||
  189. config_compare(list, "BandwidthRate", CONFIG_TYPE_UINT, &options->BandwidthRate) ||
  190. config_compare(list, "BandwidthBurst", CONFIG_TYPE_UINT, &options->BandwidthBurst) ||
  191. config_compare(list, "ClientOnly", CONFIG_TYPE_BOOL, &options->ClientOnly) ||
  192. config_compare(list, "ContactInfo", CONFIG_TYPE_STRING, &options->ContactInfo) ||
  193. config_compare(list, "DebugLogFile", CONFIG_TYPE_STRING, &options->DebugLogFile) ||
  194. config_compare(list, "DataDirectory", CONFIG_TYPE_STRING, &options->DataDirectory) ||
  195. config_compare(list, "DirPort", CONFIG_TYPE_UINT, &options->DirPort) ||
  196. config_compare(list, "DirBindAddress", CONFIG_TYPE_LINELIST, &options->DirBindAddress) ||
  197. config_compare(list, "DirFetchPostPeriod",CONFIG_TYPE_UINT, &options->DirFetchPostPeriod) ||
  198. config_compare(list, "DirServer", CONFIG_TYPE_LINELIST, &options->DirServers) ||
  199. config_compare(list, "ExitNodes", CONFIG_TYPE_STRING, &options->ExitNodes) ||
  200. config_compare(list, "EntryNodes", CONFIG_TYPE_STRING, &options->EntryNodes) ||
  201. config_compare(list, "StrictExitNodes", CONFIG_TYPE_BOOL, &options->StrictExitNodes) ||
  202. config_compare(list, "StrictEntryNodes", CONFIG_TYPE_BOOL, &options->StrictEntryNodes) ||
  203. config_compare(list, "ExitPolicy", CONFIG_TYPE_LINELIST, &options->ExitPolicy) ||
  204. config_compare(list, "ExcludeNodes", CONFIG_TYPE_STRING, &options->ExcludeNodes) ||
  205. config_compare(list, "FascistFirewall",CONFIG_TYPE_BOOL, &options->FascistFirewall) ||
  206. config_compare(list, "FirewallPorts",CONFIG_TYPE_CSV, &options->FirewallPorts) ||
  207. config_compare(list, "Group", CONFIG_TYPE_STRING, &options->Group) ||
  208. config_compare(list, "HttpProxy", CONFIG_TYPE_STRING, &options->HttpProxy) ||
  209. config_compare(list, "HiddenServiceDir", CONFIG_TYPE_LINELIST, &options->RendConfigLines)||
  210. config_compare(list, "HiddenServicePort", CONFIG_TYPE_LINELIST, &options->RendConfigLines)||
  211. config_compare(list, "HiddenServiceNodes", CONFIG_TYPE_LINELIST, &options->RendConfigLines)||
  212. config_compare(list, "HiddenServiceExcludeNodes", CONFIG_TYPE_LINELIST, &options->RendConfigLines)||
  213. config_compare(list, "IgnoreVersion", CONFIG_TYPE_BOOL, &options->IgnoreVersion) ||
  214. config_compare(list, "KeepalivePeriod",CONFIG_TYPE_UINT, &options->KeepalivePeriod) ||
  215. config_compare(list, "LogLevel", CONFIG_TYPE_LINELIST, &options->LogOptions) ||
  216. config_compare(list, "LogFile", CONFIG_TYPE_LINELIST, &options->LogOptions) ||
  217. config_compare(list, "LinkPadding", CONFIG_TYPE_OBSOLETE, NULL) ||
  218. config_compare(list, "MaxConn", CONFIG_TYPE_UINT, &options->MaxConn) ||
  219. config_compare(list, "MaxOnionsPending",CONFIG_TYPE_UINT, &options->MaxOnionsPending) ||
  220. config_compare(list, "Nickname", CONFIG_TYPE_STRING, &options->Nickname) ||
  221. config_compare(list, "NewCircuitPeriod",CONFIG_TYPE_UINT, &options->NewCircuitPeriod) ||
  222. config_compare(list, "NumCpus", CONFIG_TYPE_UINT, &options->NumCpus) ||
  223. config_compare(list, "ORPort", CONFIG_TYPE_UINT, &options->ORPort) ||
  224. config_compare(list, "ORBindAddress", CONFIG_TYPE_LINELIST, &options->ORBindAddress) ||
  225. config_compare(list, "OutboundBindAddress",CONFIG_TYPE_STRING, &options->OutboundBindAddress) ||
  226. config_compare(list, "PidFile", CONFIG_TYPE_STRING, &options->PidFile) ||
  227. config_compare(list, "PathlenCoinWeight",CONFIG_TYPE_DOUBLE, &options->PathlenCoinWeight) ||
  228. config_compare(list, "RouterFile", CONFIG_TYPE_STRING, &options->RouterFile) ||
  229. config_compare(list, "RunAsDaemon", CONFIG_TYPE_BOOL, &options->RunAsDaemon) ||
  230. config_compare(list, "RunTesting", CONFIG_TYPE_BOOL, &options->RunTesting) ||
  231. config_compare(list, "RecommendedVersions",CONFIG_TYPE_STRING, &options->RecommendedVersions) ||
  232. config_compare(list, "RendNodes", CONFIG_TYPE_STRING, &options->RendNodes) ||
  233. config_compare(list, "RendExcludeNodes",CONFIG_TYPE_STRING, &options->RendExcludeNodes) ||
  234. config_compare(list, "SocksPort", CONFIG_TYPE_UINT, &options->SocksPort) ||
  235. config_compare(list, "SocksBindAddress",CONFIG_TYPE_LINELIST,&options->SocksBindAddress) ||
  236. config_compare(list, "SocksPolicy", CONFIG_TYPE_LINELIST,&options->SocksPolicy) ||
  237. config_compare(list, "TrafficShaping", CONFIG_TYPE_OBSOLETE, NULL) ||
  238. config_compare(list, "User", CONFIG_TYPE_STRING, &options->User)
  239. ) {
  240. /* then we're ok. it matched something. */
  241. } else {
  242. log_fn(LOG_WARN,"Unknown keyword '%s'. Failing.",list->key);
  243. return -1;
  244. }
  245. list = list->next;
  246. }
  247. return 0;
  248. }
  249. static void
  250. add_default_trusted_dirservers(void)
  251. {
  252. /* moria1 */
  253. parse_dir_server_line("18.244.0.188:9031 "
  254. "FFCB 46DB 1339 DA84 674C 70D7 CB58 6434 C437 0441");
  255. /* moria2 */
  256. parse_dir_server_line("18.244.0.114:80 "
  257. "719B E45D E224 B607 C537 07D0 E214 3E2D 423E 74CF");
  258. /* tor26 */
  259. parse_dir_server_line("62.116.124.106:9030 "
  260. "847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D");
  261. }
  262. /** Set <b>options</b> to a reasonable default.
  263. *
  264. * Call this function when we can't find any torrc config file.
  265. */
  266. static int
  267. config_assign_defaults(or_options_t *options)
  268. {
  269. /* set them up as a client only */
  270. options->SocksPort = 9050;
  271. options->AllowUnverifiedNodes = smartlist_create();
  272. smartlist_add(options->AllowUnverifiedNodes, "middle");
  273. smartlist_add(options->AllowUnverifiedNodes, "rendezvous");
  274. config_free_lines(options->ExitPolicy);
  275. options->ExitPolicy = config_line_prepend(NULL, "ExitPolicy", "reject *:*");
  276. return 0;
  277. }
  278. /** Print a usage message for tor. */
  279. static void
  280. print_usage(void)
  281. {
  282. printf("tor -f <torrc> [args]\n"
  283. "See man page for more options. This -h is probably obsolete.\n\n"
  284. "-b <bandwidth>\t\tbytes/second rate limiting\n"
  285. "-d <file>\t\tDebug file\n"
  286. // "-m <max>\t\tMax number of connections\n"
  287. "-l <level>\t\tLog level\n"
  288. "-r <file>\t\tList of known routers\n");
  289. printf("\nClient options:\n"
  290. "-e \"nick1 nick2 ...\"\t\tExit nodes\n"
  291. "-s <IP>\t\t\tPort to bind to for Socks\n");
  292. printf("\nServer options:\n"
  293. "-n <nick>\t\tNickname of router\n"
  294. "-o <port>\t\tOR port to bind to\n"
  295. "-p <file>\t\tPID file\n");
  296. }
  297. /**
  298. * Based on <b>address</b>, guess our public IP address and put it
  299. * in <b>addr</b>.
  300. */
  301. int
  302. resolve_my_address(const char *address, uint32_t *addr)
  303. {
  304. struct in_addr in;
  305. struct hostent *rent;
  306. char hostname[256];
  307. int explicit_ip=1;
  308. tor_assert(addr);
  309. if (address) {
  310. strlcpy(hostname, address, sizeof(hostname));
  311. } else { /* then we need to guess our address */
  312. explicit_ip = 0; /* it's implicit */
  313. if (gethostname(hostname, sizeof(hostname)) < 0) {
  314. log_fn(LOG_WARN,"Error obtaining local hostname");
  315. return -1;
  316. }
  317. log_fn(LOG_DEBUG,"Guessed local host name as '%s'",hostname);
  318. }
  319. /* now we know hostname. resolve it and keep only the IP */
  320. if (tor_inet_aton(hostname, &in) == 0) {
  321. /* then we have to resolve it */
  322. explicit_ip = 0;
  323. rent = (struct hostent *)gethostbyname(hostname);
  324. if (!rent) {
  325. log_fn(LOG_WARN,"Could not resolve local Address %s. Failing.", hostname);
  326. return -1;
  327. }
  328. tor_assert(rent->h_length == 4);
  329. memcpy(&in.s_addr, rent->h_addr, rent->h_length);
  330. }
  331. if (!explicit_ip && is_internal_IP(htonl(in.s_addr))) {
  332. log_fn(LOG_WARN,"Address '%s' resolves to private IP '%s'. "
  333. "Please set the Address config option to be the IP you want to use.",
  334. hostname, inet_ntoa(in));
  335. return -1;
  336. }
  337. log_fn(LOG_DEBUG, "Resolved Address to %s.", inet_ntoa(in));
  338. *addr = ntohl(in.s_addr);
  339. return 0;
  340. }
  341. static char *
  342. get_default_nickname(void)
  343. {
  344. char localhostname[256];
  345. char *cp, *out, *outp;
  346. if (gethostname(localhostname, sizeof(localhostname)) < 0) {
  347. log_fn(LOG_WARN,"Error obtaining local hostname");
  348. return NULL;
  349. }
  350. /* Put it in lowercase; stop at the first dot. */
  351. for (cp = localhostname; *cp; ++cp) {
  352. if (*cp == '.') {
  353. *cp = '\0';
  354. break;
  355. }
  356. *cp = tolower(*cp);
  357. }
  358. /* Strip invalid characters. */
  359. cp = localhostname;
  360. out = outp = tor_malloc(strlen(localhostname) + 1);
  361. while (*cp) {
  362. if (strchr(LEGAL_NICKNAME_CHARACTERS, *cp))
  363. *outp++ = *cp++;
  364. else
  365. cp++;
  366. }
  367. *outp = '\0';
  368. /* Enforce length. */
  369. if (strlen(out) > MAX_NICKNAME_LEN)
  370. out[MAX_NICKNAME_LEN]='\0';
  371. return out;
  372. }
  373. /** Release storage held by <b>options</b> */
  374. static void
  375. free_options(or_options_t *options)
  376. {
  377. config_free_lines(options->LogOptions);
  378. tor_free(options->ContactInfo);
  379. tor_free(options->DebugLogFile);
  380. tor_free(options->DataDirectory);
  381. tor_free(options->RouterFile);
  382. tor_free(options->Nickname);
  383. tor_free(options->Address);
  384. tor_free(options->PidFile);
  385. tor_free(options->ExitNodes);
  386. tor_free(options->EntryNodes);
  387. tor_free(options->ExcludeNodes);
  388. tor_free(options->RendNodes);
  389. tor_free(options->RendExcludeNodes);
  390. tor_free(options->OutboundBindAddress);
  391. tor_free(options->RecommendedVersions);
  392. tor_free(options->User);
  393. tor_free(options->Group);
  394. tor_free(options->HttpProxy);
  395. config_free_lines(options->RendConfigLines);
  396. config_free_lines(options->SocksBindAddress);
  397. config_free_lines(options->ORBindAddress);
  398. config_free_lines(options->DirBindAddress);
  399. config_free_lines(options->ExitPolicy);
  400. config_free_lines(options->SocksPolicy);
  401. config_free_lines(options->DirServers);
  402. if (options->FirewallPorts) {
  403. SMARTLIST_FOREACH(options->FirewallPorts, char *, cp, tor_free(cp));
  404. smartlist_free(options->FirewallPorts);
  405. options->FirewallPorts = NULL;
  406. }
  407. }
  408. /** Set <b>options</b> to hold reasonable defaults for most options.
  409. * Each option defaults to zero. */
  410. static void
  411. init_options(or_options_t *options)
  412. {
  413. memset(options,0,sizeof(or_options_t));
  414. options->LogOptions = NULL;
  415. options->ExitNodes = tor_strdup("");
  416. options->EntryNodes = tor_strdup("");
  417. options->StrictEntryNodes = options->StrictExitNodes = 0;
  418. options->ExcludeNodes = tor_strdup("");
  419. options->RendNodes = tor_strdup("");
  420. options->RendExcludeNodes = tor_strdup("");
  421. options->ExitPolicy = NULL;
  422. options->SocksPolicy = NULL;
  423. options->SocksBindAddress = NULL;
  424. options->ORBindAddress = NULL;
  425. options->DirBindAddress = NULL;
  426. options->OutboundBindAddress = NULL;
  427. options->RecommendedVersions = NULL;
  428. options->PidFile = NULL; // tor_strdup("tor.pid");
  429. options->DataDirectory = NULL;
  430. options->PathlenCoinWeight = 0.3;
  431. options->MaxConn = 900;
  432. options->DirFetchPostPeriod = 600;
  433. options->KeepalivePeriod = 300;
  434. options->MaxOnionsPending = 100;
  435. options->NewCircuitPeriod = 30; /* twice a minute */
  436. options->BandwidthRate = 800000; /* at most 800kB/s total sustained incoming */
  437. options->BandwidthBurst = 10000000; /* max burst on the token bucket */
  438. options->NumCpus = 1;
  439. options->RendConfigLines = NULL;
  440. options->FirewallPorts = NULL;
  441. options->DirServers = NULL;
  442. }
  443. static char *
  444. get_default_conf_file(void)
  445. {
  446. #ifdef MS_WINDOWS
  447. LPITEMIDLIST idl;
  448. IMalloc *m;
  449. HRESULT result;
  450. char *path = tor_malloc(MAX_PATH);
  451. /* Find X:\documents and settings\username\applicatation data\ .
  452. * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
  453. */
  454. if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, CSIDL_APPDATA,
  455. &idl))) {
  456. tor_free(path);
  457. return NULL;
  458. }
  459. /* Convert the path from an "ID List" (whatever that is!) to a path. */
  460. result = SHGetPathFromIDList(idl, path);
  461. /* Now we need to free the */
  462. SHGetMalloc(&m);
  463. if (m) {
  464. m->lpVtbl->Free(m, idl);
  465. m->lpVtbl->Release(m);
  466. }
  467. if (!SUCCEEDED(result)) {
  468. tor_free(path);
  469. return NULL;
  470. }
  471. strlcat(path,"\\tor\\torrc",MAX_PATH);
  472. return path;
  473. #else
  474. return tor_strdup(CONFDIR "/torrc");
  475. #endif
  476. }
  477. /** Read a configuration file into <b>options</b>, finding the configuration
  478. * file location based on the command line. After loading the options,
  479. * validate them for consistency. Return 0 if success, <0 if failure. */
  480. int
  481. getconfig(int argc, char **argv, or_options_t *options)
  482. {
  483. struct config_line_t *cl;
  484. FILE *cf;
  485. char *fname;
  486. int i;
  487. int result = 0;
  488. static int first_load = 1;
  489. static char **backup_argv;
  490. static int backup_argc;
  491. char *previous_pidfile = NULL;
  492. int previous_runasdaemon = 0;
  493. int previous_orport = -1;
  494. int using_default_torrc;
  495. if (first_load) { /* first time we're called. save commandline args */
  496. backup_argv = argv;
  497. backup_argc = argc;
  498. first_load = 0;
  499. } else { /* we're reloading. need to clean up old ones first. */
  500. argv = backup_argv;
  501. argc = backup_argc;
  502. /* record some previous values, so we can fail if they change */
  503. if (options->PidFile)
  504. previous_pidfile = tor_strdup(options->PidFile);
  505. previous_runasdaemon = options->RunAsDaemon;
  506. previous_orport = options->ORPort;
  507. free_options(options);
  508. }
  509. init_options(options);
  510. if (argc > 1 && (!strcmp(argv[1], "-h") || !strcmp(argv[1],"--help"))) {
  511. print_usage();
  512. exit(0);
  513. }
  514. if (argc > 1 && (!strcmp(argv[1],"--version"))) {
  515. printf("Tor version %s.\n",VERSION);
  516. exit(0);
  517. }
  518. /* learn config file name, get config lines, assign them */
  519. i = 1;
  520. while (i < argc-1 && strcmp(argv[i],"-f")) {
  521. i++;
  522. }
  523. if (i < argc-1) { /* we found one */
  524. fname = tor_strdup(argv[i+1]);
  525. using_default_torrc = 0;
  526. } else {
  527. /* didn't find one, try CONFDIR */
  528. char *fn;
  529. using_default_torrc = 1;
  530. fn = get_default_conf_file();
  531. if (fn && file_status(fn) == FN_FILE) {
  532. fname = fn;
  533. } else {
  534. tor_free(fn);
  535. fn = expand_filename("~/.torrc");
  536. if (fn && file_status(fn) == FN_FILE) {
  537. fname = fn;
  538. } else {
  539. tor_free(fn);
  540. fname = get_default_conf_file();
  541. }
  542. }
  543. }
  544. tor_assert(fname);
  545. log(LOG_DEBUG, "Opening config file '%s'", fname);
  546. if (config_assign_defaults(options) < 0) {
  547. return -1;
  548. }
  549. cf = fopen(fname, "r");
  550. if (!cf) {
  551. if (using_default_torrc == 1) {
  552. log(LOG_NOTICE, "Configuration file '%s' not present, "
  553. "using reasonable defaults.", fname);
  554. tor_free(fname);
  555. } else {
  556. log(LOG_WARN, "Unable to open configuration file '%s'.", fname);
  557. tor_free(fname);
  558. return -1;
  559. }
  560. } else { /* it opened successfully. use it. */
  561. tor_free(fname);
  562. if (config_get_lines(cf, &cl)<0)
  563. return -1;
  564. if (config_assign(options,cl) < 0)
  565. return -1;
  566. config_free_lines(cl);
  567. fclose(cf);
  568. }
  569. /* go through command-line variables too */
  570. cl = config_get_commandlines(argc,argv);
  571. if (config_assign(options,cl) < 0)
  572. return -1;
  573. config_free_lines(cl);
  574. /* Validate options */
  575. /* first check if any of the previous options have changed but aren't allowed to */
  576. if (previous_pidfile && strcmp(previous_pidfile,options->PidFile)) {
  577. log_fn(LOG_WARN,"During reload, PidFile changed from %s to %s. Failing.",
  578. previous_pidfile, options->PidFile);
  579. return -1;
  580. }
  581. tor_free(previous_pidfile);
  582. if (previous_runasdaemon && !options->RunAsDaemon) {
  583. log_fn(LOG_WARN,"During reload, change from RunAsDaemon=1 to =0 not allowed. Failing.");
  584. return -1;
  585. }
  586. if (previous_orport == 0 && options->ORPort > 0) {
  587. log_fn(LOG_WARN,"During reload, change from ORPort=0 to >0 not allowed. Failing.");
  588. return -1;
  589. }
  590. if (options->ORPort < 0 || options->ORPort > 65535) {
  591. log(LOG_WARN, "ORPort option out of bounds.");
  592. result = -1;
  593. }
  594. if (options->Nickname == NULL) {
  595. if (server_mode()) {
  596. if (!(options->Nickname = get_default_nickname()))
  597. return -1;
  598. log_fn(LOG_NOTICE, "Choosing default nickname %s", options->Nickname);
  599. }
  600. } else {
  601. if (strspn(options->Nickname, LEGAL_NICKNAME_CHARACTERS) !=
  602. strlen(options->Nickname)) {
  603. log_fn(LOG_WARN, "Nickname '%s' contains illegal characters.", options->Nickname);
  604. result = -1;
  605. }
  606. if (strlen(options->Nickname) == 0) {
  607. log_fn(LOG_WARN, "Nickname must have at least one character");
  608. result = -1;
  609. }
  610. if (strlen(options->Nickname) > MAX_NICKNAME_LEN) {
  611. log_fn(LOG_WARN, "Nickname '%s' has more than %d characters.",
  612. options->Nickname, MAX_NICKNAME_LEN);
  613. result = -1;
  614. }
  615. }
  616. if (server_mode()) {
  617. /* confirm that our address isn't broken, so we can complain now */
  618. uint32_t tmp;
  619. if (resolve_my_address(options->Address, &tmp) < 0)
  620. result = -1;
  621. }
  622. if (options->SocksPort < 0 || options->SocksPort > 65535) {
  623. log(LOG_WARN, "SocksPort option out of bounds.");
  624. result = -1;
  625. }
  626. if (options->SocksPort == 0 && options->ORPort == 0) {
  627. log(LOG_WARN, "SocksPort and ORPort are both undefined? Quitting.");
  628. result = -1;
  629. }
  630. if (options->DirPort < 0 || options->DirPort > 65535) {
  631. log(LOG_WARN, "DirPort option out of bounds.");
  632. result = -1;
  633. }
  634. if (options->StrictExitNodes && !strlen(options->ExitNodes)) {
  635. log(LOG_WARN, "StrictExitNodes set, but no ExitNodes listed.");
  636. }
  637. if (options->StrictEntryNodes && !strlen(options->EntryNodes)) {
  638. log(LOG_WARN, "StrictEntryNodes set, but no EntryNodes listed.");
  639. }
  640. if (options->AuthoritativeDir && options->RecommendedVersions == NULL) {
  641. log(LOG_WARN, "Directory servers must configure RecommendedVersions.");
  642. result = -1;
  643. }
  644. if (options->AuthoritativeDir && !options->DirPort) {
  645. log(LOG_WARN, "Running as authoritative directory, but no DirPort set.");
  646. result = -1;
  647. }
  648. if (options->AuthoritativeDir && !options->ORPort) {
  649. log(LOG_WARN, "Running as authoritative directory, but no ORPort set.");
  650. result = -1;
  651. }
  652. if (options->AuthoritativeDir && options->ClientOnly) {
  653. log(LOG_WARN, "Running as authoritative directory, but ClientOnly also set.");
  654. result = -1;
  655. }
  656. if (options->FascistFirewall && !options->FirewallPorts) {
  657. options->FirewallPorts = smartlist_create();
  658. smartlist_add(options->FirewallPorts, tor_strdup("80"));
  659. smartlist_add(options->FirewallPorts, tor_strdup("443"));
  660. }
  661. if (options->FirewallPorts) {
  662. SMARTLIST_FOREACH(options->FirewallPorts, const char *, cp,
  663. {
  664. i = atoi(cp);
  665. if (i < 1 || i > 65535) {
  666. log(LOG_WARN, "Port '%s' out of range in FirewallPorts", cp);
  667. result=-1;
  668. }
  669. });
  670. }
  671. options->_AllowUnverified = 0;
  672. if (options->AllowUnverifiedNodes) {
  673. SMARTLIST_FOREACH(options->AllowUnverifiedNodes, const char *, cp, {
  674. if (!strcasecmp(cp, "entry"))
  675. options->_AllowUnverified |= ALLOW_UNVERIFIED_ENTRY;
  676. else if (!strcasecmp(cp, "exit"))
  677. options->_AllowUnverified |= ALLOW_UNVERIFIED_EXIT;
  678. else if (!strcasecmp(cp, "middle"))
  679. options->_AllowUnverified |= ALLOW_UNVERIFIED_MIDDLE;
  680. else if (!strcasecmp(cp, "introduction"))
  681. options->_AllowUnverified |= ALLOW_UNVERIFIED_INTRODUCTION;
  682. else if (!strcasecmp(cp, "rendezvous"))
  683. options->_AllowUnverified |= ALLOW_UNVERIFIED_RENDEZVOUS;
  684. else {
  685. log(LOG_WARN, "Unrecognized value '%s' in AllowUnverifiedNodes",
  686. cp);
  687. result=-1;
  688. }
  689. });
  690. }
  691. if (options->SocksPort >= 1 &&
  692. (options->PathlenCoinWeight < 0.0 || options->PathlenCoinWeight >= 1.0)) {
  693. log(LOG_WARN, "PathlenCoinWeight option must be >=0.0 and <1.0.");
  694. result = -1;
  695. }
  696. if (options->MaxConn < 1) {
  697. log(LOG_WARN, "MaxConn option must be a non-zero positive integer.");
  698. result = -1;
  699. }
  700. if (options->MaxConn >= MAXCONNECTIONS) {
  701. log(LOG_WARN, "MaxConn option must be less than %d.", MAXCONNECTIONS);
  702. result = -1;
  703. }
  704. #define MIN_DIRFETCHPOSTPERIOD 60
  705. if (options->DirFetchPostPeriod < MIN_DIRFETCHPOSTPERIOD) {
  706. log(LOG_WARN, "DirFetchPostPeriod option must be at least %d.", MIN_DIRFETCHPOSTPERIOD);
  707. result = -1;
  708. }
  709. if (options->DirFetchPostPeriod > MIN_ONION_KEY_LIFETIME / 2) {
  710. log(LOG_WARN, "DirFetchPostPeriod is too large; clipping.");
  711. options->DirFetchPostPeriod = MIN_ONION_KEY_LIFETIME / 2;
  712. }
  713. if (options->KeepalivePeriod < 1) {
  714. log(LOG_WARN,"KeepalivePeriod option must be positive.");
  715. result = -1;
  716. }
  717. if (options->HttpProxy) { /* parse it now */
  718. if (parse_addr_port(options->HttpProxy, NULL,
  719. &options->HttpProxyAddr, &options->HttpProxyPort) < 0) {
  720. log(LOG_WARN,"HttpProxy failed to parse or resolve. Please fix.");
  721. result = -1;
  722. }
  723. options->HttpProxyAddr = ntohl(options->HttpProxyAddr); /* switch to host-order */
  724. if (options->HttpProxyPort == 0) { /* give it a default */
  725. options->HttpProxyPort = 80;
  726. }
  727. }
  728. clear_trusted_dir_servers();
  729. if (!options->DirServers) {
  730. add_default_trusted_dirservers();
  731. } else {
  732. for (cl = options->DirServers; cl; cl = cl->next) {
  733. if (parse_dir_server_line(cl->value)<0)
  734. return -1;
  735. }
  736. }
  737. /* XXX look at the various nicknamelists and make sure they're
  738. * valid and don't have hostnames that are too long.
  739. */
  740. if (rend_config_services(options) < 0) {
  741. result = -1;
  742. }
  743. return result;
  744. }
  745. static int
  746. add_single_log(struct config_line_t *level_opt,
  747. struct config_line_t *file_opt, int isDaemon)
  748. {
  749. int levelMin = -1, levelMax = -1;
  750. char *cp, *tmp_sev;
  751. if (level_opt) {
  752. cp = strchr(level_opt->value, '-');
  753. if (cp) {
  754. tmp_sev = tor_strndup(level_opt->value, cp - level_opt->value);
  755. levelMin = parse_log_level(tmp_sev);
  756. if (levelMin < 0) {
  757. log_fn(LOG_WARN, "Unrecognized log severity '%s': must be one of "
  758. "err|warn|notice|info|debug", tmp_sev);
  759. return -1;
  760. }
  761. tor_free(tmp_sev);
  762. levelMax = parse_log_level(cp+1);
  763. if (levelMax < 0) {
  764. log_fn(LOG_WARN, "Unrecognized log severity '%s': must be one of "
  765. "err|warn|notice|info|debug", cp+1);
  766. return -1;
  767. }
  768. } else {
  769. levelMin = parse_log_level(level_opt->value);
  770. if (levelMin < 0) {
  771. log_fn(LOG_WARN, "Unrecognized log severity '%s': must be one of "
  772. "err|warn|notice|info|debug", level_opt->value);
  773. return -1;
  774. }
  775. }
  776. }
  777. if (levelMin < 0 && levelMax < 0) {
  778. levelMin = LOG_NOTICE;
  779. levelMax = LOG_ERR;
  780. } else if (levelMin < 0) {
  781. levelMin = levelMax;
  782. } else {
  783. levelMax = LOG_ERR;
  784. }
  785. if (file_opt) {
  786. if (add_file_log(levelMin, levelMax, file_opt->value) < 0) {
  787. log_fn(LOG_WARN, "Cannot write to LogFile '%s': %s.", file_opt->value,
  788. strerror(errno));
  789. return -1;
  790. }
  791. log_fn(LOG_NOTICE, "Successfully opened LogFile '%s', redirecting output.",
  792. file_opt->value);
  793. } else if (!isDaemon) {
  794. add_stream_log(levelMin, levelMax, "<stdout>", stdout);
  795. close_temp_logs();
  796. }
  797. return 0;
  798. }
  799. /**
  800. * Initialize the logs based on the configuration file.
  801. */
  802. int
  803. config_init_logs(or_options_t *options)
  804. {
  805. /* The order of options is: Level? (File Level?)+
  806. */
  807. struct config_line_t *opt = options->LogOptions;
  808. /* Special case if no options are given. */
  809. if (!opt) {
  810. add_stream_log(LOG_NOTICE, LOG_ERR, "<stdout>", stdout);
  811. close_temp_logs();
  812. /* don't return yet, in case we want to do a debuglogfile below */
  813. }
  814. /* Special case for if first option is LogLevel. */
  815. if (opt && !strcasecmp(opt->key, "LogLevel")) {
  816. if (opt->next && !strcasecmp(opt->next->key, "LogFile")) {
  817. if (add_single_log(opt, opt->next, options->RunAsDaemon) < 0)
  818. return -1;
  819. opt = opt->next->next;
  820. } else if (!opt->next) {
  821. if (add_single_log(opt, NULL, options->RunAsDaemon) < 0)
  822. return -1;
  823. opt = opt->next;
  824. } else {
  825. ; /* give warning below */
  826. }
  827. }
  828. while (opt) {
  829. if (!strcasecmp(opt->key, "LogLevel")) {
  830. log_fn(LOG_WARN, "Two LogLevel options in a row without intervening LogFile");
  831. opt = opt->next;
  832. } else {
  833. tor_assert(!strcasecmp(opt->key, "LogFile"));
  834. if (opt->next && !strcasecmp(opt->next->key, "LogLevel")) {
  835. /* LogFile followed by LogLevel */
  836. if (add_single_log(opt->next, opt, options->RunAsDaemon) < 0)
  837. return -1;
  838. opt = opt->next->next;
  839. } else {
  840. /* LogFile followed by LogFile or end of list. */
  841. if (add_single_log(NULL, opt, options->RunAsDaemon) < 0)
  842. return -1;
  843. opt = opt->next;
  844. }
  845. }
  846. }
  847. if (options->DebugLogFile) {
  848. log_fn(LOG_WARN, "DebugLogFile is deprecated; use LogFile and LogLevel instead");
  849. if (add_file_log(LOG_DEBUG, LOG_ERR, options->DebugLogFile) < 0)
  850. return -1;
  851. }
  852. return 0;
  853. }
  854. /**
  855. * Given a linked list of config lines containing "allow" and "deny" tokens,
  856. * parse them and place the result in <b>dest</b>. Skip malformed lines.
  857. */
  858. void
  859. config_parse_exit_policy(struct config_line_t *cfg,
  860. struct exit_policy_t **dest)
  861. {
  862. struct exit_policy_t **nextp;
  863. smartlist_t *entries;
  864. if (!cfg)
  865. return;
  866. nextp = dest;
  867. while (*nextp)
  868. nextp = &((*nextp)->next);
  869. entries = smartlist_create();
  870. for (; cfg; cfg = cfg->next) {
  871. smartlist_split_string(entries, cfg->value, ",", SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  872. SMARTLIST_FOREACH(entries, const char *, ent,
  873. {
  874. log_fn(LOG_DEBUG,"Adding new entry '%s'",ent);
  875. *nextp = router_parse_exit_policy_from_string(ent);
  876. if (*nextp) {
  877. nextp = &((*nextp)->next);
  878. } else {
  879. log_fn(LOG_WARN,"Malformed exit policy %s; skipping.", ent);
  880. }
  881. });
  882. SMARTLIST_FOREACH(entries, char *, ent, tor_free(ent));
  883. smartlist_clear(entries);
  884. }
  885. smartlist_free(entries);
  886. }
  887. void exit_policy_free(struct exit_policy_t *p) {
  888. struct exit_policy_t *e;
  889. while (p) {
  890. e = p;
  891. p = p->next;
  892. tor_free(e->string);
  893. tor_free(e);
  894. }
  895. }
  896. static int parse_dir_server_line(const char *line)
  897. {
  898. smartlist_t *items = NULL;
  899. int r;
  900. char *addrport, *address=NULL;
  901. uint16_t port;
  902. char digest[DIGEST_LEN];
  903. items = smartlist_create();
  904. smartlist_split_string(items, line, " ",
  905. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
  906. if (smartlist_len(items) < 2) {
  907. log_fn(LOG_WARN, "Too few arguments to DirServer line.");
  908. goto err;
  909. }
  910. addrport = smartlist_get(items, 0);
  911. if (parse_addr_port(addrport, &address, NULL, &port)<0) {
  912. log_fn(LOG_WARN, "Error parsing DirServer address '%s'", addrport);
  913. goto err;
  914. }
  915. if (!port) {
  916. log_fn(LOG_WARN, "Missing port in DirServe address '%s'",addrport);
  917. goto err;
  918. }
  919. tor_strstrip(smartlist_get(items, 1), " ");
  920. if (strlen(smartlist_get(items, 1)) != HEX_DIGEST_LEN) {
  921. log_fn(LOG_WARN, "Key digest for DirServer is wrong length.");
  922. goto err;
  923. }
  924. if (base16_decode(digest, DIGEST_LEN,
  925. smartlist_get(items,1), HEX_DIGEST_LEN)<0) {
  926. log_fn(LOG_WARN, "Unable to decode DirServer key digest.");
  927. goto err;
  928. }
  929. log_fn(LOG_DEBUG, "Trusted dirserver at %s:%d (%s)", address, (int)port,
  930. (char*)smartlist_get(items,1));
  931. add_trusted_dir_server(address, port, digest);
  932. r = 0;
  933. goto done;
  934. err:
  935. r = -1;
  936. done:
  937. SMARTLIST_FOREACH(items, char*, s, tor_free(s));
  938. smartlist_free(items);
  939. if (address)
  940. tor_free(address);
  941. return r;
  942. }
  943. const char *
  944. get_data_directory(or_options_t *options)
  945. {
  946. const char *d;
  947. if (options->DataDirectory) {
  948. d = options->DataDirectory;
  949. } else {
  950. #ifdef MS_WINDOWS
  951. char *p;
  952. p = tor_malloc(MAX_PATH);
  953. if (!SUCCEEDED(SHGetSpecialFolderPath(NULL, p, CSIDL_APPDATA, 1))) {
  954. strlcpy(p,CONFDIR, MAX_PATH);
  955. }
  956. strlcat(p,"\\tor",MAX_PATH);
  957. options->DataDirectory = p;
  958. return p;
  959. #else
  960. d = "~/.tor";
  961. #endif
  962. }
  963. if (d && strncmp(d,"~/",2) == 0) {
  964. char *fn = expand_filename(d);
  965. if (!fn) {
  966. log_fn(LOG_ERR,"Failed to expand filename '%s'. Exiting.", d);
  967. exit(1);
  968. }
  969. tor_free(options->DataDirectory);
  970. options->DataDirectory = fn;
  971. }
  972. return options->DataDirectory;
  973. }
  974. /*
  975. Local Variables:
  976. mode:c
  977. indent-tabs-mode:nil
  978. c-basic-offset:2
  979. End:
  980. */