routers.c 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286
  1. /* Copyright 2001-2003 Roger Dingledine, Matej Pfajfar. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. #define OR_PUBLICKEY_BEGIN_TAG "-----BEGIN RSA PUBLIC KEY-----\n"
  5. #define OR_PUBLICKEY_END_TAG "-----END RSA PUBLIC KEY-----\n"
  6. #define OR_SIGNATURE_BEGIN_TAG "-----BEGIN SIGNATURE-----\n"
  7. #define OR_SIGNATURE_END_TAG "-----END SIGNATURE-----\n"
  8. #define _GNU_SOURCE
  9. /* XXX this is required on rh7 to make strptime not complain. how bad
  10. * is this for portability?
  11. */
  12. #include "or.h"
  13. /****************************************************************************/
  14. static directory_t *directory = NULL; /* router array */
  15. static routerinfo_t *desc_routerinfo = NULL; /* my descriptor */
  16. static char descriptor[8192]; /* string representation of my descriptor */
  17. extern or_options_t options; /* command-line and config-file options */
  18. /****************************************************************************/
  19. struct directory_token;
  20. typedef struct directory_token directory_token_t;
  21. /* static function prototypes */
  22. void routerlist_free(routerinfo_t *list);
  23. static char *eat_whitespace(char *s);
  24. static char *eat_whitespace_no_nl(char *s);
  25. static char *find_whitespace(char *s);
  26. static int router_add_exit_policy_from_string(routerinfo_t *router, char *s);
  27. static int router_add_exit_policy(routerinfo_t *router,
  28. directory_token_t *tok);
  29. static int router_resolve_directory(directory_t *dir);
  30. /****************************************************************************/
  31. void router_retry_connections(void) {
  32. int i;
  33. routerinfo_t *router;
  34. for (i=0;i<directory->n_routers;i++) {
  35. router = directory->routers[i];
  36. if(!connection_exact_get_by_addr_port(router->addr,router->or_port)) { /* not in the list */
  37. log_fn(LOG_DEBUG,"connecting to OR %s:%u.",router->address,router->or_port);
  38. connection_or_connect(router);
  39. }
  40. }
  41. }
  42. routerinfo_t *router_pick_directory_server(void) {
  43. /* pick the first running router with a positive dir_port */
  44. int i;
  45. routerinfo_t *router, *dirserver=NULL;
  46. if(!directory)
  47. return NULL;
  48. for(i=0;i<directory->n_routers;i++) {
  49. router = directory->routers[i];
  50. if(router->dir_port > 0 && router->is_running)
  51. return router;
  52. }
  53. log_fn(LOG_WARN,"No dirservers are up. Giving them all another chance.");
  54. /* no running dir servers found? go through and mark them all as up,
  55. * and we'll cycle through the list again. */
  56. for(i=0;i<directory->n_routers;i++) {
  57. router = directory->routers[i];
  58. if(router->dir_port > 0) {
  59. router->is_running = 1;
  60. dirserver = router;
  61. }
  62. }
  63. return dirserver;
  64. }
  65. void router_upload_desc_to_dirservers(void) {
  66. int i;
  67. routerinfo_t *router;
  68. if(!directory)
  69. return;
  70. if (!router_get_my_descriptor()) {
  71. log_fn(LOG_WARN, "No descriptor; skipping upload");
  72. return;
  73. }
  74. for(i=0;i<directory->n_routers;i++) {
  75. router = directory->routers[i];
  76. if(router->dir_port > 0)
  77. directory_initiate_command(router, DIR_CONN_STATE_CONNECTING_UPLOAD);
  78. }
  79. }
  80. routerinfo_t *router_get_by_addr_port(uint32_t addr, uint16_t port) {
  81. int i;
  82. routerinfo_t *router;
  83. assert(directory);
  84. for(i=0;i<directory->n_routers;i++) {
  85. router = directory->routers[i];
  86. if ((router->addr == addr) && (router->or_port == port))
  87. return router;
  88. }
  89. return NULL;
  90. }
  91. routerinfo_t *router_get_by_link_pk(crypto_pk_env_t *pk)
  92. {
  93. int i;
  94. routerinfo_t *router;
  95. assert(directory);
  96. for(i=0;i<directory->n_routers;i++) {
  97. router = directory->routers[i];
  98. if (0 == crypto_pk_cmp_keys(router->link_pkey, pk))
  99. return router;
  100. }
  101. return NULL;
  102. }
  103. routerinfo_t *router_get_by_nickname(char *nickname)
  104. {
  105. int i;
  106. routerinfo_t *router;
  107. assert(directory);
  108. for(i=0;i<directory->n_routers;i++) {
  109. router = directory->routers[i];
  110. if (0 == strcmp(router->nickname, nickname))
  111. return router;
  112. }
  113. return NULL;
  114. }
  115. void router_get_directory(directory_t **pdirectory) {
  116. *pdirectory = directory;
  117. }
  118. /* delete a router from memory */
  119. void routerinfo_free(routerinfo_t *router)
  120. {
  121. struct exit_policy_t *e;
  122. if (!router)
  123. return;
  124. tor_free(router->address);
  125. tor_free(router->nickname);
  126. if (router->onion_pkey)
  127. crypto_free_pk_env(router->onion_pkey);
  128. if (router->link_pkey)
  129. crypto_free_pk_env(router->link_pkey);
  130. if (router->identity_pkey)
  131. crypto_free_pk_env(router->identity_pkey);
  132. while (router->exit_policy) {
  133. e = router->exit_policy;
  134. router->exit_policy = e->next;
  135. tor_free(e->string);
  136. tor_free(e->address);
  137. tor_free(e->port);
  138. free(e);
  139. }
  140. free(router);
  141. }
  142. void directory_free(directory_t *dir)
  143. {
  144. int i;
  145. for (i = 0; i < dir->n_routers; ++i)
  146. routerinfo_free(dir->routers[i]);
  147. tor_free(dir->routers);
  148. tor_free(dir->software_versions);
  149. free(dir);
  150. }
  151. void router_mark_as_down(char *nickname) {
  152. routerinfo_t *router = router_get_by_nickname(nickname);
  153. if(!router) /* we don't seem to know about him in the first place */
  154. return;
  155. log_fn(LOG_DEBUG,"Marking %s as down.",router->nickname);
  156. router->is_running = 0;
  157. }
  158. /* load the router list */
  159. int router_get_list_from_file(char *routerfile)
  160. {
  161. char *string;
  162. string = read_file_to_str(routerfile);
  163. if(!string) {
  164. log_fn(LOG_WARN,"Failed to load routerfile %s.",routerfile);
  165. return -1;
  166. }
  167. if(router_get_list_from_string(string) < 0) {
  168. log_fn(LOG_WARN,"The routerfile itself was corrupt.");
  169. free(string);
  170. return -1;
  171. }
  172. free(string);
  173. return 0;
  174. }
  175. typedef enum {
  176. K_ACCEPT,
  177. K_DIRECTORY_SIGNATURE,
  178. K_RECOMMENDED_SOFTWARE,
  179. K_REJECT,
  180. K_ROUTER,
  181. K_SIGNED_DIRECTORY,
  182. K_SIGNING_KEY,
  183. K_ONION_KEY,
  184. K_LINK_KEY,
  185. K_ROUTER_SIGNATURE,
  186. K_PUBLISHED,
  187. K_RUNNING_ROUTERS,
  188. K_PLATFORM,
  189. _SIGNATURE,
  190. _PUBLIC_KEY,
  191. _ERR,
  192. _EOF
  193. } directory_keyword;
  194. struct token_table_ent { char *t; int v; };
  195. static struct token_table_ent token_table[] = {
  196. { "accept", K_ACCEPT },
  197. { "directory-signature", K_DIRECTORY_SIGNATURE },
  198. { "reject", K_REJECT },
  199. { "router", K_ROUTER },
  200. { "recommended-software", K_RECOMMENDED_SOFTWARE },
  201. { "signed-directory", K_SIGNED_DIRECTORY },
  202. { "signing-key", K_SIGNING_KEY },
  203. { "onion-key", K_ONION_KEY },
  204. { "link-key", K_LINK_KEY },
  205. { "router-signature", K_ROUTER_SIGNATURE },
  206. { "published", K_PUBLISHED },
  207. { "running-routers", K_RUNNING_ROUTERS },
  208. { "platform", K_PLATFORM },
  209. { NULL, -1 }
  210. };
  211. #define MAX_ARGS 1024
  212. struct directory_token {
  213. directory_keyword tp;
  214. union {
  215. struct {
  216. char *args[MAX_ARGS+1];
  217. int n_args;
  218. } cmd;
  219. char *signature;
  220. char *error;
  221. crypto_pk_env_t *public_key;
  222. } val;
  223. };
  224. /* Free any malloced resources allocated for a token. Don't call this if
  225. you inherit the reference to those resources.
  226. */
  227. static void
  228. router_release_token(directory_token_t *tok)
  229. {
  230. switch (tok->tp)
  231. {
  232. case _SIGNATURE:
  233. free(tok->val.signature);
  234. break;
  235. case _PUBLIC_KEY:
  236. crypto_free_pk_env(tok->val.public_key);
  237. break;
  238. default:
  239. break;
  240. }
  241. }
  242. static int
  243. _router_get_next_token(char **s, directory_token_t *tok) {
  244. char *next;
  245. crypto_pk_env_t *pkey = NULL;
  246. char *signature = NULL;
  247. int i, done;
  248. tok->tp = _ERR;
  249. tok->val.error = "";
  250. *s = eat_whitespace(*s);
  251. if (!**s) {
  252. tok->tp = _EOF;
  253. return 0;
  254. } else if (**s == '-') {
  255. next = strchr(*s, '\n');
  256. if (! next) { tok->val.error = "No newline at EOF"; return -1; }
  257. ++next;
  258. if (! strncmp(*s, OR_PUBLICKEY_BEGIN_TAG, next-*s)) {
  259. next = strstr(*s, OR_PUBLICKEY_END_TAG);
  260. if (!next) { tok->val.error = "No public key end tag found"; return -1; }
  261. next = strchr(next, '\n'); /* Part of OR_PUBLICKEY_END_TAG; can't fail.*/
  262. ++next;
  263. if (!(pkey = crypto_new_pk_env(CRYPTO_PK_RSA)))
  264. return -1;
  265. if (crypto_pk_read_public_key_from_string(pkey, *s, next-*s)) {
  266. crypto_free_pk_env(pkey);
  267. tok->val.error = "Couldn't parse public key.";
  268. return -1;
  269. }
  270. tok->tp = _PUBLIC_KEY;
  271. tok->val.public_key = pkey;
  272. *s = next;
  273. return 0;
  274. } else if (! strncmp(*s, OR_SIGNATURE_BEGIN_TAG, next-*s)) {
  275. /* Advance past newline; can't fail. */
  276. *s = strchr(*s, '\n');
  277. ++*s;
  278. /* Find end of base64'd data */
  279. next = strstr(*s, OR_SIGNATURE_END_TAG);
  280. if (!next) { tok->val.error = "No signature end tag found"; return -1; }
  281. signature = tor_malloc(256);
  282. i = base64_decode(signature, 256, *s, next-*s);
  283. if (i<0) {
  284. free(signature);
  285. tok->val.error = "Error decoding signature."; return -1;
  286. } else if (i != 128) {
  287. free(signature);
  288. tok->val.error = "Bad length on decoded signature."; return -1;
  289. }
  290. tok->tp = _SIGNATURE;
  291. tok->val.signature = signature;
  292. next = strchr(next, '\n'); /* Part of OR_SIGNATURE_END_TAG; can't fail.*/
  293. *s = next+1;
  294. return 0;
  295. } else {
  296. tok->val.error = "Unrecognized begin line"; return -1;
  297. }
  298. } else {
  299. next = find_whitespace(*s);
  300. if (!next) {
  301. tok->val.error = "Unexpected EOF"; return -1;
  302. }
  303. for (i = 0 ; token_table[i].t ; ++i) {
  304. if (!strncmp(token_table[i].t, *s, next-*s)) {
  305. tok->tp = token_table[i].v;
  306. i = 0;
  307. done = (*next == '\n');
  308. *s = eat_whitespace_no_nl(next);
  309. while (**s != '\n' && i <= MAX_ARGS && !done) {
  310. next = find_whitespace(*s);
  311. if (*next == '\n')
  312. done = 1;
  313. *next = 0;
  314. tok->val.cmd.args[i++] = *s;
  315. *s = eat_whitespace_no_nl(next+1);
  316. };
  317. tok->val.cmd.n_args = i;
  318. if (i > MAX_ARGS) {
  319. tok->tp = _ERR;
  320. tok->val.error = "Too many arguments"; return -1;
  321. }
  322. return 0;
  323. }
  324. }
  325. tok->val.error = "Unrecognized command"; return -1;
  326. }
  327. }
  328. #ifdef DEBUG_ROUTER_TOKENS
  329. static void
  330. router_dump_token(directory_token_t *tok) {
  331. int i;
  332. switch(tok->tp)
  333. {
  334. case _SIGNATURE:
  335. puts("(signature)");
  336. return;
  337. case _PUBLIC_KEY:
  338. puts("(public key)");
  339. return;
  340. case _ERR:
  341. printf("(Error: %s\n)", tok->val.error);
  342. return;
  343. case _EOF:
  344. puts("EOF");
  345. return;
  346. case K_ACCEPT: printf("Accept"); break;
  347. case K_DIRECTORY_SIGNATURE: printf("Directory-Signature"); break;
  348. case K_REJECT: printf("Reject"); break;
  349. case K_RECOMMENDED_SOFTWARE: printf("Server-Software"); break;
  350. case K_ROUTER: printf("Router"); break;
  351. case K_SIGNED_DIRECTORY: printf("Signed-Directory"); break;
  352. case K_SIGNING_KEY: printf("Signing-Key"); break;
  353. case K_ONION_KEY: printf("Onion-key"); break;
  354. case K_LINK_KEY: printf("Link-key"); break;
  355. case K_ROUTER_SIGNATURE: printf("Router-signature"); break;
  356. case K_PUBLISHED: printf("Published"); break;
  357. case K_RUNNING_ROUTERS: printf("Running-routers"); break;
  358. case K_PLATFORM: printf("Platform"); break;
  359. default:
  360. printf("?????? %d\n", tok->tp); return;
  361. }
  362. for (i = 0; i < tok->val.cmd.n_args; ++i) {
  363. printf(" \"%s\"", tok->val.cmd.args[i]);
  364. }
  365. printf("\n");
  366. return;
  367. }
  368. static int
  369. router_get_next_token(char **s, directory_token_t *tok) {
  370. int i;
  371. i = _router_get_next_token(s, tok);
  372. router_dump_token(tok);
  373. return i;
  374. }
  375. #else
  376. #define router_get_next_token _router_get_next_token
  377. #endif
  378. /* return the first char of s that is not whitespace and not a comment */
  379. static char *eat_whitespace(char *s) {
  380. assert(s);
  381. while(isspace(*s) || *s == '#') {
  382. while(isspace(*s))
  383. s++;
  384. if(*s == '#') { /* read to a \n or \0 */
  385. while(*s && *s != '\n')
  386. s++;
  387. if(!*s)
  388. return s;
  389. }
  390. }
  391. return s;
  392. }
  393. static char *eat_whitespace_no_nl(char *s) {
  394. while(*s == ' ' || *s == '\t')
  395. ++s;
  396. return s;
  397. }
  398. /* return the first char of s that is whitespace or '#' or '\0 */
  399. static char *find_whitespace(char *s) {
  400. assert(s);
  401. while(*s && !isspace(*s) && *s != '#')
  402. s++;
  403. return s;
  404. }
  405. int router_get_list_from_string(char *s)
  406. {
  407. if (router_get_list_from_string_impl(&s, &directory, -1, NULL)) {
  408. log(LOG_WARN, "Error parsing router file");
  409. return -1;
  410. }
  411. if (router_resolve_directory(directory)) {
  412. log(LOG_WARN, "Error resolving directory");
  413. return -1;
  414. }
  415. return 0;
  416. }
  417. static int router_get_hash_impl(char *s, char *digest, const char *start_str,
  418. const char *end_str)
  419. {
  420. char *start, *end;
  421. start = strstr(s, start_str);
  422. if (!start) {
  423. log_fn(LOG_WARN,"couldn't find \"%s\"",start_str);
  424. return -1;
  425. }
  426. end = strstr(start+strlen(start_str), end_str);
  427. if (!end) {
  428. log_fn(LOG_WARN,"couldn't find \"%s\"",end_str);
  429. return -1;
  430. }
  431. end = strchr(end, '\n');
  432. if (!end) {
  433. log_fn(LOG_WARN,"couldn't find EOL");
  434. return -1;
  435. }
  436. ++end;
  437. if (crypto_SHA_digest(start, end-start, digest)) {
  438. log_fn(LOG_WARN,"couldn't compute digest");
  439. return -1;
  440. }
  441. return 0;
  442. }
  443. int router_get_dir_hash(char *s, char *digest)
  444. {
  445. return router_get_hash_impl(s,digest,
  446. "signed-directory","directory-signature");
  447. }
  448. int router_get_router_hash(char *s, char *digest)
  449. {
  450. return router_get_hash_impl(s,digest,
  451. "router ","router-signature");
  452. }
  453. /* return 0 if myversion is in start. Else return -1. */
  454. int compare_recommended_versions(char *myversion, char *start) {
  455. int len_myversion = strlen(myversion);
  456. char *comma;
  457. char *end = start + strlen(start);
  458. log_fn(LOG_DEBUG,"checking '%s' in '%s'.", myversion, start);
  459. for(;;) {
  460. comma = strchr(start, ',');
  461. if( ((comma ? comma : end) - start == len_myversion) &&
  462. !strncmp(start, myversion, len_myversion)) /* only do strncmp if the length matches */
  463. return 0; /* success, it's there */
  464. if(!comma)
  465. return -1; /* nope */
  466. start = comma+1;
  467. }
  468. }
  469. int router_get_dir_from_string(char *s, crypto_pk_env_t *pkey)
  470. {
  471. if (router_get_dir_from_string_impl(s, &directory, pkey)) {
  472. log_fn(LOG_WARN, "Couldn't parse directory.");
  473. return -1;
  474. }
  475. if (router_resolve_directory(directory)) {
  476. log_fn(LOG_WARN, "Error resolving directory");
  477. return -1;
  478. }
  479. if (compare_recommended_versions(VERSION, directory->software_versions) < 0) {
  480. log(LOG_WARN, "You are running tor version %s, which is no longer supported.\nPlease upgrade to one of %s.", VERSION, directory->software_versions);
  481. if(options.IgnoreVersion) {
  482. log(LOG_WARN, "IgnoreVersion is set. If it breaks, we told you so.");
  483. } else {
  484. log(LOG_ERR,"Set IgnoreVersion config variable if you want to proceed.");
  485. fflush(0);
  486. exit(0);
  487. }
  488. }
  489. return 0;
  490. }
  491. int router_get_dir_from_string_impl(char *s, directory_t **dest,
  492. crypto_pk_env_t *pkey)
  493. {
  494. directory_token_t tok;
  495. char digest[20];
  496. char signed_digest[128];
  497. directory_t *new_dir = NULL;
  498. char *versions;
  499. struct tm published;
  500. time_t published_on;
  501. const char *good_nickname_lst[1024];
  502. int n_good_nicknames;
  503. #define NEXT_TOK() \
  504. do { \
  505. if (router_get_next_token(&s, &tok)) { \
  506. log_fn(LOG_WARN, "Error reading directory: %s", tok.val.error);\
  507. return -1; \
  508. } } while (0)
  509. #define TOK_IS(type,name) \
  510. do { \
  511. if (tok.tp != type) { \
  512. router_release_token(&tok); \
  513. log_fn(LOG_WARN, "Error reading directory: expected %s", name);\
  514. return -1; \
  515. } } while(0)
  516. if (router_get_dir_hash(s, digest)) {
  517. log_fn(LOG_WARN, "Unable to compute digest of directory");
  518. goto err;
  519. }
  520. log(LOG_DEBUG,"Received directory hashes to %02x:%02x:%02x:%02x",
  521. ((int)digest[0])&0xff,((int)digest[1])&0xff,
  522. ((int)digest[2])&0xff,((int)digest[3])&0xff);
  523. NEXT_TOK();
  524. TOK_IS(K_SIGNED_DIRECTORY, "signed-directory");
  525. NEXT_TOK();
  526. TOK_IS(K_PUBLISHED, "published");
  527. if (tok.val.cmd.n_args != 2) {
  528. log_fn(LOG_WARN, "Invalid published line");
  529. goto err;
  530. }
  531. tok.val.cmd.args[1][-1] = ' ';
  532. if (!strptime(tok.val.cmd.args[0], "%Y-%m-%d %H:%M:%S", &published)) {
  533. log_fn(LOG_WARN, "Published time was unparseable"); goto err;
  534. }
  535. published_on = tor_timegm(&published);
  536. NEXT_TOK();
  537. TOK_IS(K_RECOMMENDED_SOFTWARE, "recommended-software");
  538. if (tok.val.cmd.n_args != 1) {
  539. log_fn(LOG_WARN, "Invalid recommended-software line");
  540. goto err;
  541. }
  542. versions = tor_strdup(tok.val.cmd.args[0]);
  543. NEXT_TOK();
  544. TOK_IS(K_RUNNING_ROUTERS, "running-routers");
  545. n_good_nicknames = tok.val.cmd.n_args;
  546. memcpy(good_nickname_lst, tok.val.cmd.args, n_good_nicknames*sizeof(char *));
  547. if (router_get_list_from_string_impl(&s, &new_dir,
  548. n_good_nicknames, good_nickname_lst)) {
  549. log_fn(LOG_WARN, "Error reading routers from directory");
  550. goto err;
  551. }
  552. new_dir->software_versions = versions;
  553. new_dir->published_on = published_on;
  554. NEXT_TOK();
  555. TOK_IS(K_DIRECTORY_SIGNATURE, "directory-signature");
  556. NEXT_TOK();
  557. TOK_IS(_SIGNATURE, "signature");
  558. if (pkey) {
  559. if (crypto_pk_public_checksig(pkey, tok.val.signature, 128, signed_digest)
  560. != 20) {
  561. log_fn(LOG_WARN, "Error reading directory: invalid signature.");
  562. free(tok.val.signature);
  563. goto err;
  564. }
  565. log(LOG_DEBUG,"Signed directory hash starts %02x:%02x:%02x:%02x",
  566. ((int)signed_digest[0])&0xff,((int)signed_digest[1])&0xff,
  567. ((int)signed_digest[2])&0xff,((int)signed_digest[3])&0xff);
  568. if (memcmp(digest, signed_digest, 20)) {
  569. log_fn(LOG_WARN, "Error reading directory: signature does not match.");
  570. free(tok.val.signature);
  571. goto err;
  572. }
  573. }
  574. free(tok.val.signature);
  575. NEXT_TOK();
  576. TOK_IS(_EOF, "end of directory");
  577. if (*dest)
  578. directory_free(*dest);
  579. *dest = new_dir;
  580. return 0;
  581. err:
  582. if (new_dir)
  583. directory_free(new_dir);
  584. return -1;
  585. #undef NEXT_TOK
  586. #undef TOK_IS
  587. }
  588. int router_get_list_from_string_impl(char **s, directory_t **dest,
  589. int n_good_nicknames,
  590. const char **good_nickname_lst)
  591. {
  592. routerinfo_t *router;
  593. routerinfo_t **rarray;
  594. int rarray_len = 0;
  595. int i;
  596. assert(s && *s);
  597. rarray = (routerinfo_t **)tor_malloc((sizeof(routerinfo_t *))*MAX_ROUTERS_IN_DIR);
  598. while (1) {
  599. *s = eat_whitespace(*s);
  600. if (strncmp(*s, "router ", 7)!=0)
  601. break;
  602. router = router_get_entry_from_string(s);
  603. if (!router) {
  604. log_fn(LOG_WARN, "Error reading router");
  605. for(i=0;i<rarray_len;i++)
  606. routerinfo_free(rarray[i]);
  607. free(rarray);
  608. return -1;
  609. }
  610. if (rarray_len >= MAX_ROUTERS_IN_DIR) {
  611. log_fn(LOG_WARN, "too many routers");
  612. routerinfo_free(router);
  613. continue;
  614. }
  615. if (n_good_nicknames>=0) {
  616. router->is_running = 0;
  617. for (i = 0; i < n_good_nicknames; ++i) {
  618. if (0==strcasecmp(good_nickname_lst[i], router->nickname)) {
  619. router->is_running = 1;
  620. break;
  621. }
  622. }
  623. } else {
  624. router->is_running = 1; /* start out assuming all dirservers are up */
  625. }
  626. rarray[rarray_len++] = router;
  627. log_fn(LOG_DEBUG,"just added router #%d.",rarray_len);
  628. }
  629. if (*dest)
  630. directory_free(*dest);
  631. *dest = (directory_t *)tor_malloc(sizeof(directory_t));
  632. (*dest)->routers = rarray;
  633. (*dest)->n_routers = rarray_len;
  634. (*dest)->software_versions = NULL;
  635. return 0;
  636. }
  637. static int
  638. router_resolve(routerinfo_t *router)
  639. {
  640. struct hostent *rent;
  641. rent = (struct hostent *)gethostbyname(router->address);
  642. if (!rent) {
  643. log_fn(LOG_WARN,"Could not get address for router %s.",router->address);
  644. return -1;
  645. }
  646. assert(rent->h_length == 4);
  647. memcpy(&router->addr, rent->h_addr,rent->h_length);
  648. router->addr = ntohl(router->addr); /* get it back into host order */
  649. return 0;
  650. }
  651. static int
  652. router_resolve_directory(directory_t *dir)
  653. {
  654. int i, max, remove;
  655. if (!dir)
  656. dir = directory;
  657. max = dir->n_routers;
  658. for (i = 0; i < max; ++i) {
  659. remove = 0;
  660. if (router_resolve(dir->routers[i])) {
  661. log_fn(LOG_WARN, "Couldn't resolve router %s; removing",
  662. dir->routers[i]->address);
  663. remove = 1;
  664. } else if (options.Nickname &&
  665. !strcmp(dir->routers[i]->nickname, options.Nickname)) {
  666. remove = 1;
  667. }
  668. if (remove) {
  669. routerinfo_free(dir->routers[i]);
  670. dir->routers[i] = dir->routers[--max];
  671. --dir->n_routers;
  672. --i;
  673. }
  674. }
  675. return 0;
  676. }
  677. /* reads a single router entry from s.
  678. * updates s so it points to after the router it just read.
  679. * mallocs a new router, returns it if all goes well, else returns NULL.
  680. */
  681. routerinfo_t *router_get_entry_from_string(char**s) {
  682. routerinfo_t *router = NULL;
  683. char signed_digest[128];
  684. char digest[128];
  685. directory_token_t _tok;
  686. directory_token_t *tok = &_tok;
  687. struct tm published;
  688. int t;
  689. #define NEXT_TOKEN() \
  690. do { if (router_get_next_token(s, tok)) { \
  691. log_fn(LOG_WARN, "Error reading directory: %s", tok->val.error);\
  692. goto err; \
  693. } } while(0)
  694. #define ARGS tok->val.cmd.args
  695. if (router_get_router_hash(*s, digest) < 0) {
  696. log_fn(LOG_WARN, "Couldn't compute router hash.");
  697. return NULL;
  698. }
  699. NEXT_TOKEN();
  700. if (tok->tp != K_ROUTER) {
  701. router_release_token(tok);
  702. log_fn(LOG_WARN,"Entry does not start with \"router\"");
  703. return NULL;
  704. }
  705. router = tor_malloc(sizeof(routerinfo_t));
  706. memset(router,0,sizeof(routerinfo_t)); /* zero it out first */
  707. router->onion_pkey = router->identity_pkey = router->link_pkey = NULL;
  708. if (tok->val.cmd.n_args != 6) {
  709. log_fn(LOG_WARN,"Wrong # of arguments to \"router\"");
  710. goto err;
  711. }
  712. router->nickname = tor_strdup(ARGS[0]);
  713. if (strlen(router->nickname) > MAX_NICKNAME_LEN) {
  714. log_fn(LOG_WARN,"Router nickname too long.");
  715. goto err;
  716. }
  717. if (strspn(router->nickname, LEGAL_NICKNAME_CHARACTERS) !=
  718. strlen(router->nickname)) {
  719. log_fn(LOG_WARN, "Router nickname contains illegal characters.");
  720. goto err;
  721. }
  722. /* read router.address */
  723. router->address = tor_strdup(ARGS[1]);
  724. router->addr = 0;
  725. /* Read router->or_port */
  726. router->or_port = atoi(ARGS[2]);
  727. if(!router->or_port) {
  728. log_fn(LOG_WARN,"or_port unreadable or 0. Failing.");
  729. goto err;
  730. }
  731. /* Router->socks_port */
  732. router->socks_port = atoi(ARGS[3]);
  733. /* Router->dir_port */
  734. router->dir_port = atoi(ARGS[4]);
  735. /* Router->bandwidth */
  736. router->bandwidth = atoi(ARGS[5]);
  737. if (!router->bandwidth) {
  738. log_fn(LOG_WARN,"bandwidth unreadable or 0. Failing.");
  739. goto err;
  740. }
  741. log_fn(LOG_DEBUG,"or_port %d, socks_port %d, dir_port %d, bandwidth %d.",
  742. router->or_port, router->socks_port, router->dir_port, router->bandwidth);
  743. /* XXX Later, require platform before published. */
  744. NEXT_TOKEN();
  745. if (tok->tp == K_PLATFORM) {
  746. NEXT_TOKEN();
  747. }
  748. if (tok->tp != K_PUBLISHED) {
  749. log_fn(LOG_WARN, "Missing published time"); goto err;
  750. }
  751. if (tok->val.cmd.n_args != 2) {
  752. log_fn(LOG_WARN, "Wrong number of arguments to published"); goto err;
  753. }
  754. ARGS[1][-1] = ' '; /* Re-insert space. */
  755. if (!strptime(ARGS[0], "%Y-%m-%d %H:%M:%S", &published)) {
  756. log_fn(LOG_WARN, "Published time was unparseable"); goto err;
  757. }
  758. router->published_on = tor_timegm(&published);
  759. NEXT_TOKEN();
  760. if (tok->tp != K_ONION_KEY) {
  761. log_fn(LOG_WARN, "Missing onion-key"); goto err;
  762. }
  763. NEXT_TOKEN();
  764. if (tok->tp != _PUBLIC_KEY) {
  765. log_fn(LOG_WARN, "Missing onion key"); goto err;
  766. } /* XXX Check key length */
  767. router->onion_pkey = tok->val.public_key;
  768. NEXT_TOKEN();
  769. if (tok->tp != K_LINK_KEY) {
  770. log_fn(LOG_WARN, "Missing link-key"); goto err;
  771. }
  772. NEXT_TOKEN();
  773. if (tok->tp != _PUBLIC_KEY) {
  774. log_fn(LOG_WARN, "Missing link key"); goto err;
  775. } /* XXX Check key length */
  776. router->link_pkey = tok->val.public_key;
  777. NEXT_TOKEN();
  778. if (tok->tp != K_SIGNING_KEY) {
  779. log_fn(LOG_WARN, "Missing signing-key"); goto err;
  780. }
  781. NEXT_TOKEN();
  782. if (tok->tp != _PUBLIC_KEY) {
  783. log_fn(LOG_WARN, "Missing signing key"); goto err;
  784. }
  785. router->identity_pkey = tok->val.public_key;
  786. NEXT_TOKEN();
  787. while (tok->tp == K_ACCEPT || tok->tp == K_REJECT) {
  788. router_add_exit_policy(router, tok);
  789. NEXT_TOKEN();
  790. }
  791. if (tok->tp != K_ROUTER_SIGNATURE) {
  792. log_fn(LOG_WARN,"Missing router signature");
  793. goto err;
  794. }
  795. NEXT_TOKEN();
  796. if (tok->tp != _SIGNATURE) {
  797. log_fn(LOG_WARN,"Missing router signature");
  798. goto err;
  799. }
  800. assert (router->identity_pkey);
  801. if ((t=crypto_pk_public_checksig(router->identity_pkey, tok->val.signature,
  802. 128, signed_digest)) != 20) {
  803. log_fn(LOG_WARN, "Invalid signature %d",t);
  804. goto err;
  805. }
  806. if (memcmp(digest, signed_digest, 20)) {
  807. log_fn(LOG_WARN, "Mismatched signature");
  808. goto err;
  809. }
  810. router_release_token(tok); /* free the signature */
  811. return router;
  812. err:
  813. router_release_token(tok);
  814. routerinfo_free(router);
  815. return NULL;
  816. #undef ARGS
  817. #undef NEXT_TOKEN
  818. }
  819. void router_add_exit_policy_from_config(routerinfo_t *router) {
  820. char *s = options.ExitPolicy, *e;
  821. int last=0;
  822. char line[1024];
  823. if(!s) {
  824. log_fn(LOG_INFO,"No exit policy configured. Ok.");
  825. return; /* nothing to see here */
  826. }
  827. if(!*s) {
  828. log_fn(LOG_INFO,"Exit policy is empty. Ok.");
  829. return; /* nothing to see here */
  830. }
  831. for(;;) {
  832. e = strchr(s,',');
  833. if(!e) {
  834. last = 1;
  835. strcpy(line,s);
  836. } else {
  837. memcpy(line,s,e-s);
  838. line[e-s] = 0;
  839. }
  840. log_fn(LOG_DEBUG,"Adding new entry '%s'",line);
  841. if(router_add_exit_policy_from_string(router,line) < 0)
  842. log_fn(LOG_WARN,"Malformed exit policy %s; skipping.", line);
  843. if(last)
  844. return;
  845. s = e+1;
  846. }
  847. }
  848. static int
  849. router_add_exit_policy_from_string(routerinfo_t *router,
  850. char *s)
  851. {
  852. directory_token_t tok;
  853. char *tmp, *cp;
  854. int r;
  855. int len, idx;
  856. len = strlen(s);
  857. tmp = cp = tor_malloc(len+2);
  858. for (idx = 0; idx < len; ++idx) {
  859. tmp[idx] = tolower(s[idx]);
  860. }
  861. tmp[len]='\n';
  862. tmp[len+1]='\0';
  863. if (router_get_next_token(&cp, &tok)) {
  864. log_fn(LOG_WARN, "Error reading exit policy: %s", tok.val.error);
  865. free(tmp);
  866. return -1;
  867. }
  868. if (tok.tp != K_ACCEPT && tok.tp != K_REJECT) {
  869. log_fn(LOG_WARN, "Expected 'accept' or 'reject'.");
  870. free(tmp);
  871. return -1;
  872. }
  873. r = router_add_exit_policy(router, &tok);
  874. free(tmp);
  875. return r;
  876. }
  877. static int router_add_exit_policy(routerinfo_t *router,
  878. directory_token_t *tok) {
  879. struct exit_policy_t *tmpe, *newe;
  880. char *arg, *colon;
  881. if (tok->val.cmd.n_args != 1)
  882. return -1;
  883. arg = tok->val.cmd.args[0];
  884. newe = tor_malloc(sizeof(struct exit_policy_t));
  885. memset(newe,0,sizeof(struct exit_policy_t));
  886. newe->string = tor_malloc(8+strlen(arg));
  887. if (tok->tp == K_REJECT) {
  888. strcpy(newe->string, "reject ");
  889. newe->policy_type = EXIT_POLICY_REJECT;
  890. } else {
  891. assert(tok->tp == K_ACCEPT);
  892. strcpy(newe->string, "accept ");
  893. newe->policy_type = EXIT_POLICY_ACCEPT;
  894. }
  895. strcat(newe->string, arg);
  896. colon = strchr(arg,':');
  897. if(!colon)
  898. goto policy_read_failed;
  899. *colon = 0;
  900. newe->address = tor_strdup(arg);
  901. newe->port = tor_strdup(colon+1);
  902. log_fn(LOG_DEBUG,"%s %s:%s",
  903. newe->policy_type == EXIT_POLICY_REJECT ? "reject" : "accept",
  904. newe->address, newe->port);
  905. /* now link newe onto the end of exit_policy */
  906. if(!router->exit_policy) {
  907. router->exit_policy = newe;
  908. return 0;
  909. }
  910. for(tmpe=router->exit_policy; tmpe->next; tmpe=tmpe->next) ;
  911. tmpe->next = newe;
  912. return 0;
  913. policy_read_failed:
  914. assert(newe->string);
  915. log_fn(LOG_WARN,"Couldn't parse line '%s'. Dropping", newe->string);
  916. tor_free(newe->string);
  917. tor_free(newe->address);
  918. tor_free(newe->port);
  919. free(newe);
  920. return -1;
  921. }
  922. /* Return 0 if my exit policy says to allow connection to conn.
  923. * Else return -1.
  924. */
  925. int router_compare_to_exit_policy(connection_t *conn) {
  926. struct exit_policy_t *tmpe;
  927. struct in_addr in;
  928. assert(desc_routerinfo);
  929. for(tmpe=desc_routerinfo->exit_policy; tmpe; tmpe=tmpe->next) {
  930. assert(tmpe->address);
  931. assert(tmpe->port);
  932. log_fn(LOG_DEBUG,"Considering exit policy %s:%s",tmpe->address, tmpe->port);
  933. if(strcmp(tmpe->address,"*") &&
  934. inet_aton(tmpe->address,&in) == 0) { /* malformed IP. reject. */
  935. log_fn(LOG_WARN,"Malformed IP %s in exit policy. Rejecting.",tmpe->address);
  936. return -1;
  937. }
  938. if((!strcmp(tmpe->address,"*") || conn->addr == ntohl(in.s_addr)) &&
  939. (!strcmp(tmpe->port,"*") || atoi(tmpe->port) == conn->port)) {
  940. log_fn(LOG_INFO,"Address '%s' matches '%s' and port '%s' matches '%d'. %s.",
  941. tmpe->address, conn->address,
  942. tmpe->port, conn->port,
  943. tmpe->policy_type == EXIT_POLICY_ACCEPT ? "Accepting" : "Rejecting");
  944. if(tmpe->policy_type == EXIT_POLICY_ACCEPT)
  945. return 0;
  946. else
  947. return -1;
  948. }
  949. }
  950. return 0; /* accept all by default. */
  951. }
  952. const char *router_get_my_descriptor(void) {
  953. if (!desc_routerinfo) {
  954. if (router_rebuild_descriptor())
  955. return NULL;
  956. }
  957. log_fn(LOG_DEBUG,"my desc is '%s'",descriptor);
  958. return descriptor;
  959. }
  960. const routerinfo_t *router_get_desc_routerinfo(void) {
  961. if (!desc_routerinfo) {
  962. if (router_rebuild_descriptor())
  963. return NULL;
  964. }
  965. return desc_routerinfo;
  966. }
  967. int router_rebuild_descriptor(void) {
  968. routerinfo_t *ri;
  969. char localhostname[256];
  970. char *address = options.Address;
  971. if(!address) { /* if not specified in config, we find a default */
  972. if(gethostname(localhostname,sizeof(localhostname)) < 0) {
  973. log_fn(LOG_WARN,"Error obtaining local hostname");
  974. return -1;
  975. }
  976. address = localhostname;
  977. if(!strchr(address,'.')) {
  978. log_fn(LOG_WARN,"fqdn '%s' has only one element. Misconfigured machine?",address);
  979. log_fn(LOG_WARN,"Try setting the Address line in your config file.");
  980. return -1;
  981. }
  982. }
  983. ri = tor_malloc(sizeof(routerinfo_t));
  984. ri->address = tor_strdup(address);
  985. ri->nickname = tor_strdup(options.Nickname);
  986. /* No need to set addr. */
  987. ri->or_port = options.ORPort;
  988. ri->socks_port = options.SocksPort;
  989. ri->dir_port = options.DirPort;
  990. ri->published_on = time(NULL);
  991. ri->onion_pkey = crypto_pk_dup_key(get_onion_key());
  992. ri->link_pkey = crypto_pk_dup_key(get_link_key());
  993. ri->identity_pkey = crypto_pk_dup_key(get_identity_key());
  994. ri->bandwidth = options.TotalBandwidth;
  995. ri->exit_policy = NULL; /* zero it out first */
  996. router_add_exit_policy_from_config(ri);
  997. if (desc_routerinfo)
  998. routerinfo_free(desc_routerinfo);
  999. desc_routerinfo = ri;
  1000. if (router_dump_router_to_string(descriptor, 8192, ri, get_identity_key())<0) {
  1001. log_fn(LOG_WARN, "Couldn't dump router to string.");
  1002. return -1;
  1003. }
  1004. return 0;
  1005. }
  1006. static void get_platform_str(char *platform, int len)
  1007. {
  1008. snprintf(platform, len-1, "Tor %s on %s", VERSION, get_uname());
  1009. platform[len-1] = '\0';
  1010. return;
  1011. }
  1012. #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  1013. int router_dump_router_to_string(char *s, int maxlen, routerinfo_t *router,
  1014. crypto_pk_env_t *ident_key) {
  1015. char *onion_pkey;
  1016. char *link_pkey;
  1017. char *identity_pkey;
  1018. char platform[256];
  1019. char digest[20];
  1020. char signature[128];
  1021. char published[32];
  1022. int onion_pkeylen, link_pkeylen, identity_pkeylen;
  1023. int written;
  1024. int result=0;
  1025. struct exit_policy_t *tmpe;
  1026. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  1027. char *s_tmp, *s_dup;
  1028. routerinfo_t *ri_tmp;
  1029. #endif
  1030. get_platform_str(platform, sizeof(platform));
  1031. if (crypto_pk_cmp_keys(ident_key, router->identity_pkey)) {
  1032. log_fn(LOG_WARN,"Tried to sign a router with a private key that didn't match router's public key!");
  1033. return -1;
  1034. }
  1035. if(crypto_pk_write_public_key_to_string(router->onion_pkey,
  1036. &onion_pkey,&onion_pkeylen)<0) {
  1037. log_fn(LOG_WARN,"write onion_pkey to string failed!");
  1038. return -1;
  1039. }
  1040. if(crypto_pk_write_public_key_to_string(router->identity_pkey,
  1041. &identity_pkey,&identity_pkeylen)<0) {
  1042. log_fn(LOG_WARN,"write identity_pkey to string failed!");
  1043. return -1;
  1044. }
  1045. if(crypto_pk_write_public_key_to_string(router->link_pkey,
  1046. &link_pkey,&link_pkeylen)<0) {
  1047. log_fn(LOG_WARN,"write link_pkey to string failed!");
  1048. return -1;
  1049. }
  1050. strftime(published, 32, "%Y-%m-%d %H:%M:%S", gmtime(&router->published_on));
  1051. result = snprintf(s, maxlen,
  1052. "router %s %s %d %d %d %d\n"
  1053. "platform %s\n"
  1054. "published %s\n"
  1055. "onion-key\n%s"
  1056. "link-key\n%s"
  1057. "signing-key\n%s",
  1058. router->nickname,
  1059. router->address,
  1060. router->or_port,
  1061. router->socks_port,
  1062. router->dir_port,
  1063. router->bandwidth,
  1064. platform,
  1065. published,
  1066. onion_pkey, link_pkey, identity_pkey);
  1067. free(onion_pkey);
  1068. free(link_pkey);
  1069. free(identity_pkey);
  1070. if(result < 0 || result >= maxlen) {
  1071. /* apparently different glibcs do different things on snprintf error.. so check both */
  1072. return -1;
  1073. }
  1074. written = result;
  1075. for(tmpe=router->exit_policy; tmpe; tmpe=tmpe->next) {
  1076. result = snprintf(s+written, maxlen-written, "%s %s:%s\n",
  1077. tmpe->policy_type == EXIT_POLICY_ACCEPT ? "accept" : "reject",
  1078. tmpe->address, tmpe->port);
  1079. if(result < 0 || result+written > maxlen) {
  1080. /* apparently different glibcs do different things on snprintf error.. so check both */
  1081. return -1;
  1082. }
  1083. written += result;
  1084. }
  1085. if (written > maxlen-256) /* Not enough room for signature. */
  1086. return -1;
  1087. strcat(s+written, "router-signature\n");
  1088. written += strlen(s+written);
  1089. s[written] = '\0';
  1090. if (router_get_router_hash(s, digest) < 0)
  1091. return -1;
  1092. if (crypto_pk_private_sign(ident_key, digest, 20, signature) < 0) {
  1093. log_fn(LOG_WARN, "Error signing digest");
  1094. return -1;
  1095. }
  1096. strcat(s+written, "-----BEGIN SIGNATURE-----\n");
  1097. written += strlen(s+written);
  1098. if (base64_encode(s+written, maxlen-written, signature, 128) < 0) {
  1099. log_fn(LOG_WARN, "Couldn't base64-encode signature");
  1100. return -1;
  1101. }
  1102. written += strlen(s+written);
  1103. strcat(s+written, "-----END SIGNATURE-----\n");
  1104. written += strlen(s+written);
  1105. if (written > maxlen-2)
  1106. return -1;
  1107. /* include a last '\n' */
  1108. s[written] = '\n';
  1109. s[written+1] = 0;
  1110. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  1111. s_tmp = s_dup = tor_strdup(s);
  1112. ri_tmp = router_get_entry_from_string(&s_tmp);
  1113. if (!ri_tmp) {
  1114. log_fn(LOG_ERR, "We just generated a router descriptor we can't parse: <<%s>>",
  1115. s);
  1116. return -1;
  1117. }
  1118. free(s_dup);
  1119. routerinfo_free(ri_tmp);
  1120. #endif
  1121. return written+1;
  1122. }
  1123. /*
  1124. Local Variables:
  1125. mode:c
  1126. indent-tabs-mode:nil
  1127. c-basic-offset:2
  1128. End:
  1129. */