routerlist.c 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578
  1. /* Copyright 2001-2003 Roger Dingledine, Matej Pfajfar. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. #define _GNU_SOURCE
  5. /* XXX this is required on rh7 to make strptime not complain. how bad
  6. * is this for portability?
  7. */
  8. #include "or.h"
  9. /*****
  10. * routerlist.c: Code to parse descriptors and directories, and to
  11. * maintain and access the global list of routerinfos for known
  12. * servers.
  13. *****/
  14. /****************************************************************************/
  15. extern or_options_t options; /* command-line and config-file options */
  16. /****************************************************************************/
  17. /* We parse a directory by breaking it into "tokens", each consisting
  18. * of a keyword, a line full of arguments, and a binary object. The
  19. * arguments and object are both optional, depending on the keyword
  20. * type.
  21. */
  22. /* Enumeration of possible token types. The ones starting with K_
  23. * correspond to directory 'keywords'. _UNRECOGNIZED is for an
  24. * unrecognized keyword; _ERR is an error in the tokenizing process,
  25. * _EOF is an end-of-file marker, and _NIL is used to encode
  26. * not-a-token.
  27. */
  28. typedef enum {
  29. K_ACCEPT,
  30. K_DIRECTORY_SIGNATURE,
  31. K_RECOMMENDED_SOFTWARE,
  32. K_REJECT,
  33. K_ROUTER,
  34. K_SIGNED_DIRECTORY,
  35. K_SIGNING_KEY,
  36. K_ONION_KEY,
  37. K_LINK_KEY, /* XXXX obsolete */
  38. K_ROUTER_SIGNATURE,
  39. K_PUBLISHED,
  40. K_RUNNING_ROUTERS,
  41. K_PLATFORM,
  42. K_OPT,
  43. K_BANDWIDTH,
  44. K_PORTS,
  45. _UNRECOGNIZED,
  46. _ERR,
  47. _EOF,
  48. _NIL
  49. } directory_keyword;
  50. /* Structure to hold a single directory tokon.
  51. */
  52. typedef struct directory_token_t {
  53. directory_keyword tp; /* Type of the token. */
  54. int n_args; /* Number of elements in args */
  55. char **args; /* Array of aguments from keyword line. */
  56. char *object_type; /* -----BEGIN [object_type]-----*/
  57. int object_size; /* Bytes in object_boody */
  58. char *object_body; /* Contents of object, base65-decoded. */
  59. crypto_pk_env_t *key; /* For public keys only. */
  60. char *error; /* For _ERR tokens only. */
  61. } directory_token_t;
  62. /* ********************************************************************** */
  63. /* We use a table of rules to decide how to parse each token type. */
  64. /* Rules for how many arguments a keyword can take. */
  65. typedef enum {
  66. NO_ARGS, /* (1) no arguments, ever */
  67. ARGS, /* (2) a list of arguments separated by spaces */
  68. CONCAT_ARGS, /* or (3) the rest of the line, treated as a single argument. */
  69. } arg_syntax;
  70. /* Rules for whether the keyword needs an object. */
  71. typedef enum {
  72. NO_OBJ, /* (1) no object, ever */
  73. NEED_OBJ, /* (2) object is required */
  74. NEED_KEY, /* (3) object is requierd, and must be a public key. */
  75. OBJ_OK, /* or (4) object is optional. */
  76. } obj_syntax;
  77. /* Rules for where a keyword can apper. */
  78. typedef enum {
  79. ANY = 0, /* Appears in router descriptor or in directory sections. */
  80. DIR_ONLY, /* Appears only in directory. */
  81. RTR_ONLY, /* Appears only in router descriptor. */
  82. } where_syntax;
  83. /* Table mapping keywords to token value and to argument rules. */
  84. static struct {
  85. char *t; int v; arg_syntax s; obj_syntax os; where_syntax ws;
  86. } token_table[] = {
  87. { "accept", K_ACCEPT, ARGS, NO_OBJ, RTR_ONLY },
  88. { "directory-signature", K_DIRECTORY_SIGNATURE, ARGS, NEED_OBJ,DIR_ONLY},
  89. { "reject", K_REJECT, ARGS, NO_OBJ, RTR_ONLY },
  90. { "router", K_ROUTER, ARGS, NO_OBJ, RTR_ONLY },
  91. { "recommended-software",K_RECOMMENDED_SOFTWARE,ARGS, NO_OBJ, DIR_ONLY },
  92. { "signed-directory", K_SIGNED_DIRECTORY, NO_ARGS, NO_OBJ, DIR_ONLY },
  93. { "signing-key", K_SIGNING_KEY, NO_ARGS, NEED_KEY,RTR_ONLY },
  94. { "onion-key", K_ONION_KEY, NO_ARGS, NEED_KEY,RTR_ONLY },
  95. { "link-key", K_LINK_KEY, NO_ARGS, NEED_KEY,RTR_ONLY },
  96. { "router-signature", K_ROUTER_SIGNATURE, NO_ARGS, NEED_OBJ,RTR_ONLY },
  97. { "running-routers", K_RUNNING_ROUTERS, ARGS, NO_OBJ, DIR_ONLY },
  98. { "ports", K_PORTS, ARGS, NO_OBJ, RTR_ONLY },
  99. { "bandwidth", K_BANDWIDTH, ARGS, NO_OBJ, RTR_ONLY },
  100. { "platform", K_PLATFORM, CONCAT_ARGS, NO_OBJ, RTR_ONLY },
  101. { "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ, ANY },
  102. { "opt", K_OPT, CONCAT_ARGS, OBJ_OK, ANY },
  103. { NULL, -1 }
  104. };
  105. /* ********************************************************************** */
  106. /* static function prototypes */
  107. static routerinfo_t *
  108. router_pick_directory_server_impl(void);
  109. static int
  110. router_get_list_from_string_impl(const char **s, routerlist_t **dest,
  111. int n_good_nicknames,
  112. const char **good_nickname_lst);
  113. int /* Exposed for unit tests */
  114. router_get_routerlist_from_directory_impl(const char *s, routerlist_t **dest,
  115. crypto_pk_env_t *pkey);
  116. static int
  117. router_add_exit_policy(routerinfo_t *router, directory_token_t *tok);
  118. static int
  119. router_resolve_routerlist(routerlist_t *dir);
  120. static int router_get_hash_impl(const char *s, char *digest,
  121. const char *start_str, const char *end_str);
  122. static void token_free(directory_token_t *tok);
  123. static smartlist_t *find_all_exitpolicy(smartlist_t *s);
  124. static directory_token_t *find_first_by_keyword(smartlist_t *s,
  125. directory_keyword keyword);
  126. static int tokenize_string(const char *start, const char *end,
  127. smartlist_t *out, int is_dir);
  128. static directory_token_t *get_next_token(const char **s, where_syntax where);
  129. /****************************************************************************/
  130. /****
  131. * Functions to manage and access our list of known routers. (Note:
  132. * dirservers maintain a separate, independent list of known router
  133. * descriptors.)
  134. *****/
  135. /* Global list of all of the routers that we, as an OR or OP, know about. */
  136. static routerlist_t *routerlist = NULL;
  137. extern int has_fetched_directory; /* from main.c */
  138. /* Try to find a running dirserver. If there are no running dirservers
  139. * in our routerlist, reload the routerlist and try again. */
  140. routerinfo_t *router_pick_directory_server(void) {
  141. routerinfo_t *choice;
  142. choice = router_pick_directory_server_impl();
  143. if(!choice) {
  144. log_fn(LOG_WARN,"No dirservers known. Reloading and trying again.");
  145. has_fetched_directory=0; /* reset it */
  146. if(options.RouterFile) {
  147. if(router_set_routerlist_from_file(options.RouterFile) < 0)
  148. return NULL;
  149. } else {
  150. if(config_assign_default_dirservers() < 0)
  151. return NULL;
  152. }
  153. /* give it another try */
  154. choice = router_pick_directory_server_impl();
  155. }
  156. return choice;
  157. }
  158. /* Pick a random running router with a positive dir_port from our
  159. * routerlist. */
  160. static routerinfo_t *router_pick_directory_server_impl(void) {
  161. int i;
  162. routerinfo_t *router, *dirserver=NULL;
  163. smartlist_t *sl;
  164. if(!routerlist)
  165. return NULL;
  166. /* Find all the running dirservers we know about. */
  167. sl = smartlist_create();
  168. for(i=0;i< smartlist_len(routerlist->routers); i++) {
  169. router = smartlist_get(routerlist->routers, i);
  170. if(router->dir_port > 0 && router->is_running)
  171. smartlist_add(sl, router);
  172. }
  173. router = smartlist_choose(sl);
  174. smartlist_free(sl);
  175. if(router)
  176. return router;
  177. log_fn(LOG_INFO,"No dirservers are reachable. Trying them all again.");
  178. /* No running dir servers found? go through and mark them all as up,
  179. * and next time, we'll cycle through the list again. */
  180. for(i=0; i < smartlist_len(routerlist->routers); i++) {
  181. router = smartlist_get(routerlist->routers, i);
  182. if(router->dir_port > 0) {
  183. router->is_running = 1;
  184. dirserver = router;
  185. }
  186. }
  187. if(!dirserver)
  188. log_fn(LOG_WARN,"No dirservers in directory! Returning NULL.");
  189. return dirserver;
  190. }
  191. /* Given a comma-and-whitespace separated list of nicknames, see which
  192. * nicknames in 'list' name routers in our routerlist that are
  193. * currently running. Add the routerinfos for those routers to 'sl'.
  194. */
  195. void add_nickname_list_to_smartlist(smartlist_t *sl, const char *list) {
  196. char *start,*end;
  197. char nick[MAX_NICKNAME_LEN+1];
  198. routerinfo_t *router;
  199. tor_assert(sl);
  200. tor_assert(list);
  201. while(isspace((int)*list) || *list==',') list++;
  202. start = list;
  203. while(*start) {
  204. end=start; while(*end && !isspace((int)*end) && *end != ',') end++;
  205. memcpy(nick,start,end-start);
  206. nick[end-start] = 0; /* null terminate it */
  207. router = router_get_by_nickname(nick);
  208. if (router) {
  209. if (router->is_running)
  210. smartlist_add(sl,router);
  211. else
  212. log_fn(LOG_INFO,"Nickname list includes '%s' which is known but down.",nick);
  213. } else
  214. log_fn(has_fetched_directory ? LOG_WARN : LOG_INFO,
  215. "Nickname list includes '%s' which isn't a known router.",nick);
  216. while(isspace((int)*end) || *end==',') end++;
  217. start = end;
  218. }
  219. }
  220. /* Add every router from our routerlist that is currently running to 'sl'.
  221. */
  222. void router_add_running_routers_to_smartlist(smartlist_t *sl) {
  223. routerinfo_t *router;
  224. int i;
  225. if(!routerlist)
  226. return;
  227. for(i=0;i<smartlist_len(routerlist->routers);i++) {
  228. router = smartlist_get(routerlist->routers, i);
  229. if(router->is_running &&
  230. (!options.ORPort ||
  231. connection_twin_get_by_addr_port(router->addr, router->or_port) ))
  232. smartlist_add(sl, router);
  233. }
  234. }
  235. /* Pick a random running router from a routerlist 'dir'. If any node
  236. * named in 'preferred' is available, pick one of those. Never pick a
  237. * node named in 'excluded', or whose routerinfo is in
  238. * 'excludedsmartlist', even if they are the only nodes available.
  239. */
  240. routerinfo_t *router_choose_random_node(routerlist_t *dir,
  241. char *preferred, char *excluded,
  242. smartlist_t *excludedsmartlist)
  243. {
  244. smartlist_t *sl, *excludednodes;
  245. routerinfo_t *choice;
  246. excludednodes = smartlist_create();
  247. add_nickname_list_to_smartlist(excludednodes,excluded);
  248. /* try the nodes in RendNodes first */
  249. sl = smartlist_create();
  250. add_nickname_list_to_smartlist(sl,preferred);
  251. smartlist_subtract(sl,excludednodes);
  252. if(excludedsmartlist)
  253. smartlist_subtract(sl,excludedsmartlist);
  254. choice = smartlist_choose(sl);
  255. smartlist_free(sl);
  256. if(!choice) {
  257. sl = smartlist_create();
  258. router_add_running_routers_to_smartlist(sl);
  259. smartlist_subtract(sl,excludednodes);
  260. if(excludedsmartlist)
  261. smartlist_subtract(sl,excludedsmartlist);
  262. choice = smartlist_choose(sl);
  263. smartlist_free(sl);
  264. }
  265. smartlist_free(excludednodes);
  266. if(!choice)
  267. log_fn(LOG_WARN,"No available nodes when trying to choose node. Failing.");
  268. return choice;
  269. }
  270. /* Return the router in our routerlist whose address is 'addr' and
  271. * whose OR port is 'port'. Return NULL if no such router is known.
  272. */
  273. routerinfo_t *router_get_by_addr_port(uint32_t addr, uint16_t port) {
  274. int i;
  275. routerinfo_t *router;
  276. tor_assert(routerlist);
  277. for(i=0;i<smartlist_len(routerlist->routers);i++) {
  278. router = smartlist_get(routerlist->routers, i);
  279. if ((router->addr == addr) && (router->or_port == port))
  280. return router;
  281. }
  282. return NULL;
  283. }
  284. /* Return the router in our routerlist whose nickname is 'nickname'
  285. * (case insensitive). Return NULL if no such router is known.
  286. */
  287. routerinfo_t *router_get_by_nickname(char *nickname)
  288. {
  289. int i;
  290. routerinfo_t *router;
  291. tor_assert(routerlist);
  292. for(i=0;i<smartlist_len(routerlist->routers);i++) {
  293. router = smartlist_get(routerlist->routers, i);
  294. if (0 == strcasecmp(router->nickname, nickname))
  295. return router;
  296. }
  297. return NULL;
  298. }
  299. /* Set *prouterlist to the current list of all known routers. */
  300. void router_get_routerlist(routerlist_t **prouterlist) {
  301. *prouterlist = routerlist;
  302. }
  303. /* Free all storage held by 'router'. */
  304. void routerinfo_free(routerinfo_t *router)
  305. {
  306. struct exit_policy_t *e;
  307. if (!router)
  308. return;
  309. tor_free(router->address);
  310. tor_free(router->nickname);
  311. tor_free(router->platform);
  312. if (router->onion_pkey)
  313. crypto_free_pk_env(router->onion_pkey);
  314. if (router->identity_pkey)
  315. crypto_free_pk_env(router->identity_pkey);
  316. while (router->exit_policy) {
  317. e = router->exit_policy;
  318. router->exit_policy = e->next;
  319. tor_free(e->string);
  320. free(e);
  321. }
  322. free(router);
  323. }
  324. /* Allocate a fresh copy of 'router' */
  325. routerinfo_t *routerinfo_copy(const routerinfo_t *router)
  326. {
  327. routerinfo_t *r;
  328. struct exit_policy_t **e, *tmp;
  329. r = tor_malloc(sizeof(routerinfo_t));
  330. memcpy(r, router, sizeof(routerinfo_t));
  331. r->address = tor_strdup(r->address);
  332. r->nickname = tor_strdup(r->nickname);
  333. r->platform = tor_strdup(r->platform);
  334. if (r->onion_pkey)
  335. r->onion_pkey = crypto_pk_dup_key(r->onion_pkey);
  336. if (r->identity_pkey)
  337. r->identity_pkey = crypto_pk_dup_key(r->identity_pkey);
  338. e = &r->exit_policy;
  339. while (*e) {
  340. tmp = tor_malloc(sizeof(struct exit_policy_t));
  341. memcpy(tmp,*e,sizeof(struct exit_policy_t));
  342. *e = tmp;
  343. (*e)->string = tor_strdup((*e)->string);
  344. e = & ((*e)->next);
  345. }
  346. return r;
  347. }
  348. /* Free all storage held by a routerlist 'rl' */
  349. static void routerlist_free(routerlist_t *rl)
  350. {
  351. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
  352. routerinfo_free(r));
  353. smartlist_free(rl->routers);
  354. tor_free(rl->software_versions);
  355. tor_free(rl);
  356. }
  357. /* Mark the router named 'nickname' as non-running in our routerlist. */
  358. void router_mark_as_down(char *nickname) {
  359. routerinfo_t *router = router_get_by_nickname(nickname);
  360. if(!router) /* we don't seem to know about him in the first place */
  361. return;
  362. log_fn(LOG_DEBUG,"Marking %s as down.",router->nickname);
  363. router->is_running = 0;
  364. }
  365. /*****
  366. * Code to parse router descriptors and directories.
  367. *****/
  368. /* Replace the current router list with the one stored in 'routerfile'. */
  369. int router_set_routerlist_from_file(char *routerfile)
  370. {
  371. char *string;
  372. string = read_file_to_str(routerfile);
  373. if(!string) {
  374. log_fn(LOG_WARN,"Failed to load routerfile %s.",routerfile);
  375. return -1;
  376. }
  377. if(router_set_routerlist_from_string(string) < 0) {
  378. log_fn(LOG_WARN,"The routerfile itself was corrupt.");
  379. free(string);
  380. return -1;
  381. }
  382. /* dump_onion_keys(LOG_NOTICE); */
  383. free(string);
  384. return 0;
  385. }
  386. /* Helper function: read routerinfo elements from s, and throw out the
  387. * ones that don't parse and resolve. Replace the current
  388. * routerlist. */
  389. int router_set_routerlist_from_string(const char *s)
  390. {
  391. if (router_get_list_from_string_impl(&s, &routerlist, -1, NULL)) {
  392. log(LOG_WARN, "Error parsing router file");
  393. return -1;
  394. }
  395. if (router_resolve_routerlist(routerlist)) {
  396. log(LOG_WARN, "Error resolving routerlist");
  397. return -1;
  398. }
  399. /* dump_onion_keys(LOG_NOTICE); */
  400. return 0;
  401. }
  402. /* Set 'digest' to the SHA-1 digest of the hash of the directory in 's'.
  403. * Return 0 on success, nonzero on failure.
  404. */
  405. int router_get_dir_hash(const char *s, char *digest)
  406. {
  407. return router_get_hash_impl(s,digest,
  408. "signed-directory","directory-signature");
  409. }
  410. /* Set 'digest' to the SHA-1 digest of the hash of the first router in 's'.
  411. * Return 0 on success, nonzero on failure.
  412. */
  413. int router_get_router_hash(const char *s, char *digest)
  414. {
  415. return router_get_hash_impl(s,digest,
  416. "router ","router-signature");
  417. }
  418. /* Return 1 if myversion is in versionlist. Else return 0.
  419. * (versionlist is a comma-separated list of versions.) */
  420. int is_recommended_version(const char *myversion,
  421. const char *versionlist) {
  422. int len_myversion = strlen(myversion);
  423. char *comma;
  424. const char *end = versionlist + strlen(versionlist);
  425. log_fn(LOG_DEBUG,"checking '%s' in '%s'.", myversion, versionlist);
  426. for(;;) {
  427. comma = strchr(versionlist, ',');
  428. if( ((comma ? comma : end) - versionlist == len_myversion) &&
  429. !strncmp(versionlist, myversion, len_myversion))
  430. /* only do strncmp if the length matches */
  431. return 1; /* success, it's there */
  432. if(!comma)
  433. return 0; /* nope */
  434. versionlist = comma+1;
  435. }
  436. }
  437. /* Replace the current routerlist with the routers stored in the
  438. * signed directory 's'. If pkey is provided, make sure that 's' is
  439. * signed with pkey. */
  440. int router_set_routerlist_from_directory(const char *s, crypto_pk_env_t *pkey)
  441. {
  442. if (router_get_routerlist_from_directory_impl(s, &routerlist, pkey)) {
  443. log_fn(LOG_WARN, "Couldn't parse directory.");
  444. return -1;
  445. }
  446. if (router_resolve_routerlist(routerlist)) {
  447. log_fn(LOG_WARN, "Error resolving routerlist");
  448. return -1;
  449. }
  450. if (!is_recommended_version(VERSION, routerlist->software_versions)) {
  451. log(options.IgnoreVersion ? LOG_WARN : LOG_ERR,
  452. "You are running Tor version %s, which will not work with this network.\n"
  453. "Please use %s%s.",
  454. VERSION, strchr(routerlist->software_versions,',') ? "one of " : "",
  455. routerlist->software_versions);
  456. if(options.IgnoreVersion) {
  457. log(LOG_WARN, "IgnoreVersion is set. If it breaks, we told you so.");
  458. } else {
  459. fflush(0);
  460. exit(0);
  461. }
  462. }
  463. return 0;
  464. }
  465. /* Helper function: resolve the hostname for 'router'. */
  466. static int
  467. router_resolve(routerinfo_t *router)
  468. {
  469. if (tor_lookup_hostname(router->address, &router->addr) != 0) {
  470. log_fn(LOG_WARN,"Could not get address for router %s (%s).",
  471. router->address, router->nickname);
  472. return -1;
  473. }
  474. router->addr = ntohl(router->addr); /* get it back into host order */
  475. return 0;
  476. }
  477. /* Helper function: resolve every router in rl, and ensure that our own
  478. * routerinfo is at the front.
  479. */
  480. static int
  481. router_resolve_routerlist(routerlist_t *rl)
  482. {
  483. int i, remove;
  484. routerinfo_t *r;
  485. if (!rl)
  486. rl = routerlist;
  487. i = 0;
  488. if ((r = router_get_my_routerinfo())) {
  489. smartlist_insert(rl->routers, 0, routerinfo_copy(r));
  490. ++i;
  491. }
  492. for ( ; i < smartlist_len(rl->routers); ++i) {
  493. remove = 0;
  494. r = smartlist_get(rl->routers,i);
  495. if (router_is_me(r)) {
  496. remove = 1;
  497. } else if (router_resolve(r)) {
  498. log_fn(LOG_WARN, "Couldn't resolve router %s; not using", r->address);
  499. remove = 1;
  500. }
  501. if (remove) {
  502. routerinfo_free(r);
  503. smartlist_del_keeporder(rl->routers, i--);
  504. }
  505. }
  506. return 0;
  507. }
  508. /* Decide whether a given addr:port is definitely accepted, definitely
  509. * rejected, or neither by a given exit policy. If 'addr' is 0, we
  510. * don't know the IP of the target address.
  511. *
  512. * Returns -1 for 'rejected', 0 for accepted, 1 for 'maybe' (since IP is
  513. * unknown.
  514. */
  515. int router_compare_addr_to_exit_policy(uint32_t addr, uint16_t port,
  516. struct exit_policy_t *policy)
  517. {
  518. int maybe_reject = 0;
  519. int maybe_accept = 0;
  520. int match = 0;
  521. int maybe = 0;
  522. struct in_addr in;
  523. struct exit_policy_t *tmpe;
  524. for(tmpe=policy; tmpe; tmpe=tmpe->next) {
  525. // log_fn(LOG_DEBUG,"Considering exit policy %s", tmpe->string);
  526. maybe = 0;
  527. if (!addr) {
  528. /* Address is unknown. */
  529. if (port >= tmpe->prt_min && port <= tmpe->prt_max) {
  530. /* The port definitely matches. */
  531. if (tmpe->msk == 0) {
  532. match = 1;
  533. } else {
  534. maybe = 1;
  535. }
  536. } else if (!port) {
  537. /* The port maybe matches. */
  538. maybe = 1;
  539. }
  540. } else {
  541. /* Address is known */
  542. if ((addr & tmpe->msk) == (tmpe->addr & tmpe->msk)) {
  543. if (port >= tmpe->prt_min && port <= tmpe->prt_max) {
  544. /* Exact match for the policy */
  545. match = 1;
  546. } else if (!port) {
  547. maybe = 1;
  548. }
  549. }
  550. }
  551. if (maybe) {
  552. if (tmpe->policy_type == EXIT_POLICY_REJECT)
  553. maybe_reject = 1;
  554. else
  555. maybe_accept = 1;
  556. }
  557. if (match) {
  558. in.s_addr = htonl(addr);
  559. log_fn(LOG_DEBUG,"Address %s:%d matches exit policy '%s'",
  560. inet_ntoa(in), port, tmpe->string);
  561. if(tmpe->policy_type == EXIT_POLICY_ACCEPT) {
  562. /* If we already hit a clause that might trigger a 'reject', than we
  563. * can't be sure of this certain 'accept'.*/
  564. return maybe_reject ? ADDR_POLICY_UNKNOWN : ADDR_POLICY_ACCEPTED;
  565. } else {
  566. return maybe_accept ? ADDR_POLICY_UNKNOWN : ADDR_POLICY_REJECTED;
  567. }
  568. }
  569. }
  570. /* accept all by default. */
  571. return maybe_reject ? ADDR_POLICY_UNKNOWN : ADDR_POLICY_ACCEPTED;
  572. }
  573. /* Return 1 if all running routers will reject addr:port, return 0 if
  574. * any might accept it. */
  575. int router_exit_policy_all_routers_reject(uint32_t addr, uint16_t port) {
  576. int i;
  577. routerinfo_t *router;
  578. for (i=0;i<smartlist_len(routerlist->routers);i++) {
  579. router = smartlist_get(routerlist->routers, i);
  580. if (router->is_running && router_compare_addr_to_exit_policy(
  581. addr, port, router->exit_policy) != ADDR_POLICY_REJECTED)
  582. return 0; /* this one could be ok. good enough. */
  583. }
  584. return 1; /* all will reject. */
  585. }
  586. /* Return true iff 'router' does not permit exit streams.
  587. */
  588. int router_exit_policy_rejects_all(routerinfo_t *router) {
  589. return router_compare_addr_to_exit_policy(0, 0, router->exit_policy)
  590. == ADDR_POLICY_REJECTED;
  591. }
  592. /* Parse a date of the format 'YYYY-MM-DD hh:mm:ss" and store the result into
  593. * *t.
  594. */
  595. static int parse_time(const char *cp, time_t *t)
  596. {
  597. struct tm st_tm;
  598. #ifdef HAVE_STRPTIME
  599. if (!strptime(cp, "%Y-%m-%d %H:%M:%S", &st_tm)) {
  600. log_fn(LOG_WARN, "Published time was unparseable"); return -1;
  601. }
  602. #else
  603. unsigned int year=0, month=0, day=0, hour=100, minute=100, second=100;
  604. if (sscanf(cp, "%u-%u-%u %u:%u:%u", &year, &month,
  605. &day, &hour, &minute, &second) < 6) {
  606. log_fn(LOG_WARN, "Published time was unparseable"); return -1;
  607. }
  608. if (year < 1970 || month < 1 || month > 12 || day < 1 || day > 31 ||
  609. hour > 23 || minute > 59 || second > 61) {
  610. log_fn(LOG_WARN, "Published time was nonsensical"); return -1;
  611. }
  612. st_tm.tm_year = year;
  613. st_tm.tm_mon = month-1;
  614. st_tm.tm_mday = day;
  615. st_tm.tm_hour = hour;
  616. st_tm.tm_min = minute;
  617. st_tm.tm_sec = second;
  618. #endif
  619. *t = tor_timegm(&st_tm);
  620. return 0;
  621. }
  622. /* Helper function: parse a directory from 's' and, when done, store the
  623. * resulting routerlist in *dest, freeing the old value if necessary.
  624. * If pkey is provided, we check the directory signature with pkey.
  625. */
  626. int /* Should be static; exposed for unit tests */
  627. router_get_routerlist_from_directory_impl(const char *str,
  628. routerlist_t **dest,
  629. crypto_pk_env_t *pkey)
  630. {
  631. directory_token_t *tok;
  632. char digest[20];
  633. char signed_digest[128];
  634. routerlist_t *new_dir = NULL;
  635. char *versions = NULL;
  636. time_t published_on;
  637. char *good_nickname_lst[1024];
  638. int n_good_nicknames = 0;
  639. int i, r;
  640. const char *end;
  641. smartlist_t *tokens = NULL;
  642. if (router_get_dir_hash(str, digest)) {
  643. log_fn(LOG_WARN, "Unable to compute digest of directory");
  644. goto err;
  645. }
  646. log(LOG_DEBUG,"Received directory hashes to %s",hex_str(digest,4));
  647. if ((end = strstr(str,"\nrouter "))) {
  648. ++end;
  649. } else if ((end = strstr(str, "\ndirectory-signature"))) {
  650. ++end;
  651. } else {
  652. end = str + strlen(str);
  653. }
  654. tokens = smartlist_create();
  655. if (tokenize_string(str,end,tokens,1)) {
  656. log_fn(LOG_WARN, "Error tokenizing directory"); goto err;
  657. }
  658. if (smartlist_len(tokens) < 1) {
  659. log_fn(LOG_WARN, "Impossibly short directory header"); goto err;
  660. }
  661. if ((tok = find_first_by_keyword(tokens, _UNRECOGNIZED))) {
  662. log_fn(LOG_WARN, "Unrecognized keyword in \"%s\"; can't parse directory.",
  663. tok->args[0]);
  664. goto err;
  665. }
  666. tok = smartlist_get(tokens,0);
  667. if (tok->tp != K_SIGNED_DIRECTORY) {
  668. log_fn(LOG_WARN, "Directory doesn't start with signed-directory.");
  669. goto err;
  670. }
  671. if (!(tok = find_first_by_keyword(tokens, K_PUBLISHED))) {
  672. log_fn(LOG_WARN, "Missing published time on directory.");
  673. goto err;
  674. }
  675. tor_assert(tok->n_args == 1);
  676. if (parse_time(tok->args[0], &published_on) < 0) {
  677. goto err;
  678. }
  679. if (!(tok = find_first_by_keyword(tokens, K_RECOMMENDED_SOFTWARE))) {
  680. log_fn(LOG_WARN, "Missing recommended-software line from directory.");
  681. goto err;
  682. }
  683. if (tok->n_args != 1) {
  684. log_fn(LOG_WARN, "Invalid recommended-software line"); goto err;
  685. }
  686. versions = tor_strdup(tok->args[0]);
  687. if (!(tok = find_first_by_keyword(tokens, K_RUNNING_ROUTERS))) {
  688. log_fn(LOG_WARN, "Missing running-routers line from directory.");
  689. goto err;
  690. }
  691. n_good_nicknames = tok->n_args;
  692. memcpy(good_nickname_lst, tok->args, n_good_nicknames*sizeof(char *));
  693. tok->n_args = 0; /* Don't free the strings in good_nickname_lst yet. */
  694. /* Read the router list from s, advancing s up past the end of the last
  695. * router. */
  696. str = end;
  697. if (router_get_list_from_string_impl(&str, &new_dir,
  698. n_good_nicknames,
  699. (const char**)good_nickname_lst)) {
  700. log_fn(LOG_WARN, "Error reading routers from directory");
  701. goto err;
  702. }
  703. for (i = 0; i < n_good_nicknames; ++i) {
  704. tor_free(good_nickname_lst[i]); /* now free them */
  705. }
  706. new_dir->software_versions = versions; versions = NULL;
  707. new_dir->published_on = published_on;
  708. SMARTLIST_FOREACH(tokens, directory_token_t *, tok, token_free(tok));
  709. smartlist_free(tokens);
  710. tokens = smartlist_create();
  711. if (tokenize_string(str,str+strlen(str),tokens,1)<0) {
  712. log_fn(LOG_WARN, "Error tokenizing signature"); goto err;
  713. }
  714. if (smartlist_len(tokens) != 1 ||
  715. ((directory_token_t*)smartlist_get(tokens,0))->tp != K_DIRECTORY_SIGNATURE){
  716. log_fn(LOG_WARN,"Expected a single directory signature"); goto err;
  717. }
  718. tok = smartlist_get(tokens,0);
  719. if (strcmp(tok->object_type, "SIGNATURE") || tok->object_size != 128) {
  720. log_fn(LOG_WARN, "Bad object type or length on directory signature");
  721. goto err;
  722. }
  723. if (pkey) {
  724. if (crypto_pk_public_checksig(pkey, tok->object_body, 128, signed_digest)
  725. != 20) {
  726. log_fn(LOG_WARN, "Error reading directory: invalid signature.");
  727. goto err;
  728. }
  729. log(LOG_DEBUG,"Signed directory hash starts %s", hex_str(signed_digest,4));
  730. if (memcmp(digest, signed_digest, 20)) {
  731. log_fn(LOG_WARN, "Error reading directory: signature does not match.");
  732. goto err;
  733. }
  734. }
  735. if (*dest)
  736. routerlist_free(*dest);
  737. *dest = new_dir;
  738. r = 0;
  739. goto done;
  740. err:
  741. r = -1;
  742. if (new_dir)
  743. routerlist_free(new_dir);
  744. tor_free(versions);
  745. for (i = 0; i < n_good_nicknames; ++i) {
  746. tor_free(good_nickname_lst[i]);
  747. }
  748. done:
  749. if (tokens) {
  750. SMARTLIST_FOREACH(tokens, directory_token_t *, tok, token_free(tok));
  751. smartlist_free(tokens);
  752. }
  753. return r;
  754. }
  755. /* Helper function: Given a string *s containing a concatenated
  756. * sequence of router descriptors, parses them and stores the result
  757. * in *dest. If good_nickname_lst is provided, then routers whose
  758. * nicknames are not listed are marked as nonrunning. Advances *s to
  759. * a point immediately following the last router entry. Returns 0 on
  760. * success and -1 on failure.
  761. */
  762. static int
  763. router_get_list_from_string_impl(const char **s, routerlist_t **dest,
  764. int n_good_nicknames,
  765. const char **good_nickname_lst)
  766. {
  767. routerinfo_t *router;
  768. smartlist_t *routers;
  769. int rarray_len = 0;
  770. int i;
  771. const char *end;
  772. tor_assert(s && *s);
  773. routers = smartlist_create();
  774. while (1) {
  775. *s = eat_whitespace(*s);
  776. /* Don't start parsing the rest of *s unless it contains a router. */
  777. if (strncmp(*s, "router ", 7)!=0)
  778. break;
  779. if ((end = strstr(*s+1, "\nrouter "))) {
  780. end++;
  781. } else if ((end = strstr(*s+1, "\ndirectory-signature"))) {
  782. end++;
  783. } else {
  784. end = *s+strlen(*s);
  785. }
  786. router = router_get_entry_from_string(*s, end);
  787. *s = end;
  788. if (!router) {
  789. log_fn(LOG_WARN, "Error reading router; skipping");
  790. continue;
  791. }
  792. if (n_good_nicknames>=0) {
  793. router->is_running = 0;
  794. for (i = 0; i < n_good_nicknames; ++i) {
  795. if (0==strcasecmp(good_nickname_lst[i], router->nickname)) {
  796. router->is_running = 1;
  797. break;
  798. }
  799. }
  800. } else {
  801. router->is_running = 1; /* start out assuming all dirservers are up */
  802. }
  803. smartlist_add(routers, router);
  804. log_fn(LOG_DEBUG,"just added router #%d.",rarray_len);
  805. }
  806. if (*dest)
  807. routerlist_free(*dest);
  808. *dest = tor_malloc(sizeof(routerlist_t));
  809. (*dest)->routers = routers;
  810. (*dest)->software_versions = NULL;
  811. return 0;
  812. }
  813. /* Helper function: reads a single router entry from *s ... *end.
  814. * Mallocs a new router and returns it if all goes well, else returns
  815. * NULL.
  816. */
  817. routerinfo_t *router_get_entry_from_string(const char *s,
  818. const char *end) {
  819. routerinfo_t *router = NULL;
  820. char signed_digest[128];
  821. char digest[128];
  822. smartlist_t *tokens = NULL, *exit_policy_tokens = NULL;
  823. directory_token_t *tok;
  824. int t;
  825. int ports_set, bw_set;
  826. if (!end) {
  827. end = s + strlen(s);
  828. }
  829. if (router_get_router_hash(s, digest) < 0) {
  830. log_fn(LOG_WARN, "Couldn't compute router hash.");
  831. return NULL;
  832. }
  833. tokens = smartlist_create();
  834. if (tokenize_string(s,end,tokens,0)) {
  835. log_fn(LOG_WARN, "Error tokeninzing router descriptor."); goto err;
  836. }
  837. if (smartlist_len(tokens) < 2) {
  838. log_fn(LOG_WARN, "Impossibly short router descriptor.");
  839. goto err;
  840. }
  841. if ((tok = find_first_by_keyword(tokens, _UNRECOGNIZED))) {
  842. log_fn(LOG_WARN, "Unrecognized keyword in \"%s\"; skipping descriptor.",
  843. tok->args[0]);
  844. goto err;
  845. }
  846. tok = smartlist_get(tokens,0);
  847. if (tok->tp != K_ROUTER) {
  848. log_fn(LOG_WARN,"Entry does not start with \"router\"");
  849. goto err;
  850. }
  851. router = tor_malloc_zero(sizeof(routerinfo_t));
  852. router->onion_pkey = router->identity_pkey = NULL;
  853. ports_set = bw_set = 0;
  854. if (tok->n_args == 2 || tok->n_args == 5 || tok->n_args == 6) {
  855. router->nickname = tor_strdup(tok->args[0]);
  856. if (strlen(router->nickname) > MAX_NICKNAME_LEN) {
  857. log_fn(LOG_WARN,"Router nickname too long.");
  858. goto err;
  859. }
  860. if (strspn(router->nickname, LEGAL_NICKNAME_CHARACTERS) !=
  861. strlen(router->nickname)) {
  862. log_fn(LOG_WARN, "Router nickname contains illegal characters.");
  863. goto err;
  864. }
  865. router->address = tor_strdup(tok->args[1]);
  866. router->addr = 0;
  867. if (tok->n_args >= 5) {
  868. router->or_port = atoi(tok->args[2]);
  869. router->socks_port = atoi(tok->args[3]);
  870. router->dir_port = atoi(tok->args[4]);
  871. ports_set = 1;
  872. /* XXXX Remove this after everyone has moved to 0.0.6 */
  873. if (tok->n_args == 6) {
  874. router->bandwidthrate = atoi(tok->args[5]);
  875. router->bandwidthburst = router->bandwidthrate * 10;
  876. bw_set = 1;
  877. }
  878. }
  879. } else {
  880. log_fn(LOG_WARN,"Wrong # of arguments to \"router\" (%d)",tok->n_args);
  881. goto err;
  882. }
  883. tok = find_first_by_keyword(tokens, K_PORTS);
  884. if (tok && ports_set) {
  885. log_fn(LOG_WARN,"Redundant ports line");
  886. goto err;
  887. } else if (tok) {
  888. if (tok->n_args != 3) {
  889. log_fn(LOG_WARN,"Wrong # of arguments to \"ports\"");
  890. goto err;
  891. }
  892. router->or_port = atoi(tok->args[0]);
  893. router->socks_port = atoi(tok->args[1]);
  894. router->dir_port = atoi(tok->args[2]);
  895. ports_set = 1;
  896. }
  897. tok = find_first_by_keyword(tokens, K_BANDWIDTH);
  898. if (tok && bw_set) {
  899. log_fn(LOG_WARN,"Redundant bandwidth line");
  900. goto err;
  901. } else if (tok) {
  902. if (tok->n_args < 2) {
  903. log_fn(LOG_WARN,"Not enough arguments to \"bandwidth\"");
  904. goto err;
  905. }
  906. router->bandwidthrate = atoi(tok->args[0]);
  907. router->bandwidthburst = atoi(tok->args[1]);
  908. bw_set = 1;
  909. }
  910. if (!(tok = find_first_by_keyword(tokens, K_PUBLISHED))) {
  911. log_fn(LOG_WARN, "Missing published time"); goto err;
  912. }
  913. tor_assert(tok->n_args == 1);
  914. if (parse_time(tok->args[0], &router->published_on) < 0)
  915. goto err;
  916. if (!(tok = find_first_by_keyword(tokens, K_ONION_KEY))) {
  917. log_fn(LOG_WARN, "Missing onion key"); goto err;
  918. }
  919. /* XXX Check key length */
  920. router->onion_pkey = tok->key;
  921. tok->key = NULL; /* Prevent free */
  922. if ((tok = find_first_by_keyword(tokens, K_LINK_KEY))) {
  923. log_fn(LOG_INFO, "Skipping obsolete link-key");
  924. }
  925. if (!(tok = find_first_by_keyword(tokens, K_SIGNING_KEY))) {
  926. log_fn(LOG_WARN, "Missing onion key"); goto err;
  927. }
  928. /* XXX Check key length */
  929. router->identity_pkey = tok->key;
  930. tok->key = NULL; /* Prevent free */
  931. if ((tok = find_first_by_keyword(tokens, K_PLATFORM))) {
  932. router->platform = tor_strdup(tok->args[0]);
  933. }
  934. exit_policy_tokens = find_all_exitpolicy(tokens);
  935. SMARTLIST_FOREACH(exit_policy_tokens, directory_token_t *, t,
  936. if (router_add_exit_policy(router,t)<0) {
  937. log_fn(LOG_WARN,"Error in exit policy"); goto err;}
  938. );
  939. if (!(tok = find_first_by_keyword(tokens, K_ROUTER_SIGNATURE))) {
  940. log_fn(LOG_WARN, "Missing router signature"); goto err;
  941. }
  942. if (strcmp(tok->object_type, "SIGNATURE") || tok->object_size != 128) {
  943. log_fn(LOG_WARN, "Bad object type or length on router signature");
  944. goto err;
  945. }
  946. if ((t=crypto_pk_public_checksig(router->identity_pkey, tok->object_body,
  947. 128, signed_digest)) != 20) {
  948. log_fn(LOG_WARN, "Invalid signature %d",t); goto err;
  949. }
  950. if (memcmp(digest, signed_digest, 20)) {
  951. log_fn(LOG_WARN, "Mismatched signature"); goto err;
  952. }
  953. if (!ports_set) {
  954. log_fn(LOG_WARN,"No ports declared; failing."); goto err;
  955. }
  956. if (!bw_set) {
  957. log_fn(LOG_WARN,"No bandwidth declared; failing."); goto err;
  958. }
  959. if(!router->or_port) {
  960. log_fn(LOG_WARN,"or_port unreadable or 0. Failing.");
  961. goto err;
  962. }
  963. if (!router->bandwidthrate) {
  964. log_fn(LOG_WARN,"bandwidthrate unreadable or 0. Failing.");
  965. goto err;
  966. }
  967. if (!router->platform) {
  968. router->platform = tor_strdup("<unknown>");
  969. }
  970. log_fn(LOG_DEBUG,"or_port %d, socks_port %d, dir_port %d, bandwidthrate %u, bandwidthburst %u.",
  971. router->or_port, router->socks_port, router->dir_port,
  972. (unsigned) router->bandwidthrate, (unsigned) router->bandwidthburst);
  973. goto done;
  974. return router;
  975. err:
  976. routerinfo_free(router);
  977. router = NULL;
  978. done:
  979. if (tokens) {
  980. SMARTLIST_FOREACH(tokens, directory_token_t *, tok, token_free(tok));
  981. smartlist_free(tokens);
  982. }
  983. if (exit_policy_tokens) {
  984. smartlist_free(exit_policy_tokens);
  985. }
  986. return router;
  987. }
  988. /* Parse the exit policy in the string 's' and add it to 'router'.
  989. */
  990. int
  991. router_add_exit_policy_from_string(routerinfo_t *router, const char *s)
  992. {
  993. directory_token_t *tok = NULL;
  994. const char *cp;
  995. char *tmp;
  996. int r;
  997. int len, idx;
  998. /* *s might not end with \n, so we need to extend it with one. */
  999. len = strlen(s);
  1000. cp = tmp = tor_malloc(len+2);
  1001. for (idx = 0; idx < len; ++idx) {
  1002. tmp[idx] = tolower(s[idx]);
  1003. }
  1004. tmp[len]='\n';
  1005. tmp[len+1]='\0';
  1006. tok = get_next_token(&cp, RTR_ONLY);
  1007. if (tok->tp == _ERR) {
  1008. log_fn(LOG_WARN, "Error reading exit policy: %s", tok->error);
  1009. goto err;
  1010. }
  1011. if (tok->tp != K_ACCEPT && tok->tp != K_REJECT) {
  1012. log_fn(LOG_WARN, "Expected 'accept' or 'reject'.");
  1013. goto err;
  1014. }
  1015. /* Now that we've gotten an exit policy, add it to the router. */
  1016. r = router_add_exit_policy(router, tok);
  1017. goto done;
  1018. err:
  1019. r = -1;
  1020. done:
  1021. free(tmp);
  1022. token_free(tok);
  1023. return r;
  1024. }
  1025. /* Given a K_ACCEPT or K_REJECT token and a router, create a new exit_policy_t
  1026. * corresponding to the token, and add it to 'router' */
  1027. static int
  1028. router_add_exit_policy(routerinfo_t *router, directory_token_t *tok) {
  1029. struct exit_policy_t *tmpe, *newe;
  1030. struct in_addr in;
  1031. char *arg, *address, *mask, *port, *endptr;
  1032. int bits;
  1033. tor_assert(tok->tp == K_REJECT || tok->tp == K_ACCEPT);
  1034. if (tok->n_args != 1)
  1035. return -1;
  1036. arg = tok->args[0];
  1037. newe = tor_malloc_zero(sizeof(struct exit_policy_t));
  1038. newe->string = tor_malloc(8+strlen(arg));
  1039. if (tok->tp == K_REJECT) {
  1040. strcpy(newe->string, "reject ");
  1041. newe->policy_type = EXIT_POLICY_REJECT;
  1042. } else {
  1043. strcpy(newe->string, "accept ");
  1044. newe->policy_type = EXIT_POLICY_ACCEPT;
  1045. }
  1046. strcat(newe->string, arg); /* can't overflow */
  1047. address = arg;
  1048. mask = strchr(arg,'/');
  1049. port = strchr(mask?mask:arg,':');
  1050. /* Break 'arg' into separate strings. 'arg' was already strdup'd by
  1051. * _router_get_next_token, so it's safe to modify.
  1052. */
  1053. if (mask)
  1054. *mask++ = 0;
  1055. if (port)
  1056. *port++ = 0;
  1057. if (strcmp(address, "*") == 0) {
  1058. newe->addr = 0;
  1059. } else if (tor_inet_aton(address, &in) != 0) {
  1060. newe->addr = ntohl(in.s_addr);
  1061. } else {
  1062. log_fn(LOG_WARN, "Malformed IP %s in exit policy; rejecting.",
  1063. address);
  1064. goto policy_read_failed;
  1065. }
  1066. if (!mask) {
  1067. if (strcmp(address, "*") == 0)
  1068. newe->msk = 0;
  1069. else
  1070. newe->msk = 0xFFFFFFFFu;
  1071. } else {
  1072. endptr = NULL;
  1073. bits = (int) strtol(mask, &endptr, 10);
  1074. if (!*endptr) {
  1075. /* strtol handled the whole mask. */
  1076. newe->msk = ~((1<<(32-bits))-1);
  1077. } else if (tor_inet_aton(mask, &in) != 0) {
  1078. newe->msk = ntohl(in.s_addr);
  1079. } else {
  1080. log_fn(LOG_WARN, "Malformed mask %s on exit policy; rejecting.",
  1081. mask);
  1082. goto policy_read_failed;
  1083. }
  1084. }
  1085. if (!port || strcmp(port, "*") == 0) {
  1086. newe->prt_min = 0;
  1087. newe->prt_max = 65535;
  1088. } else {
  1089. endptr = NULL;
  1090. newe->prt_min = (uint16_t) strtol(port, &endptr, 10);
  1091. if (*endptr == '-') {
  1092. port = endptr+1;
  1093. endptr = NULL;
  1094. newe->prt_max = (uint16_t) strtol(port, &endptr, 10);
  1095. if (*endptr) {
  1096. log_fn(LOG_WARN, "Malformed port %s on exit policy; rejecting.",
  1097. port);
  1098. }
  1099. } else if (*endptr) {
  1100. log_fn(LOG_WARN, "Malformed port %s on exit policy; rejecting.",
  1101. port);
  1102. goto policy_read_failed;
  1103. } else {
  1104. newe->prt_max = newe->prt_min;
  1105. }
  1106. }
  1107. in.s_addr = htonl(newe->addr);
  1108. address = tor_strdup(inet_ntoa(in));
  1109. in.s_addr = htonl(newe->msk);
  1110. log_fn(LOG_DEBUG,"%s %s/%s:%d-%d",
  1111. newe->policy_type == EXIT_POLICY_REJECT ? "reject" : "accept",
  1112. address, inet_ntoa(in), newe->prt_min, newe->prt_max);
  1113. tor_free(address);
  1114. /* now link newe onto the end of exit_policy */
  1115. if(!router->exit_policy) {
  1116. router->exit_policy = newe;
  1117. return 0;
  1118. }
  1119. for(tmpe=router->exit_policy; tmpe->next; tmpe=tmpe->next) ;
  1120. tmpe->next = newe;
  1121. return 0;
  1122. policy_read_failed:
  1123. tor_assert(newe->string);
  1124. log_fn(LOG_WARN,"Couldn't parse line '%s'. Dropping", newe->string);
  1125. tor_free(newe->string);
  1126. free(newe);
  1127. return -1;
  1128. }
  1129. /*****
  1130. * Low-level tokenizer for router descriptors and directories.
  1131. *****/
  1132. /* Free all resources allocated for 'tok' */
  1133. static void
  1134. token_free(directory_token_t *tok)
  1135. {
  1136. int i;
  1137. tor_assert(tok);
  1138. if (tok->args) {
  1139. for (i = 0; i < tok->n_args; ++i) {
  1140. tor_free(tok->args[i]);
  1141. }
  1142. tor_free(tok->args);
  1143. }
  1144. tor_free(tok->object_type);
  1145. tor_free(tok->object_body);
  1146. if (tok->key)
  1147. crypto_free_pk_env(tok->key);
  1148. tor_free(tok);
  1149. }
  1150. /* Helper function: read the next token from *s, advance *s to the end
  1151. * of the token, and return the parsed token. If 'where' is DIR_ONLY
  1152. * or RTR_ONLY, reject all tokens of the wrong type.
  1153. */
  1154. static directory_token_t *
  1155. get_next_token(const char **s, where_syntax where) {
  1156. const char *next, *obstart;
  1157. int i, done, allocated;
  1158. directory_token_t *tok;
  1159. arg_syntax a_syn;
  1160. obj_syntax o_syn = NO_OBJ;
  1161. #define RET_ERR(msg) \
  1162. do { if (tok) token_free(tok); \
  1163. tok = tor_malloc_zero(sizeof(directory_token_t));\
  1164. tok->tp = _ERR; \
  1165. tok->error = msg; \
  1166. goto done_tokenizing; } while (0)
  1167. tok = tor_malloc_zero(sizeof(directory_token_t));
  1168. tok->tp = _ERR;
  1169. *s = eat_whitespace(*s);
  1170. if (!**s) {
  1171. tok->tp = _EOF;
  1172. return tok;
  1173. }
  1174. next = find_whitespace(*s);
  1175. if (!next) {
  1176. tok->error = "Unexpected EOF"; return tok;
  1177. }
  1178. /* It's a keyword... but which one? */
  1179. for (i = 0 ; token_table[i].t ; ++i) {
  1180. if (!strncmp(token_table[i].t, *s, next-*s)) {
  1181. /* We've found the keyword. */
  1182. tok->tp = token_table[i].v;
  1183. a_syn = token_table[i].s;
  1184. o_syn = token_table[i].os;
  1185. if (token_table[i].ws != ANY && token_table[i].ws != where) {
  1186. if (where == DIR_ONLY) {
  1187. RET_ERR("Found a router-only token in a directory section");
  1188. } else {
  1189. RET_ERR("Found a directory-only token in a router descriptor");
  1190. }
  1191. }
  1192. if (a_syn == ARGS) {
  1193. /* This keyword takes multiple arguments. */
  1194. i = 0;
  1195. done = (*next == '\n');
  1196. allocated = 32;
  1197. tok->args = tor_malloc(sizeof(char*)*32);
  1198. *s = eat_whitespace_no_nl(next);
  1199. while (**s != '\n' && !done) {
  1200. next = find_whitespace(*s);
  1201. if (*next == '\n')
  1202. done = 1;
  1203. if (i == allocated) {
  1204. allocated *= 2;
  1205. tok->args = tor_realloc(tok->args,sizeof(char*)*allocated);
  1206. }
  1207. tok->args[i++] = tor_strndup(*s,next-*s);
  1208. *s = eat_whitespace_no_nl(next+1);
  1209. }
  1210. tok->n_args = i;
  1211. } else if (a_syn == CONCAT_ARGS) {
  1212. /* The keyword takes the line as a single argument */
  1213. *s = eat_whitespace_no_nl(next);
  1214. next = strchr(*s, '\n');
  1215. if (!next)
  1216. RET_ERR("Unexpected EOF");
  1217. tok->args = tor_malloc(sizeof(char*));
  1218. tok->args[0] = tor_strndup(*s,next-*s);
  1219. tok->n_args = 1;
  1220. *s = eat_whitespace_no_nl(next+1);
  1221. } else {
  1222. /* The keyword takes no arguments. */
  1223. tor_assert(a_syn == NO_ARGS);
  1224. *s = eat_whitespace_no_nl(next);
  1225. if (**s != '\n') {
  1226. RET_ERR("Unexpected arguments");
  1227. }
  1228. tok->n_args = 0;
  1229. *s = eat_whitespace_no_nl(*s+1);
  1230. }
  1231. break;
  1232. }
  1233. }
  1234. if (tok->tp == _ERR) {
  1235. tok->tp = _UNRECOGNIZED;
  1236. next = strchr(*s, '\n');
  1237. if (!next) {
  1238. RET_ERR("Unexpected EOF");
  1239. }
  1240. tok->args = tor_malloc(sizeof(char*));
  1241. tok->args[0] = tor_strndup(*s,next-*s);
  1242. tok->n_args = 1;
  1243. *s = next+1;
  1244. o_syn = OBJ_OK;
  1245. }
  1246. *s = eat_whitespace(*s);
  1247. if (strncmp(*s, "-----BEGIN ", 11)) {
  1248. goto done_tokenizing;
  1249. }
  1250. obstart = *s;
  1251. *s += 11; /* length of "-----BEGIN ". */
  1252. next = strchr(*s, '\n');
  1253. if (next-*s < 6 || strncmp(next-5, "-----\n", 6)) {
  1254. RET_ERR("Malformed object: bad begin line");
  1255. }
  1256. tok->object_type = tor_strndup(*s, next-*s-5);
  1257. *s = next+1;
  1258. next = strstr(*s, "-----END ");
  1259. if (!next) {
  1260. RET_ERR("Malformed object: missing end line");
  1261. }
  1262. if (!strcmp(tok->object_type, "RSA PUBLIC KEY")) {
  1263. if (strncmp(next, "-----END RSA PUBLIC KEY-----\n", 29))
  1264. RET_ERR("Malformed object: mismatched end line");
  1265. next = strchr(next,'\n')+1;
  1266. tok->key = crypto_new_pk_env();
  1267. if (crypto_pk_read_public_key_from_string(tok->key, obstart, next-obstart))
  1268. RET_ERR("Couldn't parse public key.");
  1269. *s = next;
  1270. } else {
  1271. tok->object_body = tor_malloc(next-*s); /* really, this is too much RAM. */
  1272. i = base64_decode(tok->object_body, 256, *s, next-*s);
  1273. if (i<0) {
  1274. RET_ERR("Malformed object: bad base64-encoded data");
  1275. }
  1276. tok->object_size = i;
  1277. *s = next + 9; /* length of "-----END ". */
  1278. i = strlen(tok->object_type);
  1279. if (strncmp(*s, tok->object_type, i) || strncmp(*s+i, "-----\n", 6)) {
  1280. RET_ERR("Malformed object: mismatched end tag");
  1281. }
  1282. *s += i+6;
  1283. }
  1284. switch(o_syn)
  1285. {
  1286. case NO_OBJ:
  1287. if (tok->object_body)
  1288. RET_ERR("Unexpected object for keyword");
  1289. if (tok->key)
  1290. RET_ERR("Unexpected public key for keyword");
  1291. break;
  1292. case NEED_OBJ:
  1293. if (!tok->object_body)
  1294. RET_ERR("Missing object for keyword");
  1295. break;
  1296. case NEED_KEY:
  1297. if (!tok->key)
  1298. RET_ERR("Missing publid key for keyword");
  1299. break;
  1300. case OBJ_OK:
  1301. break;
  1302. }
  1303. done_tokenizing:
  1304. #if 0
  1305. for (i = 0; token_table[i].t ; ++i) {
  1306. if (token_table[i].v == tok->tp) {
  1307. fputs(token_table[i].t, stdout);
  1308. break;
  1309. i = -1;
  1310. }
  1311. }
  1312. if (i) {
  1313. if (tok->tp == _UNRECOGNIZED) fputs("UNRECOGNIZED", stdout);
  1314. if (tok->tp == _ERR) fputs("ERR",stdout);
  1315. if (tok->tp == _EOF) fputs("EOF",stdout);
  1316. if (tok->tp == _NIL) fputs("_NIL",stdout);
  1317. }
  1318. for(i = 0; i < tok->n_args; ++i) {
  1319. fprintf(stdout," \"%s\"", tok->args[i]);
  1320. }
  1321. if (tok->error) { fprintf(stdout," *%s*", tok->error); }
  1322. fputs("\n",stdout);
  1323. #endif
  1324. return tok;
  1325. #undef RET_ERR
  1326. }
  1327. /* Read all tokens from a string between 'start' and 'end', and add
  1328. * them to 'out'. If 'is_dir' is true, reject all non-directory
  1329. * tokens; else reject all non-routerdescriptor tokens.
  1330. */
  1331. static int
  1332. tokenize_string(const char *start, const char *end, smartlist_t *out,
  1333. int is_dir)
  1334. {
  1335. const char **s;
  1336. directory_token_t *tok = NULL;
  1337. where_syntax where = is_dir ? DIR_ONLY : RTR_ONLY;
  1338. s = &start;
  1339. while (*s < end && (!tok || tok->tp != _EOF)) {
  1340. tok = get_next_token(s, where);
  1341. if (tok->tp == _ERR) {
  1342. log_fn(LOG_WARN, "parse error: %s", tok->error);
  1343. return -1;
  1344. }
  1345. smartlist_add(out, tok);
  1346. *s = eat_whitespace(*s);
  1347. }
  1348. return 0;
  1349. }
  1350. /* Find the first token in 's' whose keyword is 'keyword'; return NULL if no
  1351. * such keyword is found.
  1352. */
  1353. static directory_token_t *
  1354. find_first_by_keyword(smartlist_t *s, directory_keyword keyword)
  1355. {
  1356. SMARTLIST_FOREACH(s, directory_token_t *, t, if (t->tp == keyword) return t);
  1357. return NULL;
  1358. }
  1359. /* Return a newly allocated smartlist of all accept or reject tokens in 's'.
  1360. */
  1361. static smartlist_t *
  1362. find_all_exitpolicy(smartlist_t *s)
  1363. {
  1364. smartlist_t *out = smartlist_create();
  1365. SMARTLIST_FOREACH(s, directory_token_t *, t,
  1366. if (t->tp == K_ACCEPT || t->tp == K_REJECT)
  1367. smartlist_add(out,t));
  1368. return out;
  1369. }
  1370. /* Compute the SHA digest of the substring of s taken from the first
  1371. * occurrence of start_str through the first newline after the first
  1372. * subsequent occurrence of end_str; store the 20-byte result in 'digest';
  1373. * return 0 on success.
  1374. *
  1375. * If no such substring exists, return -1.
  1376. */
  1377. static int router_get_hash_impl(const char *s, char *digest,
  1378. const char *start_str,
  1379. const char *end_str)
  1380. {
  1381. char *start, *end;
  1382. start = strstr(s, start_str);
  1383. if (!start) {
  1384. log_fn(LOG_WARN,"couldn't find \"%s\"",start_str);
  1385. return -1;
  1386. }
  1387. end = strstr(start+strlen(start_str), end_str);
  1388. if (!end) {
  1389. log_fn(LOG_WARN,"couldn't find \"%s\"",end_str);
  1390. return -1;
  1391. }
  1392. end = strchr(end, '\n');
  1393. if (!end) {
  1394. log_fn(LOG_WARN,"couldn't find EOL");
  1395. return -1;
  1396. }
  1397. ++end;
  1398. if (crypto_digest(start, end-start, digest)) {
  1399. log_fn(LOG_WARN,"couldn't compute digest");
  1400. return -1;
  1401. }
  1402. return 0;
  1403. }
  1404. /*
  1405. Local Variables:
  1406. mode:c
  1407. indent-tabs-mode:nil
  1408. c-basic-offset:2
  1409. End:
  1410. */