routerlist.c 46 KB

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