config.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959
  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. /** Enumeration of types which option values can take */
  12. typedef enum config_type_t {
  13. CONFIG_TYPE_STRING = 0, /**< An arbitrary string. */
  14. CONFIG_TYPE_INT, /**< An integer */
  15. CONFIG_TYPE_DOUBLE, /**< A floating-point value */
  16. CONFIG_TYPE_BOOL, /**< A boolean value, expressed as 0 or 1. */
  17. CONFIG_TYPE_LINELIST, /**< Uninterpreted config lines */
  18. } config_type_t;
  19. /** Largest allowed config line */
  20. #define CONFIG_LINE_T_MAXLEN 4096
  21. static FILE *config_open(const unsigned char *filename);
  22. static int config_close(FILE *f);
  23. static struct config_line_t *config_get_commandlines(int argc, char **argv);
  24. static struct config_line_t *config_get_lines(FILE *f);
  25. static void config_free_lines(struct config_line_t *front);
  26. static int config_compare(struct config_line_t *c, const char *key, config_type_t type, void *arg);
  27. static int config_assign(or_options_t *options, struct config_line_t *list);
  28. /** Open a configuration file for reading */
  29. static FILE *config_open(const unsigned char *filename) {
  30. tor_assert(filename);
  31. if (strspn(filename,CONFIG_LEGAL_FILENAME_CHARACTERS) != strlen(filename)) {
  32. /* filename has illegal letters */
  33. return NULL;
  34. }
  35. return fopen(filename, "r");
  36. }
  37. /** Close the configuration file */
  38. static int config_close(FILE *f) {
  39. tor_assert(f);
  40. return fclose(f);
  41. }
  42. /** Helper: Read a list of configuration options from the command line. */
  43. static struct config_line_t *config_get_commandlines(int argc, char **argv) {
  44. struct config_line_t *new;
  45. struct config_line_t *front = NULL;
  46. char *s;
  47. int i = 1;
  48. while(i < argc-1) {
  49. if(!strcmp(argv[i],"-f")) {
  50. // log(LOG_DEBUG,"Commandline: skipping over -f.");
  51. i+=2; /* this is the config file option. ignore it. */
  52. continue;
  53. }
  54. new = tor_malloc(sizeof(struct config_line_t));
  55. s = argv[i];
  56. while(*s == '-')
  57. s++;
  58. new->key = tor_strdup(s);
  59. new->value = tor_strdup(argv[i+1]);
  60. log(LOG_DEBUG,"Commandline: parsed keyword '%s', value '%s'",
  61. new->key, new->value);
  62. new->next = front;
  63. front = new;
  64. i += 2;
  65. }
  66. return front;
  67. }
  68. /** Helper: allocate a new configuration option mapping 'key' to 'val',
  69. * prepend it to 'front', and return the newly allocated config_line_t */
  70. static struct config_line_t *
  71. config_line_prepend(struct config_line_t *front,
  72. const char *key,
  73. const char *val)
  74. {
  75. struct config_line_t *newline;
  76. newline = tor_malloc(sizeof(struct config_line_t));
  77. newline->key = tor_strdup(key);
  78. newline->value = tor_strdup(val);
  79. newline->next = front;
  80. return newline;
  81. }
  82. /** Helper: parse the config file and strdup into key/value
  83. * strings. Return list, or NULL if parsing the file failed. Warn and
  84. * ignore any misformatted lines. */
  85. static struct config_line_t *config_get_lines(FILE *f) {
  86. struct config_line_t *front = NULL;
  87. char line[CONFIG_LINE_T_MAXLEN];
  88. int result;
  89. char *key, *value;
  90. while( (result=parse_line_from_file(line,sizeof(line),f,&key,&value)) > 0) {
  91. front = config_line_prepend(front, key, value);
  92. }
  93. if(result < 0)
  94. return NULL;
  95. return front;
  96. }
  97. /**
  98. * Free all the configuration lines on the linked list <b>front</b>.
  99. */
  100. static void config_free_lines(struct config_line_t *front) {
  101. struct config_line_t *tmp;
  102. while(front) {
  103. tmp = front;
  104. front = tmp->next;
  105. free(tmp->key);
  106. free(tmp->value);
  107. free(tmp);
  108. }
  109. }
  110. /** Search the linked list <b>c</b> for any option whose key is <b>key</b>.
  111. * If such an option is found, interpret it as of type <b>type</b>, and store
  112. * the result in <b>arg</b>. If the option is misformatted, log a warning and
  113. * skip it.
  114. */
  115. static int config_compare(struct config_line_t *c, const char *key, config_type_t type, void *arg) {
  116. int i;
  117. if(strncasecmp(c->key,key,strlen(c->key)))
  118. return 0;
  119. if(strcasecmp(c->key,key)) {
  120. tor_free(c->key);
  121. c->key = tor_strdup(key);
  122. }
  123. /* it's a match. cast and assign. */
  124. log_fn(LOG_DEBUG,"Recognized keyword '%s' as %s, using value '%s'.",c->key,key,c->value);
  125. switch(type) {
  126. case CONFIG_TYPE_INT:
  127. *(int *)arg = atoi(c->value);
  128. break;
  129. case CONFIG_TYPE_BOOL:
  130. i = atoi(c->value);
  131. if (i != 0 && i != 1) {
  132. log(LOG_WARN, "Boolean keyword '%s' expects 0 or 1", c->key);
  133. return 0;
  134. }
  135. *(int *)arg = i;
  136. break;
  137. case CONFIG_TYPE_STRING:
  138. tor_free(*(char **)arg);
  139. *(char **)arg = tor_strdup(c->value);
  140. break;
  141. case CONFIG_TYPE_DOUBLE:
  142. *(double *)arg = atof(c->value);
  143. break;
  144. case CONFIG_TYPE_LINELIST:
  145. /* Note: this reverses the order that the lines appear in. That's
  146. * just fine, since we build up the list of lines reversed in the
  147. * first place. */
  148. *(struct config_line_t**)arg =
  149. config_line_prepend(*(struct config_line_t**)arg, c->key, c->value);
  150. break;
  151. }
  152. return 1;
  153. }
  154. /** Iterate through the linked list of options <b>list</b>.
  155. * For each item, convert as appropriate and assign to <b>options</b>.
  156. * If an item is unrecognized, return -1 immediately,
  157. * else return 0 for success. */
  158. static int config_assign(or_options_t *options, struct config_line_t *list) {
  159. while(list) {
  160. if(
  161. /* order matters here! abbreviated arguments use the first match. */
  162. /* string options */
  163. config_compare(list, "Address", CONFIG_TYPE_STRING, &options->Address) ||
  164. config_compare(list, "AuthoritativeDirectory",CONFIG_TYPE_BOOL, &options->AuthoritativeDir) ||
  165. config_compare(list, "BandwidthRate", CONFIG_TYPE_INT, &options->BandwidthRate) ||
  166. config_compare(list, "BandwidthBurst", CONFIG_TYPE_INT, &options->BandwidthBurst) ||
  167. config_compare(list, "ClientOnly", CONFIG_TYPE_BOOL, &options->ClientOnly) ||
  168. config_compare(list, "ContactInfo", CONFIG_TYPE_STRING, &options->ContactInfo) ||
  169. config_compare(list, "DebugLogFile", CONFIG_TYPE_STRING, &options->DebugLogFile) ||
  170. config_compare(list, "DataDirectory", CONFIG_TYPE_STRING, &options->DataDirectory) ||
  171. config_compare(list, "DirPort", CONFIG_TYPE_INT, &options->DirPort) ||
  172. config_compare(list, "DirBindAddress", CONFIG_TYPE_LINELIST, &options->DirBindAddress) ||
  173. config_compare(list, "DirFetchPostPeriod",CONFIG_TYPE_INT, &options->DirFetchPostPeriod) ||
  174. config_compare(list, "ExitNodes", CONFIG_TYPE_STRING, &options->ExitNodes) ||
  175. config_compare(list, "EntryNodes", CONFIG_TYPE_STRING, &options->EntryNodes) ||
  176. config_compare(list, "ExitPolicy", CONFIG_TYPE_LINELIST, &options->ExitPolicy) ||
  177. config_compare(list, "ExcludeNodes", CONFIG_TYPE_STRING, &options->ExcludeNodes) ||
  178. config_compare(list, "Group", CONFIG_TYPE_STRING, &options->Group) ||
  179. config_compare(list, "IgnoreVersion", CONFIG_TYPE_BOOL, &options->IgnoreVersion) ||
  180. config_compare(list, "KeepalivePeriod",CONFIG_TYPE_INT, &options->KeepalivePeriod) ||
  181. config_compare(list, "LogLevel", CONFIG_TYPE_LINELIST, &options->LogOptions) ||
  182. config_compare(list, "LogFile", CONFIG_TYPE_LINELIST, &options->LogOptions) ||
  183. config_compare(list, "LinkPadding", CONFIG_TYPE_BOOL, &options->LinkPadding) ||
  184. config_compare(list, "MaxConn", CONFIG_TYPE_INT, &options->MaxConn) ||
  185. config_compare(list, "MaxOnionsPending",CONFIG_TYPE_INT, &options->MaxOnionsPending) ||
  186. config_compare(list, "Nickname", CONFIG_TYPE_STRING, &options->Nickname) ||
  187. config_compare(list, "NewCircuitPeriod",CONFIG_TYPE_INT, &options->NewCircuitPeriod) ||
  188. config_compare(list, "NumCpus", CONFIG_TYPE_INT, &options->NumCpus) ||
  189. config_compare(list, "ORPort", CONFIG_TYPE_INT, &options->ORPort) ||
  190. config_compare(list, "ORBindAddress", CONFIG_TYPE_LINELIST, &options->ORBindAddress) ||
  191. config_compare(list, "PidFile", CONFIG_TYPE_STRING, &options->PidFile) ||
  192. config_compare(list, "PathlenCoinWeight",CONFIG_TYPE_DOUBLE, &options->PathlenCoinWeight) ||
  193. config_compare(list, "RouterFile", CONFIG_TYPE_STRING, &options->RouterFile) ||
  194. config_compare(list, "RunAsDaemon", CONFIG_TYPE_BOOL, &options->RunAsDaemon) ||
  195. config_compare(list, "RecommendedVersions",CONFIG_TYPE_STRING, &options->RecommendedVersions) ||
  196. config_compare(list, "RendNodes", CONFIG_TYPE_STRING, &options->RendNodes) ||
  197. config_compare(list, "RendExcludeNodes",CONFIG_TYPE_STRING, &options->RendExcludeNodes) ||
  198. config_compare(list, "SocksPort", CONFIG_TYPE_INT, &options->SocksPort) ||
  199. config_compare(list, "SocksBindAddress",CONFIG_TYPE_LINELIST,&options->SocksBindAddress) ||
  200. config_compare(list, "SocksPolicy", CONFIG_TYPE_LINELIST,&options->SocksPolicy) ||
  201. config_compare(list, "TrafficShaping", CONFIG_TYPE_BOOL, &options->TrafficShaping) ||
  202. config_compare(list, "User", CONFIG_TYPE_STRING, &options->User) ||
  203. config_compare(list, "RunTesting", CONFIG_TYPE_BOOL, &options->RunTesting) ||
  204. config_compare(list, "HiddenServiceDir", CONFIG_TYPE_LINELIST, &options->RendConfigLines)||
  205. config_compare(list, "HiddenServicePort", CONFIG_TYPE_LINELIST, &options->RendConfigLines)||
  206. config_compare(list, "HiddenServiceNodes", CONFIG_TYPE_LINELIST, &options->RendConfigLines)||
  207. config_compare(list, "HiddenServiceExcludeNodes", CONFIG_TYPE_LINELIST, &options->RendConfigLines)
  208. ) {
  209. /* then we're ok. it matched something. */
  210. } else {
  211. log_fn(LOG_WARN,"Unknown keyword '%s'. Failing.",list->key);
  212. return -1;
  213. }
  214. list = list->next;
  215. }
  216. return 0;
  217. }
  218. const char default_dirservers_string[] =
  219. "router moria1 18.244.0.188 9001 9021 9031\n"
  220. "platform Tor 0.0.6rc1 on Linux moria.mit.edu i686\n"
  221. "published 2004-04-25 21:54:28\n"
  222. "bandwidth 800000 10000000\n"
  223. "onion-key\n"
  224. "-----BEGIN RSA PUBLIC KEY-----\n"
  225. "MIGJAoGBANoIvHieyHUTzIacbnWOnyTyzGrLOdXqbcjz2GGMxyHEd5K1bO1ZBNHP\n"
  226. "9i5qLQpN5viFk2K2rEGuG8tFgDEzSWZEtBqv3NVfUdiumdERWMBwlaQ0MVK4C+jf\n"
  227. "y5gZ8KI3o9ZictgPS1AQF+Kk932/vIHTuRIUKb4ILTnQilNvID0NAgMBAAE=\n"
  228. "-----END RSA PUBLIC KEY-----\n"
  229. "signing-key\n"
  230. "-----BEGIN RSA PUBLIC KEY-----\n"
  231. "MIGJAoGBAMHa0ZC/jo2Q2DrwKYF/6ZbmZ27PFYG91u4gUzzmZ/VXLpZ8wNzEV3oW\n"
  232. "nt+I61048fBiC1frT1/DZ351n2bLSk9zJbB6jyGZJn0380FPRX3+cXyXS0Gq8Ril\n"
  233. "xkhMQf5XuNFUb8UmYPSOH4WErjvYjKvU+gfjbK/82Jo9SuHpYz+BAgMBAAE=\n"
  234. "-----END RSA PUBLIC KEY-----\n"
  235. "reject 0.0.0.0/255.0.0.0:*\n"
  236. "reject 169.254.0.0/255.255.0.0:*\n"
  237. "reject 127.0.0.0/255.0.0.0:*\n"
  238. "reject 192.168.0.0/255.255.0.0:*\n"
  239. "reject 10.0.0.0/255.0.0.0:*\n"
  240. "reject 172.16.0.0/255.240.0.0:*\n"
  241. "accept *:20-22\n"
  242. "accept *:53\n"
  243. "accept *:79-80\n"
  244. "accept *:110\n"
  245. "accept *:143\n"
  246. "accept *:443\n"
  247. "accept *:873\n"
  248. "accept *:993\n"
  249. "accept *:995\n"
  250. "accept *:1024-65535\n"
  251. "reject *:*\n"
  252. "router-signature\n"
  253. "-----BEGIN SIGNATURE-----\n"
  254. "o1eAoRHDAEAXsnh5wN++vIwrupd+DbAJ2p3wxHDrmqxTpygzxxCnyQyhMfX03ua2\n"
  255. "4iplyNlwyFwzWcw0sk31otlO2HBYXT1V9G0YxGtKMOeOBMHjfGbUjGvEALHzWi4z\n"
  256. "8DXGJp13zgnUyP4ZA6xaGROwcT6oB5e7UlztvvpGxTg=\n"
  257. "-----END SIGNATURE-----\n"
  258. "\n"
  259. "router moria2 18.244.0.188 9002 9022 9032\n"
  260. "platform Tor 0.0.6rc1 on Linux moria.mit.edu i686\n"
  261. "published 2004-04-25 21:54:30\n"
  262. "bandwidth 800000 10000000\n"
  263. "onion-key\n"
  264. "-----BEGIN RSA PUBLIC KEY-----\n"
  265. "MIGJAoGBAM4Cc/npgYC54XrYLC+grVxJp7PDmNO2DRRJOxKttBBtvLpnR1UaueTi\n"
  266. "kyknT5kmlx+ihgZF/jmye//2dDUp2+kK/kSkpRV4xnDLXZmed+sNSQxqmm9TtZQ9\n"
  267. "/hjpxhp5J9HmUTYhntBs+4E4CUKokmrI6oRLoln4SA39AX9QLPcnAgMBAAE=\n"
  268. "-----END RSA PUBLIC KEY-----\n"
  269. "signing-key\n"
  270. "-----BEGIN RSA PUBLIC KEY-----\n"
  271. "MIGJAoGBAOcrht/y5rkaahfX7sMe2qnpqoPibsjTSJaDvsUtaNP/Bq0MgNDGOR48\n"
  272. "rtwfqTRff275Edkp/UYw3G3vSgKCJr76/bqOHCmkiZrnPV1zxNfrK18gNw2Cxre0\n"
  273. "nTA+fD8JQqpPtb8b0SnG9kwy75eS//sRu7TErie2PzGMxrf9LH0LAgMBAAE=\n"
  274. "-----END RSA PUBLIC KEY-----\n"
  275. "reject 0.0.0.0/255.0.0.0:*\n"
  276. "reject 169.254.0.0/255.255.0.0:*\n"
  277. "reject 127.0.0.0/255.0.0.0:*\n"
  278. "reject 192.168.0.0/255.255.0.0:*\n"
  279. "reject 10.0.0.0/255.0.0.0:*\n"
  280. "reject 172.16.0.0/255.240.0.0:*\n"
  281. "accept *:20-22\n"
  282. "accept *:53\n"
  283. "accept *:79-80\n"
  284. "accept *:110\n"
  285. "accept *:143\n"
  286. "accept *:443\n"
  287. "accept *:873\n"
  288. "accept *:993\n"
  289. "accept *:995\n"
  290. "accept *:1024-65535\n"
  291. "reject *:*\n"
  292. "router-signature\n"
  293. "-----BEGIN SIGNATURE-----\n"
  294. "RKROLwP1ExjTZeg6wuN0pzYqed9IJUd5lAe9hp4ritbnmJAgS6qfww6jgx61CfUR\n"
  295. "6SElhOLE7Q77jAdoL45Ji5pn/Y+Q+E+5lJm1E/ed9ha+YsOPaOc7z6GQ7E4mihCL\n"
  296. "gI1vsw92+P1Ty4RHj6fyD9DhbV19nh2Qs+pvGJOS2FY=\n"
  297. "-----END SIGNATURE-----\n"
  298. "\n"
  299. "router tor26 62.116.124.106 9001 9050 9030\n"
  300. "platform Tor 0.0.6 on Linux seppia i686\n"
  301. "published 2004-05-06 21:33:23\n"
  302. "bandwidth 500000 10000000\n"
  303. "onion-key\n"
  304. "-----BEGIN RSA PUBLIC KEY-----\n"
  305. "MIGJAoGBAMEHdDnpj3ik1AF1xe/VqjoguH2DbANifYqXXfempu0fS+tU9FGo6dU/\n"
  306. "fnVHAZwL9Ek9k2rMzumShi1RduK9p035R/Gk+PBBcLfvwYJ/Nat+ZO/L8jn/3bZe\n"
  307. "ieQd9CKj2LjNGKpRNry37vkwMGIOIlegwK+2us8aXJ7sIvlNts0TAgMBAAE=\n"
  308. "-----END RSA PUBLIC KEY-----\n"
  309. "signing-key\n"
  310. "-----BEGIN RSA PUBLIC KEY-----\n"
  311. "MIGJAoGBAMQgV2gXLbXgesWgeAsj8P1Uvm/zibrFXqwDq27lLKNgWGYGX2ax3LyT\n"
  312. "3nzI1Y5oLs4kPKTsMM5ft9aokwf417lKoCRlZc9ptfRbgxDx90c9GtWVmkrmDvCK\n"
  313. "ae59TMoXIiGfZiwWT6KKq5Zm9/Fu2Il3B2vHGkKJYKixmiBJRKp/AgMBAAE=\n"
  314. "-----END RSA PUBLIC KEY-----\n"
  315. "accept 62.245.184.24:25\n"
  316. "accept 62.116.124.106:6666-6670\n"
  317. "accept *:48099\n"
  318. "reject *:*\n"
  319. "router-signature\n"
  320. "-----BEGIN SIGNATURE-----\n"
  321. "qh/xRoqfLNFzPaB8VdpbdMAwRyuk5qjx4LeLVQ2pDwTZ55PqmG99+VKUNte2WTTD\n"
  322. "7dZEA7um2rueohGe4nYmvbhJWr20/I0ZxmWDRDvFy0b5nwzDMGvLvDw95Zu/XJQ2\n"
  323. "md32NE3y9VZCfbCN+GlvETX3fdR3Svzcm8Kzesg2/s4=\n"
  324. "-----END SIGNATURE-----\n"
  325. ;
  326. int config_assign_default_dirservers(void) {
  327. if(router_load_routerlist_from_string(default_dirservers_string, 1) < 0) {
  328. log_fn(LOG_WARN,"Bug: the default dirservers internal string is corrupt.");
  329. return -1;
  330. }
  331. return 0;
  332. }
  333. /** Set <b>options</b> to a reasonable default.
  334. *
  335. * Call this function when we can't find any torrc config file.
  336. */
  337. static int config_assign_defaults(or_options_t *options) {
  338. /* set them up as a client only */
  339. options->SocksPort = 9050;
  340. config_free_lines(options->ExitPolicy);
  341. options->ExitPolicy = config_line_prepend(NULL, "ExitPolicy", "reject *:*");
  342. /* plus give them a dirservers file */
  343. if(config_assign_default_dirservers() < 0)
  344. return -1;
  345. return 0;
  346. }
  347. /** Print a usage message for tor. */
  348. static void print_usage(void) {
  349. printf("tor -f <torrc> [args]\n"
  350. "See man page for more options. This -h is probably obsolete.\n\n"
  351. "-b <bandwidth>\t\tbytes/second rate limiting\n"
  352. "-d <file>\t\tDebug file\n"
  353. // "-m <max>\t\tMax number of connections\n"
  354. "-l <level>\t\tLog level\n"
  355. "-r <file>\t\tList of known routers\n");
  356. printf("\nClient options:\n"
  357. "-e \"nick1 nick2 ...\"\t\tExit nodes\n"
  358. "-s <IP>\t\t\tPort to bind to for Socks\n"
  359. );
  360. printf("\nServer options:\n"
  361. "-n <nick>\t\tNickname of router\n"
  362. "-o <port>\t\tOR port to bind to\n"
  363. "-p <file>\t\tPID file\n"
  364. );
  365. }
  366. /**
  367. * Adjust <b>options</b> to contain a reasonable value for Address.
  368. */
  369. static int resolve_my_address(or_options_t *options) {
  370. struct in_addr in;
  371. struct hostent *rent;
  372. char localhostname[256];
  373. int explicit_ip=1;
  374. if(!options->Address) { /* then we need to guess our address */
  375. explicit_ip = 0; /* it's implicit */
  376. if(gethostname(localhostname,sizeof(localhostname)) < 0) {
  377. log_fn(LOG_WARN,"Error obtaining local hostname");
  378. return -1;
  379. }
  380. #if 0 /* don't worry about complaining, as long as it resolves */
  381. if(!strchr(localhostname,'.')) {
  382. log_fn(LOG_WARN,"fqdn '%s' has only one element. Misconfigured machine?",address);
  383. log_fn(LOG_WARN,"Try setting the Address line in your config file.");
  384. return -1;
  385. }
  386. #endif
  387. options->Address = tor_strdup(localhostname);
  388. log_fn(LOG_DEBUG,"Guessed local host name as '%s'",options->Address);
  389. }
  390. /* now we know options->Address is set. resolve it and keep only the IP */
  391. if(tor_inet_aton(options->Address, &in) == 0) {
  392. /* then we have to resolve it */
  393. explicit_ip = 0;
  394. rent = (struct hostent *)gethostbyname(options->Address);
  395. if (!rent) {
  396. log_fn(LOG_WARN,"Could not resolve Address %s. Failing.", options->Address);
  397. return -1;
  398. }
  399. tor_assert(rent->h_length == 4);
  400. memcpy(&in.s_addr, rent->h_addr,rent->h_length);
  401. }
  402. if(!explicit_ip && is_internal_IP(htonl(in.s_addr))) {
  403. log_fn(LOG_WARN,"Address '%s' resolves to private IP '%s'. "
  404. "Please set the Address config option to be the IP you want to use.",
  405. options->Address, inet_ntoa(in));
  406. return -1;
  407. }
  408. tor_free(options->Address);
  409. options->Address = tor_strdup(inet_ntoa(in));
  410. log_fn(LOG_DEBUG,"Resolved Address to %s.", options->Address);
  411. return 0;
  412. }
  413. static char *get_default_nickname(void)
  414. {
  415. char localhostname[256];
  416. char *cp, *out, *outp;
  417. if(gethostname(localhostname,sizeof(localhostname)) < 0) {
  418. log_fn(LOG_WARN,"Error obtaining local hostname");
  419. return NULL;
  420. }
  421. /* Put it in lowercase; stop at the first dot. */
  422. for(cp = localhostname; *cp; ++cp) {
  423. if (*cp == '.') {
  424. *cp = '\0';
  425. break;
  426. }
  427. *cp = tolower(*cp);
  428. }
  429. /* Strip invalid characters. */
  430. cp = localhostname;
  431. out = outp = tor_malloc(strlen(localhostname)+1);
  432. while (*cp) {
  433. if (strchr(LEGAL_NICKNAME_CHARACTERS, *cp))
  434. *outp++ = *cp++;
  435. else
  436. cp++;
  437. }
  438. *outp = '\0';
  439. /* Enforce length. */
  440. if (strlen(out) > MAX_NICKNAME_LEN)
  441. out[MAX_NICKNAME_LEN]='\0';
  442. return out;
  443. }
  444. /** Release storage held by <b>options</b> */
  445. static void free_options(or_options_t *options) {
  446. config_free_lines(options->LogOptions);
  447. tor_free(options->ContactInfo);
  448. tor_free(options->DebugLogFile);
  449. tor_free(options->DataDirectory);
  450. tor_free(options->RouterFile);
  451. tor_free(options->Nickname);
  452. tor_free(options->Address);
  453. tor_free(options->PidFile);
  454. tor_free(options->ExitNodes);
  455. tor_free(options->EntryNodes);
  456. tor_free(options->ExcludeNodes);
  457. tor_free(options->RendNodes);
  458. tor_free(options->RendExcludeNodes);
  459. tor_free(options->RecommendedVersions);
  460. tor_free(options->User);
  461. tor_free(options->Group);
  462. config_free_lines(options->RendConfigLines);
  463. config_free_lines(options->SocksBindAddress);
  464. config_free_lines(options->ORBindAddress);
  465. config_free_lines(options->DirBindAddress);
  466. config_free_lines(options->ExitPolicy);
  467. config_free_lines(options->SocksPolicy);
  468. }
  469. /** Set <b>options</b> to hold reasonable defaults for most options. */
  470. static void init_options(or_options_t *options) {
  471. /* give reasonable values for each option. Defaults to zero. */
  472. memset(options,0,sizeof(or_options_t));
  473. options->LogOptions = NULL;
  474. options->ExitNodes = tor_strdup("");
  475. options->EntryNodes = tor_strdup("");
  476. options->ExcludeNodes = tor_strdup("");
  477. options->RendNodes = tor_strdup("");
  478. options->RendExcludeNodes = tor_strdup("");
  479. options->ExitPolicy = NULL;
  480. options->SocksPolicy = NULL;
  481. options->SocksBindAddress = NULL;
  482. options->ORBindAddress = NULL;
  483. options->DirBindAddress = NULL;
  484. options->RecommendedVersions = NULL;
  485. options->PidFile = NULL; // tor_strdup("tor.pid");
  486. options->DataDirectory = NULL;
  487. options->PathlenCoinWeight = 0.3;
  488. options->MaxConn = 900;
  489. options->DirFetchPostPeriod = 600;
  490. options->KeepalivePeriod = 300;
  491. options->MaxOnionsPending = 100;
  492. options->NewCircuitPeriod = 30; /* twice a minute */
  493. options->BandwidthRate = 800000; /* at most 800kB/s total sustained incoming */
  494. options->BandwidthBurst = 10000000; /* max burst on the token bucket */
  495. options->NumCpus = 1;
  496. options->RendConfigLines = NULL;
  497. }
  498. /** Read a configuration file into <b>options</b>, finding the configuration
  499. * file location based on the command line. After loading the options,
  500. * validate them for consistency. Return 0 if success, <0 if failure. */
  501. int getconfig(int argc, char **argv, or_options_t *options) {
  502. struct config_line_t *cl;
  503. FILE *cf;
  504. char *fname;
  505. int i;
  506. int result = 0;
  507. static int first_load = 1;
  508. static char **backup_argv;
  509. static int backup_argc;
  510. char *previous_pidfile = NULL;
  511. int previous_runasdaemon = 0;
  512. int previous_orport = -1;
  513. int using_default_torrc;
  514. if(first_load) { /* first time we're called. save commandline args */
  515. backup_argv = argv;
  516. backup_argc = argc;
  517. first_load = 0;
  518. } else { /* we're reloading. need to clean up old ones first. */
  519. argv = backup_argv;
  520. argc = backup_argc;
  521. /* record some previous values, so we can fail if they change */
  522. if(options->PidFile)
  523. previous_pidfile = tor_strdup(options->PidFile);
  524. previous_runasdaemon = options->RunAsDaemon;
  525. previous_orport = options->ORPort;
  526. free_options(options);
  527. }
  528. init_options(options);
  529. if(argc > 1 && (!strcmp(argv[1], "-h") || !strcmp(argv[1],"--help"))) {
  530. print_usage();
  531. exit(0);
  532. }
  533. if(argc > 1 && (!strcmp(argv[1],"--version"))) {
  534. printf("Tor version %s.\n",VERSION);
  535. exit(0);
  536. }
  537. /* learn config file name, get config lines, assign them */
  538. i = 1;
  539. while(i < argc-1 && strcmp(argv[i],"-f")) {
  540. i++;
  541. }
  542. if(i < argc-1) { /* we found one */
  543. fname = tor_strdup(argv[i+1]);
  544. using_default_torrc = 0;
  545. } else if (file_status(CONFDIR "/torrc")==FN_FILE) {
  546. /* didn't find one, try CONFDIR */
  547. fname = tor_strdup(CONFDIR "/torrc");
  548. using_default_torrc = 1;
  549. } else {
  550. char *fn = expand_filename("~/.torrc");
  551. if (file_status(fn)==FN_FILE) {
  552. fname = fn;
  553. } else {
  554. tor_free(fn);
  555. fname = tor_strdup(CONFDIR "/torrc");
  556. }
  557. using_default_torrc = 1;
  558. }
  559. log(LOG_DEBUG,"Opening config file '%s'",fname);
  560. cf = config_open(fname);
  561. if(!cf) {
  562. if(using_default_torrc == 1) {
  563. log(LOG_NOTICE, "Configuration file '%s' not present, using reasonable defaults.",fname);
  564. tor_free(fname);
  565. if(config_assign_defaults(options) < 0) {
  566. return -1;
  567. }
  568. } else {
  569. log(LOG_WARN, "Unable to open configuration file '%s'.",fname);
  570. tor_free(fname);
  571. return -1;
  572. }
  573. } else { /* it opened successfully. use it. */
  574. tor_free(fname);
  575. cl = config_get_lines(cf);
  576. if(!cl) return -1;
  577. if(config_assign(options,cl) < 0)
  578. return -1;
  579. config_free_lines(cl);
  580. config_close(cf);
  581. }
  582. /* go through command-line variables too */
  583. cl = config_get_commandlines(argc,argv);
  584. if(config_assign(options,cl) < 0)
  585. return -1;
  586. config_free_lines(cl);
  587. /* Validate options */
  588. /* first check if any of the previous options have changed but aren't allowed to */
  589. if(previous_pidfile && strcmp(previous_pidfile,options->PidFile)) {
  590. log_fn(LOG_WARN,"During reload, PidFile changed from %s to %s. Failing.",
  591. previous_pidfile, options->PidFile);
  592. return -1;
  593. }
  594. tor_free(previous_pidfile);
  595. if(previous_runasdaemon && !options->RunAsDaemon) {
  596. log_fn(LOG_WARN,"During reload, change from RunAsDaemon=1 to =0 not allowed. Failing.");
  597. return -1;
  598. }
  599. if(previous_orport == 0 && options->ORPort > 0) {
  600. log_fn(LOG_WARN,"During reload, change from ORPort=0 to >0 not allowed. Failing.");
  601. return -1;
  602. }
  603. if(options->ORPort < 0) {
  604. log(LOG_WARN,"ORPort option can't be negative.");
  605. result = -1;
  606. }
  607. if (options->Nickname == NULL) {
  608. if (!(options->Nickname = get_default_nickname()))
  609. return -1;
  610. log_fn(LOG_INFO, "Choosing default nickname %s", options->Nickname);
  611. } else {
  612. if (strspn(options->Nickname, LEGAL_NICKNAME_CHARACTERS) !=
  613. strlen(options->Nickname)) {
  614. log_fn(LOG_WARN, "Nickname '%s' contains illegal characters.", options->Nickname);
  615. result = -1;
  616. }
  617. if (strlen(options->Nickname) > MAX_NICKNAME_LEN) {
  618. log_fn(LOG_WARN, "Nickname '%s' has more than %d characters.",
  619. options->Nickname, MAX_NICKNAME_LEN);
  620. result = -1;
  621. }
  622. }
  623. if(options->ORPort) { /* get an IP for ourselves */
  624. if(resolve_my_address(options) < 0)
  625. result = -1;
  626. }
  627. if(options->SocksPort < 0) {
  628. log(LOG_WARN,"SocksPort option can't be negative.");
  629. result = -1;
  630. }
  631. if(options->SocksPort == 0 && options->ORPort == 0) {
  632. log(LOG_WARN,"SocksPort and ORPort are both undefined? Quitting.");
  633. result = -1;
  634. }
  635. if(options->DirPort < 0) {
  636. log(LOG_WARN,"DirPort option can't be negative.");
  637. result = -1;
  638. }
  639. if(options->AuthoritativeDir && options->RecommendedVersions == NULL) {
  640. log(LOG_WARN,"Directory servers must configure RecommendedVersions.");
  641. result = -1;
  642. }
  643. if(options->AuthoritativeDir && !options->DirPort) {
  644. log(LOG_WARN,"Running as authoritative directory, but no DirPort set.");
  645. result = -1;
  646. }
  647. /* XXX008 if AuthDir and !ORPort then fail */
  648. /* XXX008 if AuthDir and ClientOnly then fail */
  649. if(options->SocksPort >= 1 &&
  650. (options->PathlenCoinWeight < 0.0 || options->PathlenCoinWeight >= 1.0)) {
  651. log(LOG_WARN,"PathlenCoinWeight option must be >=0.0 and <1.0.");
  652. result = -1;
  653. }
  654. if(options->MaxConn < 1) {
  655. log(LOG_WARN,"MaxConn option must be a non-zero positive integer.");
  656. result = -1;
  657. }
  658. if(options->MaxConn >= MAXCONNECTIONS) {
  659. log(LOG_WARN,"MaxConn option must be less than %d.", MAXCONNECTIONS);
  660. result = -1;
  661. }
  662. if(options->DirFetchPostPeriod < 1) {
  663. log(LOG_WARN,"DirFetchPostPeriod option must be positive.");
  664. result = -1;
  665. }
  666. if(options->DirFetchPostPeriod > MIN_ONION_KEY_LIFETIME/2) {
  667. log(LOG_WARN,"DirFetchPostPeriod is too large; clipping.");
  668. options->DirFetchPostPeriod = MIN_ONION_KEY_LIFETIME/2;
  669. }
  670. if(options->KeepalivePeriod < 1) {
  671. log(LOG_WARN,"KeepalivePeriod option must be positive.");
  672. result = -1;
  673. }
  674. /* XXX look at the various nicknamelists and make sure they're
  675. * valid and don't have hostnames that are too long.
  676. */
  677. if (rend_config_services(options) < 0) {
  678. result = -1;
  679. }
  680. return result;
  681. }
  682. static int add_single_log(struct config_line_t *level_opt,
  683. struct config_line_t *file_opt,
  684. int isDaemon)
  685. {
  686. int levelMin=-1, levelMax=-1;
  687. char *cp, *tmp_sev;
  688. if (level_opt) {
  689. cp = strchr(level_opt->value, '-');
  690. if (cp) {
  691. tmp_sev = tor_strndup(level_opt->value, cp - level_opt->value);
  692. levelMin = parse_log_level(tmp_sev);
  693. if (levelMin<0) {
  694. log_fn(LOG_WARN, "Unrecognized log severity '%s': must be one of err|warn|notice|info|debug", tmp_sev);
  695. return -1;
  696. }
  697. tor_free(tmp_sev);
  698. levelMax = parse_log_level(cp+1);
  699. if (levelMax<0) {
  700. log_fn(LOG_WARN, "Unrecognized log severity '%s': must be one of err|warn|notice|info|debug", cp+1);
  701. return -1;
  702. }
  703. } else {
  704. levelMin = parse_log_level(level_opt->value);
  705. if (levelMin<0) {
  706. log_fn(LOG_WARN, "Unrecognized log severity '%s': must be one of err|warn|notice|info|debug", level_opt->value);
  707. return -1;
  708. }
  709. }
  710. }
  711. if (levelMin < 0 && levelMax < 0) {
  712. levelMin = LOG_NOTICE;
  713. levelMax = LOG_ERR;
  714. } else if (levelMin < 0) {
  715. levelMin = levelMax;
  716. } else {
  717. levelMax = LOG_ERR;
  718. }
  719. if (file_opt) {
  720. if (add_file_log(levelMin, levelMax, file_opt->value) < 0) {
  721. log_fn(LOG_WARN, "Cannot write to LogFile '%s': %s.", file_opt->value,
  722. strerror(errno));
  723. return -1;
  724. }
  725. log_fn(LOG_NOTICE, "Successfully opened LogFile '%s', redirecting output.",
  726. file_opt->value);
  727. } else if (!isDaemon) {
  728. add_stream_log(levelMin, levelMax, "<stdout>", stdout);
  729. close_temp_logs();
  730. }
  731. return 0;
  732. }
  733. /**
  734. * Initialize the logs based on the configuration file.
  735. */
  736. int config_init_logs(or_options_t *options)
  737. {
  738. /* The order of options is: Level? (File Level?)+
  739. */
  740. struct config_line_t *opt = options->LogOptions;
  741. /* Special case if no options are given. */
  742. if (!opt) {
  743. add_stream_log(LOG_NOTICE, LOG_ERR, "<stdout>", stdout);
  744. close_temp_logs();
  745. /* don't return yet, in case we want to do a debuglogfile below */
  746. }
  747. /* Special case for if first option is LogLevel. */
  748. if (opt && !strcasecmp(opt->key, "LogLevel")) {
  749. if (opt->next && !strcasecmp(opt->next->key, "LogFile")) {
  750. if (add_single_log(opt, opt->next, options->RunAsDaemon)<0)
  751. return -1;
  752. opt = opt->next->next;
  753. } else if (!opt->next) {
  754. if (add_single_log(opt, NULL, options->RunAsDaemon)<0)
  755. return -1;
  756. opt = opt->next;
  757. } else {
  758. ; /* give warning below */
  759. }
  760. }
  761. while (opt) {
  762. if (!strcasecmp(opt->key, "LogLevel")) {
  763. log_fn(LOG_WARN, "Two LogLevel options in a row without intervening LogFile");
  764. opt = opt->next;
  765. } else {
  766. tor_assert(!strcasecmp(opt->key, "LogFile"));
  767. if (opt->next && !strcasecmp(opt->next->key, "LogLevel")) {
  768. /* LogFile followed by LogLevel */
  769. if (add_single_log(opt->next, opt, options->RunAsDaemon)<0)
  770. return -1;
  771. opt = opt->next->next;
  772. } else {
  773. /* LogFile followed by LogFile or end of list. */
  774. if (add_single_log(NULL, opt, options->RunAsDaemon)<0)
  775. return -1;
  776. opt = opt->next;
  777. }
  778. }
  779. }
  780. if (options->DebugLogFile) {
  781. log_fn(LOG_WARN, "DebugLogFile is deprecated; use LogFile and LogLevel instead");
  782. if (add_file_log(LOG_DEBUG, LOG_ERR, options->DebugLogFile)<0)
  783. return -1;
  784. }
  785. return 0;
  786. }
  787. void
  788. config_parse_exit_policy(struct config_line_t *cfg,
  789. struct exit_policy_t **dest)
  790. {
  791. struct exit_policy_t **nextp;
  792. char *e, *s;
  793. int last=0;
  794. char line[1024];
  795. if (!cfg)
  796. return;
  797. nextp = dest;
  798. while (*nextp)
  799. nextp = &((*nextp)->next);
  800. for (; cfg; cfg = cfg->next) {
  801. s = cfg->value;
  802. for (;;) {
  803. e = strchr(s,',');
  804. if(!e) {
  805. last = 1;
  806. strncpy(line,s,1023);
  807. } else {
  808. memcpy(line,s, ((e-s)<1023)?(e-s):1023);
  809. line[e-s] = 0;
  810. }
  811. line[1023]=0;
  812. log_fn(LOG_DEBUG,"Adding new entry '%s'",line);
  813. *nextp = router_parse_exit_policy_from_string(line);
  814. if(*nextp) {
  815. nextp = &((*nextp)->next);
  816. } else {
  817. log_fn(LOG_WARN,"Malformed exit policy %s; skipping.", line);
  818. }
  819. if (last)
  820. break;
  821. s = e+1;
  822. }
  823. }
  824. }
  825. void exit_policy_free(struct exit_policy_t *p) {
  826. struct exit_policy_t *e;
  827. while (p) {
  828. e = p;
  829. p = p->next;
  830. tor_free(e->string);
  831. tor_free(e);
  832. }
  833. }
  834. const char *get_data_directory(or_options_t *options) {
  835. const char *d;
  836. if (options->DataDirectory)
  837. d = options->DataDirectory;
  838. else
  839. d = "~/.tor";
  840. if (strncmp(d,"~/",2)==0) {
  841. char *fn = expand_filename(d);
  842. tor_free(options->DataDirectory);
  843. options->DataDirectory = fn;
  844. }
  845. return options->DataDirectory;
  846. }
  847. /*
  848. Local Variables:
  849. mode:c
  850. indent-tabs-mode:nil
  851. c-basic-offset:2
  852. End:
  853. */