directory.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984
  1. /* Copyright 2001-2004 Roger Dingledine.
  2. * Copyright 2004 Roger Dingledine, Nick Mathewson. */
  3. /* See LICENSE for licensing information */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. #include "or.h"
  7. /**
  8. * \file directory.c
  9. * \brief Implement directory HTTP protocol.
  10. **/
  11. /* In-points to directory.c:
  12. *
  13. * - directory_post_to_dirservers(), called from
  14. * router_upload_dir_desc_to_dirservers() in router.c
  15. * upload_service_descriptor() in rendservice.c
  16. * - directory_get_from_dirserver(), called from
  17. * rend_client_refetch_renddesc() in rendclient.c
  18. * run_scheduled_events() in main.c
  19. * do_hup() in main.c
  20. * - connection_dir_process_inbuf(), called from
  21. * connection_process_inbuf() in connection.c
  22. * - connection_dir_finished_flushing(), called from
  23. * connection_finished_flushing() in connection.c
  24. * - connection_dir_finished_connecting(), called from
  25. * connection_finished_connecting() in connection.c
  26. */
  27. static void
  28. directory_initiate_command_router(routerinfo_t *router, uint8_t purpose,
  29. const char *payload, size_t payload_len);
  30. static void
  31. directory_initiate_command_trusted_dir(trusted_dir_server_t *dirserv,
  32. uint8_t purpose, const char *payload, size_t payload_len);
  33. static void
  34. directory_initiate_command(const char *address, uint32_t addr, uint16_t port,
  35. const char *platform,
  36. const char *digest, uint8_t purpose,
  37. const char *payload, size_t payload_len);
  38. static void
  39. directory_send_command(connection_t *conn, const char *platform,
  40. int purpose, const char *payload, size_t payload_len);
  41. static int directory_handle_command(connection_t *conn);
  42. /********* START VARIABLES **********/
  43. static struct exit_policy_t *dir_policy = NULL;
  44. #if 0 /* commented out for now, since for now what clients send is
  45. different from what servers want to receive */
  46. /** URL for publishing rendezvous descriptors. */
  47. char rend_publish_string[] = "/tor/rendezvous/publish";
  48. /** Prefix for downloading rendezvous descriptors. */
  49. char rend_fetch_url[] = "/tor/rendezvous/";
  50. #endif
  51. #define MAX_HEADERS_SIZE 50000
  52. #define MAX_BODY_SIZE 500000
  53. #define ALLOW_DIRECTORY_TIME_SKEW 30*60
  54. /********* END VARIABLES ************/
  55. /** A helper function for dir_policy_permits_address() below.
  56. *
  57. * Parse options->DirPolicy in the same way that the exit policy
  58. * is parsed, and put the processed version in &dir_policy.
  59. * Ignore port specifiers.
  60. */
  61. static void parse_dir_policy(void)
  62. {
  63. struct exit_policy_t *n;
  64. if (dir_policy) {
  65. exit_policy_free(dir_policy);
  66. dir_policy = NULL;
  67. }
  68. config_parse_exit_policy(get_options()->DirPolicy, &dir_policy);
  69. /* ports aren't used. */
  70. for (n=dir_policy; n; n = n->next) {
  71. n->prt_min = 1;
  72. n->prt_max = 65535;
  73. }
  74. }
  75. /** Return 1 if <b>addr</b> is permitted to connect to our dir port,
  76. * based on <b>dir_policy</b>. Else return 0.
  77. */
  78. int dir_policy_permits_address(uint32_t addr)
  79. {
  80. int a;
  81. if (get_options()->DirPolicy && !dir_policy)
  82. parse_dir_policy();
  83. if(!dir_policy) /* 'no dir policy' means 'accept' */
  84. return 1;
  85. a = router_compare_addr_to_exit_policy(addr, 1, dir_policy);
  86. if (a==-1)
  87. return 0;
  88. else if (a==0)
  89. return 1;
  90. tor_assert(a==1);
  91. log_fn(LOG_WARN, "Got unexpected 'maybe' answer from dir policy");
  92. return 0;
  93. }
  94. /** Start a connection to every known directory server, using
  95. * connection purpose 'purpose' and uploading the payload 'payload'
  96. * (length 'payload_len'). The purpose should be one of
  97. * 'DIR_PURPOSE_UPLOAD_DIR' or 'DIR_PURPOSE_UPLOAD_RENDDESC'.
  98. */
  99. void
  100. directory_post_to_dirservers(uint8_t purpose, const char *payload,
  101. size_t payload_len)
  102. {
  103. smartlist_t *dirservers;
  104. char buf[16];
  105. router_get_trusted_dir_servers(&dirservers);
  106. tor_assert(dirservers);
  107. /* This tries dirservers which we believe to be down, but ultimately, that's
  108. * harmless, and we may as well err on the side of getting things uploaded.
  109. */
  110. SMARTLIST_FOREACH(dirservers, trusted_dir_server_t *, ds,
  111. {
  112. /* Pay attention to fascistfirewall when we're uploading a
  113. * router descriptor, but not when uploading a service
  114. * descriptor -- those use Tor. */
  115. if (get_options()->FascistFirewall && purpose == DIR_PURPOSE_UPLOAD_DIR &&
  116. !get_options()->HttpProxy) {
  117. tor_snprintf(buf,sizeof(buf),"%d",ds->dir_port);
  118. if (!smartlist_string_isin(get_options()->FirewallPorts, buf))
  119. continue;
  120. }
  121. directory_initiate_command_trusted_dir(ds, purpose, payload, payload_len);
  122. });
  123. }
  124. /** Start a connection to a random running directory server, using
  125. * connection purpose 'purpose' requesting 'payload' (length
  126. * 'payload_len'). The purpose should be one of
  127. * 'DIR_PURPOSE_FETCH_DIR' or 'DIR_PURPOSE_FETCH_RENDDESC'.
  128. */
  129. void
  130. directory_get_from_dirserver(uint8_t purpose, const char *payload,
  131. size_t payload_len)
  132. {
  133. routerinfo_t *r = NULL;
  134. trusted_dir_server_t *ds = NULL;
  135. if (purpose == DIR_PURPOSE_FETCH_DIR) {
  136. if (advertised_server_mode()) {
  137. /* only ask authdirservers, and don't ask myself */
  138. ds = router_pick_trusteddirserver(1, get_options()->FascistFirewall);
  139. } else {
  140. /* anybody with a non-zero dirport will do */
  141. r = router_pick_directory_server(1, get_options()->FascistFirewall);
  142. if (!r) {
  143. log_fn(LOG_INFO, "No router found for directory; falling back to dirserver list");
  144. ds = router_pick_trusteddirserver(1, get_options()->FascistFirewall);
  145. }
  146. }
  147. } else { // (purpose == DIR_PURPOSE_FETCH_RENDDESC)
  148. /* only ask authdirservers, any of them will do */
  149. /* Never use fascistfirewall; we're going via Tor. */
  150. ds = router_pick_trusteddirserver(0, 0);
  151. }
  152. if (r)
  153. directory_initiate_command_router(r, purpose, payload, payload_len);
  154. else if (ds)
  155. directory_initiate_command_trusted_dir(ds, purpose, payload, payload_len);
  156. else
  157. log_fn(LOG_WARN,"No running dirservers known. Not trying. (purpose %d)", purpose);
  158. }
  159. /** Launch a new connection to the directory server <b>router</b> to upload or
  160. * download a service or rendezvous descriptor. <b>purpose</b> determines what
  161. * kind of directory connection we're launching, and must be one of
  162. * DIR_PURPOSE_{FETCH|UPLOAD}_{DIR|RENDDESC}.
  163. *
  164. * When uploading, <b>payload</b> and <b>payload_len</b> determine the content
  165. * of the HTTP post. When fetching a rendezvous descriptor, <b>payload</b>
  166. * and <b>payload_len</b> are the service ID we want to fetch.
  167. */
  168. static void
  169. directory_initiate_command_router(routerinfo_t *router, uint8_t purpose,
  170. const char *payload, size_t payload_len)
  171. {
  172. directory_initiate_command(router->address, router->addr, router->dir_port,
  173. router->platform, router->identity_digest,
  174. purpose, payload, payload_len);
  175. }
  176. static void
  177. directory_initiate_command_trusted_dir(trusted_dir_server_t *dirserv,
  178. uint8_t purpose, const char *payload, size_t payload_len)
  179. {
  180. directory_initiate_command(dirserv->address, dirserv->addr,dirserv->dir_port,
  181. NULL, dirserv->digest, purpose, payload, payload_len);
  182. }
  183. static void
  184. directory_initiate_command(const char *address, uint32_t addr,
  185. uint16_t dir_port, const char *platform,
  186. const char *digest, uint8_t purpose,
  187. const char *payload, size_t payload_len)
  188. {
  189. connection_t *conn;
  190. tor_assert(address);
  191. tor_assert(addr);
  192. tor_assert(dir_port);
  193. tor_assert(digest);
  194. switch (purpose) {
  195. case DIR_PURPOSE_FETCH_DIR:
  196. log_fn(LOG_DEBUG,"initiating directory fetch");
  197. break;
  198. case DIR_PURPOSE_FETCH_RENDDESC:
  199. log_fn(LOG_DEBUG,"initiating hidden-service descriptor fetch");
  200. break;
  201. case DIR_PURPOSE_UPLOAD_DIR:
  202. log_fn(LOG_DEBUG,"initiating server descriptor upload");
  203. break;
  204. case DIR_PURPOSE_UPLOAD_RENDDESC:
  205. log_fn(LOG_DEBUG,"initiating hidden-service descriptor upload");
  206. break;
  207. default:
  208. log_fn(LOG_ERR, "Unrecognized directory connection purpose.");
  209. tor_assert(0);
  210. }
  211. conn = connection_new(CONN_TYPE_DIR);
  212. /* set up conn so it's got all the data we need to remember */
  213. conn->addr = addr;
  214. conn->port = dir_port;
  215. if(get_options()->HttpProxy) {
  216. addr = get_options()->HttpProxyAddr;
  217. dir_port = get_options()->HttpProxyPort;
  218. }
  219. conn->address = tor_strdup(address);
  220. /* conn->nickname = tor_strdup(router->nickname); */
  221. /* tor_assert(router->identity_pkey); */
  222. /* conn->identity_pkey = crypto_pk_dup_key(router->identity_pkey); */
  223. /* crypto_pk_get_digest(conn->identity_pkey, conn->identity_digest); */
  224. memcpy(conn->identity_digest, digest, DIGEST_LEN);
  225. conn->purpose = purpose;
  226. /* give it an initial state */
  227. conn->state = DIR_CONN_STATE_CONNECTING;
  228. if(purpose == DIR_PURPOSE_FETCH_DIR ||
  229. purpose == DIR_PURPOSE_UPLOAD_DIR) {
  230. /* then we want to connect directly */
  231. switch(connection_connect(conn, conn->address, addr, dir_port)) {
  232. case -1:
  233. router_mark_as_down(conn->identity_digest); /* don't try him again */
  234. if(purpose == DIR_PURPOSE_FETCH_DIR &&
  235. !all_trusted_directory_servers_down()) {
  236. log_fn(LOG_INFO,"Giving up on dirserver %s; trying another.", conn->address);
  237. directory_get_from_dirserver(purpose, payload, payload_len);
  238. }
  239. connection_free(conn);
  240. return;
  241. case 1:
  242. conn->state = DIR_CONN_STATE_CLIENT_SENDING; /* start flushing conn */
  243. /* fall through */
  244. case 0:
  245. /* queue the command on the outbuf */
  246. directory_send_command(conn, platform, purpose, payload, payload_len);
  247. connection_watch_events(conn, POLLIN | POLLOUT | POLLERR);
  248. /* writable indicates finish, readable indicates broken link,
  249. error indicates broken link in windowsland. */
  250. }
  251. } else { /* we want to connect via tor */
  252. /* make an AP connection
  253. * populate it and add it at the right state
  254. * socketpair and hook up both sides
  255. */
  256. conn->s = connection_ap_make_bridge(conn->address, conn->port);
  257. if(conn->s < 0) {
  258. log_fn(LOG_WARN,"Making AP bridge to dirserver failed.");
  259. connection_mark_for_close(conn);
  260. return;
  261. }
  262. conn->state = DIR_CONN_STATE_CLIENT_SENDING;
  263. connection_add(conn);
  264. /* queue the command on the outbuf */
  265. directory_send_command(conn, platform, purpose, payload, payload_len);
  266. connection_watch_events(conn, POLLIN | POLLOUT | POLLERR);
  267. }
  268. }
  269. /** Queue an appropriate HTTP command on conn-\>outbuf. The args
  270. * <b>purpose</b>, <b>payload</b>, and <b>payload_len</b> are as in
  271. * directory_initiate_command.
  272. */
  273. static void
  274. directory_send_command(connection_t *conn, const char *platform,
  275. int purpose, const char *payload, size_t payload_len) {
  276. char tmp[8192];
  277. char proxystring[128];
  278. char hoststring[128];
  279. char url[128];
  280. int use_newer = 0;
  281. const char *httpcommand = NULL;
  282. tor_assert(conn);
  283. tor_assert(conn->type == CONN_TYPE_DIR);
  284. /* If we don't know the platform, assume it's up-to-date. */
  285. use_newer = platform ? tor_version_as_new_as(platform, "0.0.9pre1"):1;
  286. if(conn->port == 80) {
  287. strlcpy(hoststring, conn->address, sizeof(hoststring));
  288. } else {
  289. tor_snprintf(hoststring, sizeof(hoststring),"%s:%d",conn->address, conn->port);
  290. }
  291. if(get_options()->HttpProxy) {
  292. tor_snprintf(proxystring, sizeof(proxystring),"http://%s", hoststring);
  293. } else {
  294. proxystring[0] = 0;
  295. }
  296. switch(purpose) {
  297. case DIR_PURPOSE_FETCH_DIR:
  298. tor_assert(payload == NULL);
  299. log_fn(LOG_DEBUG, "Asking for %scompressed directory from server running %s",
  300. use_newer?"":"un", platform?platform:"<unknown version>");
  301. httpcommand = "GET";
  302. strlcpy(url, use_newer ? "/tor/dir.z" : "/", sizeof(url));
  303. break;
  304. case DIR_PURPOSE_FETCH_RUNNING_LIST:
  305. tor_assert(payload == NULL);
  306. httpcommand = "GET";
  307. strlcpy(url, use_newer ? "/tor/running-routers" : "/running-routers", sizeof(url));
  308. break;
  309. case DIR_PURPOSE_UPLOAD_DIR:
  310. tor_assert(payload);
  311. httpcommand = "POST";
  312. strlcpy(url, use_newer ? "/tor/" : "/", sizeof(url));
  313. break;
  314. case DIR_PURPOSE_FETCH_RENDDESC:
  315. tor_assert(payload);
  316. /* this must be true or we wouldn't be doing the lookup */
  317. tor_assert(payload_len <= REND_SERVICE_ID_LEN);
  318. /* This breaks the function abstraction. */
  319. memcpy(conn->rend_query, payload, payload_len);
  320. conn->rend_query[payload_len] = 0;
  321. httpcommand = "GET";
  322. tor_snprintf(url, sizeof(url), "%s/rendezvous/%s", use_newer ? "/tor" : "", payload);
  323. /* XXX We're using payload here to mean something other than
  324. * payload of the http post. This is probably bad, and should
  325. * be fixed one day. Kludge for now to make sure we don't post more. */
  326. payload_len = 0;
  327. payload = NULL;
  328. break;
  329. case DIR_PURPOSE_UPLOAD_RENDDESC:
  330. tor_assert(payload);
  331. httpcommand = "POST";
  332. tor_snprintf(url, sizeof(url), "%s/rendezvous/publish", use_newer ? "/tor" : "");
  333. break;
  334. }
  335. tor_snprintf(tmp, sizeof(tmp), "%s %s%s HTTP/1.0\r\nContent-Length: %lu\r\nHost: %s\r\n\r\n",
  336. httpcommand,
  337. proxystring,
  338. url,
  339. (unsigned long)payload_len,
  340. hoststring);
  341. connection_write_to_buf(tmp, strlen(tmp), conn);
  342. if(payload) {
  343. /* then send the payload afterwards too */
  344. connection_write_to_buf(payload, payload_len, conn);
  345. }
  346. }
  347. /** Parse an HTTP request string <b>headers</b> of the form
  348. * "\%s [http[s]://]\%s HTTP/1..."
  349. * If it's well-formed, strdup the second \%s into *<b>url</b>, and
  350. * null-terminate it. If the url doesn't start with "/tor/", rewrite it
  351. * so it does. Return 0.
  352. * Otherwise, return -1.
  353. */
  354. static int
  355. parse_http_url(char *headers, char **url)
  356. {
  357. char *s, *start, *tmp;
  358. s = (char *)eat_whitespace_no_nl(headers);
  359. if (!*s) return -1;
  360. s = (char *)find_whitespace(s); /* get past GET/POST */
  361. if (!*s) return -1;
  362. s = (char *)eat_whitespace_no_nl(s);
  363. if (!*s) return -1;
  364. start = s; /* this is it, assuming it's valid */
  365. s = (char *)find_whitespace(start);
  366. if (!*s) return -1;
  367. /* tolerate the http[s] proxy style of putting the hostname in the url */
  368. if(s-start >= 4 && !strcmpstart(start,"http")) {
  369. tmp = start + 4;
  370. if(*tmp == 's')
  371. tmp++;
  372. if(s-tmp >= 3 && !strcmpstart(tmp,"://")) {
  373. tmp = strchr(tmp+3, '/');
  374. if(tmp && tmp < s) {
  375. log_fn(LOG_DEBUG,"Skipping over 'http[s]://hostname' string");
  376. start = tmp;
  377. }
  378. }
  379. }
  380. if(s-start < 5 || strcmpstart(start,"/tor/")) { /* need to rewrite it */
  381. *url = tor_malloc(s - start + 5);
  382. strlcpy(*url,"/tor", s-start+5);
  383. strlcat((*url)+4, start, s-start+1);
  384. } else {
  385. *url = tor_strndup(start, s-start);
  386. }
  387. return 0;
  388. }
  389. /** Parse an HTTP response string <b>headers</b> of the form
  390. * "HTTP/1.\%d \%d\%s\r\n...".
  391. * If it's well-formed, assign *<b>code</b>, point *<b>message</b> to the first
  392. * non-space character after code if there is one and message is non-NULL
  393. * (else leave it alone), and return 0.
  394. * If <b>date</b> is provided, set *date to the Date header in the
  395. * http headers, or 0 if no such header is found.
  396. * Otherwise, return -1.
  397. */
  398. static int
  399. parse_http_response(char *headers, int *code, char **message, time_t *date,
  400. int *compression)
  401. {
  402. int n1, n2;
  403. char datestr[RFC1123_TIME_LEN+1];
  404. smartlist_t *parsed_headers;
  405. tor_assert(headers);
  406. tor_assert(code);
  407. while(isspace((int)*headers)) headers++; /* tolerate leading whitespace */
  408. if(sscanf(headers, "HTTP/1.%d %d", &n1, &n2) < 2 ||
  409. (n1 != 0 && n1 != 1) ||
  410. (n2 < 100 || n2 >= 600)) {
  411. log_fn(LOG_WARN,"Failed to parse header '%s'",headers);
  412. return -1;
  413. }
  414. *code = n2;
  415. if(message) {
  416. /* XXX should set *message correctly */
  417. }
  418. parsed_headers = smartlist_create();
  419. smartlist_split_string(parsed_headers, headers, "\n",
  420. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  421. if (date) {
  422. *date = 0;
  423. SMARTLIST_FOREACH(parsed_headers, const char *, s,
  424. if (!strcmpstart(s, "Date: ")) {
  425. strlcpy(datestr, s+6, sizeof(datestr));
  426. /* This will do nothing on failure, so we don't need to check
  427. the result. We shouldn't warn, since there are many other valid
  428. date formats besides the one we use. */
  429. parse_rfc1123_time(datestr, date);
  430. break;
  431. });
  432. }
  433. if (compression) {
  434. const char *enc = NULL;
  435. SMARTLIST_FOREACH(parsed_headers, const char *, s,
  436. if (!strcmpstart(s, "Content-Encoding: ")) {
  437. enc = s+18; break;
  438. });
  439. if (!enc || !strcmp(enc, "identity")) {
  440. *compression = 0;
  441. } else if (!strcmp(enc, "deflate") || !strcmp(enc, "x-deflate")) {
  442. *compression = ZLIB_METHOD;
  443. } else if (!strcmp(enc, "gzip") || !strcmp(enc, "x-gzip")) {
  444. *compression = GZIP_METHOD;
  445. } else {
  446. log_fn(LOG_WARN, "Unrecognized content encoding: '%s'", enc);
  447. *compression = 0;
  448. }
  449. }
  450. SMARTLIST_FOREACH(parsed_headers, char *, s, tor_free(s));
  451. smartlist_free(parsed_headers);
  452. return 0;
  453. }
  454. /** We are a client, and we've finished reading the server's
  455. * response. Parse and it and act appropriately.
  456. *
  457. * Return -1 if an error has occurred, or 0 normally. The caller
  458. * will take care of marking the connection for close.
  459. */
  460. static int
  461. connection_dir_client_reached_eof(connection_t *conn)
  462. {
  463. char *body;
  464. char *headers;
  465. size_t body_len=0;
  466. int status_code;
  467. time_t now, date_header=0;
  468. int delta;
  469. int compression;
  470. switch(fetch_from_buf_http(conn->inbuf,
  471. &headers, MAX_HEADERS_SIZE,
  472. &body, &body_len, MAX_DIR_SIZE)) {
  473. case -1: /* overflow */
  474. log_fn(LOG_WARN,"'fetch' response too large. Failing.");
  475. return -1;
  476. case 0:
  477. log_fn(LOG_INFO,"'fetch' response not all here, but we're at eof. Closing.");
  478. return -1;
  479. /* case 1, fall through */
  480. }
  481. if(parse_http_response(headers, &status_code, NULL, &date_header,
  482. &compression) < 0) {
  483. log_fn(LOG_WARN,"Unparseable headers. Closing.");
  484. tor_free(body); tor_free(headers);
  485. return -1;
  486. }
  487. if (date_header > 0) {
  488. now = time(NULL);
  489. delta = now-date_header;
  490. if (abs(delta)>ALLOW_DIRECTORY_TIME_SKEW) {
  491. log_fn(LOG_WARN, "Received directory with skewed time: we are %d minutes %s, or the directory is %d minutes %s.",
  492. abs(delta)/60, delta>0 ? "ahead" : "behind",
  493. abs(delta)/60, delta>0 ? "behind" : "ahead");
  494. } else {
  495. log_fn(LOG_INFO, "Time on received directory is within tolerance; we are %d seconds skewed. (That's okay.)", delta);
  496. }
  497. }
  498. if (compression != 0) {
  499. char *new_body;
  500. size_t new_len;
  501. if (tor_gzip_uncompress(&new_body, &new_len, body, body_len, compression)) {
  502. log_fn(LOG_WARN, "Unable to decompress HTTP body.");
  503. tor_free(body); tor_free(headers);
  504. return -1;
  505. }
  506. tor_free(body);
  507. body = new_body;
  508. body_len = new_len;
  509. }
  510. if(conn->purpose == DIR_PURPOSE_FETCH_DIR) {
  511. /* fetch/process the directory to learn about new routers. */
  512. log_fn(LOG_INFO,"Received directory (size %d):\n%s", (int)body_len, body);
  513. if(status_code == 503 || body_len == 0) {
  514. log_fn(LOG_INFO,"Empty directory. Ignoring.");
  515. tor_free(body); tor_free(headers);
  516. return 0;
  517. }
  518. if(status_code != 200) {
  519. log_fn(LOG_WARN,"Received http status code %d from dirserver. Failing.",
  520. status_code);
  521. tor_free(body); tor_free(headers);
  522. return -1;
  523. }
  524. if(router_load_routerlist_from_directory(body, NULL, 1) < 0){
  525. log_fn(LOG_WARN,"I failed to parse the directory I fetched from %s:%d. Ignoring.", conn->address, conn->port);
  526. } else {
  527. log_fn(LOG_INFO,"updated routers.");
  528. }
  529. directory_has_arrived(time(NULL)); /* do things we've been waiting to do */
  530. }
  531. if(conn->purpose == DIR_PURPOSE_FETCH_RUNNING_LIST) {
  532. running_routers_t *rrs;
  533. routerlist_t *rl;
  534. /* just update our list of running routers, if this list is new info */
  535. log_fn(LOG_INFO,"Received running-routers list (size %d):\n%s", (int)body_len, body);
  536. if(status_code != 200) {
  537. log_fn(LOG_WARN,"Received http status code %d from dirserver. Failing.",
  538. status_code);
  539. tor_free(body); tor_free(headers);
  540. return -1;
  541. }
  542. if (!(rrs = router_parse_runningrouters(body))) {
  543. log_fn(LOG_WARN, "Can't parse runningrouters list");
  544. tor_free(body); tor_free(headers);
  545. return -1;
  546. }
  547. router_get_routerlist(&rl);
  548. if (rl)
  549. routerlist_update_from_runningrouters(rl,rrs);
  550. running_routers_free(rrs);
  551. }
  552. if(conn->purpose == DIR_PURPOSE_UPLOAD_DIR) {
  553. switch(status_code) {
  554. case 200:
  555. log_fn(LOG_INFO,"eof (status 200) after uploading server descriptor: finished.");
  556. break;
  557. case 400:
  558. log_fn(LOG_WARN,"http status 400 (bad request) response from dirserver. Malformed server descriptor?");
  559. break;
  560. case 403:
  561. log_fn(LOG_WARN,"http status 403 (unapproved server) response from dirserver. Is your clock skewed? Have you mailed us your identity fingerprint? Are you using the right key? See README.");
  562. break;
  563. default:
  564. log_fn(LOG_WARN,"http status %d response unrecognized.", status_code);
  565. break;
  566. }
  567. }
  568. if(conn->purpose == DIR_PURPOSE_FETCH_RENDDESC) {
  569. log_fn(LOG_INFO,"Received rendezvous descriptor (size %d, status code %d)",
  570. (int)body_len, status_code);
  571. switch(status_code) {
  572. case 200:
  573. if(rend_cache_store(body, body_len) < 0) {
  574. log_fn(LOG_WARN,"Failed to store rendezvous descriptor.");
  575. /* alice's ap_stream will notice when connection_mark_for_close
  576. * cleans it up */
  577. } else {
  578. /* success. notify pending connections about this. */
  579. rend_client_desc_fetched(conn->rend_query, 1);
  580. conn->purpose = DIR_PURPOSE_HAS_FETCHED_RENDDESC;
  581. }
  582. break;
  583. case 404:
  584. /* not there. pending connections will be notified when
  585. * connection_mark_for_close cleans it up. */
  586. break;
  587. case 400:
  588. log_fn(LOG_WARN,"http status 400 (bad request). Dirserver didn't like our rendezvous query?");
  589. break;
  590. }
  591. }
  592. if(conn->purpose == DIR_PURPOSE_UPLOAD_RENDDESC) {
  593. switch(status_code) {
  594. case 200:
  595. log_fn(LOG_INFO,"eof (status 200) after uploading rendezvous descriptor: finished.");
  596. break;
  597. case 400:
  598. log_fn(LOG_WARN,"http status 400 (bad request) response from dirserver. Malformed rendezvous descriptor?");
  599. break;
  600. default:
  601. log_fn(LOG_WARN,"http status %d response unrecognized.", status_code);
  602. break;
  603. }
  604. }
  605. tor_free(body); tor_free(headers);
  606. return 0;
  607. }
  608. /** Read handler for directory connections. (That's connections <em>to</em>
  609. * directory servers and connections <em>at</em> directory servers.)
  610. */
  611. int connection_dir_process_inbuf(connection_t *conn) {
  612. int retval;
  613. tor_assert(conn);
  614. tor_assert(conn->type == CONN_TYPE_DIR);
  615. /* Directory clients write, then read data until they receive EOF;
  616. * directory servers read data until they get an HTTP command, then
  617. * write their response (when it's finished flushing, they mark for
  618. * close).
  619. */
  620. if(conn->inbuf_reached_eof) {
  621. if(conn->state != DIR_CONN_STATE_CLIENT_READING) {
  622. log_fn(LOG_INFO,"conn reached eof, not reading. Closing.");
  623. connection_close_immediate(conn); /* it was an error; give up on flushing */
  624. connection_mark_for_close(conn);
  625. return -1;
  626. }
  627. retval = connection_dir_client_reached_eof(conn);
  628. connection_mark_for_close(conn);
  629. return retval;
  630. } /* endif 'reached eof' */
  631. /* If we're on the dirserver side, look for a command. */
  632. if(conn->state == DIR_CONN_STATE_SERVER_COMMAND_WAIT) {
  633. if (directory_handle_command(conn) < 0) {
  634. connection_mark_for_close(conn);
  635. return -1;
  636. }
  637. return 0;
  638. }
  639. /* XXX for READ states, might want to make sure inbuf isn't too big */
  640. log_fn(LOG_DEBUG,"Got data, not eof. Leaving on inbuf.");
  641. return 0;
  642. }
  643. static char answer200[] = "HTTP/1.0 200 OK\r\n\r\n";
  644. static char answer400[] = "HTTP/1.0 400 Bad request\r\n\r\n";
  645. static char answer403[] = "HTTP/1.0 403 Unapproved server\r\n\r\n";
  646. static char answer404[] = "HTTP/1.0 404 Not found\r\n\r\n";
  647. static char answer503[] = "HTTP/1.0 503 Directory unavailable\r\n\r\n";
  648. /** Helper function: called when a dirserver gets a complete HTTP GET
  649. * request. Look for a request for a directory or for a rendezvous
  650. * service descriptor. On finding one, write a response into
  651. * conn-\>outbuf. If the request is unrecognized, send a 400.
  652. * Always return 0. */
  653. static int
  654. directory_handle_command_get(connection_t *conn, char *headers,
  655. char *body, size_t body_len)
  656. {
  657. size_t dlen;
  658. const char *cp;
  659. char *url;
  660. char tmp[8192];
  661. char date[RFC1123_TIME_LEN+1];
  662. log_fn(LOG_DEBUG,"Received GET command.");
  663. conn->state = DIR_CONN_STATE_SERVER_WRITING;
  664. if (parse_http_url(headers, &url) < 0) {
  665. connection_write_to_buf(answer400, strlen(answer400), conn);
  666. return 0;
  667. }
  668. log_fn(LOG_INFO,"rewritten url as '%s'.", url);
  669. if(!strcmp(url,"/tor/") || !strcmp(url,"/tor/dir.z")) { /* directory fetch */
  670. int deflated = !strcmp(url,"/tor/dir.z");
  671. dlen = dirserv_get_directory(&cp, deflated);
  672. tor_free(url);
  673. if(dlen == 0) {
  674. log_fn(LOG_WARN,"My directory is empty. Closing.");
  675. connection_write_to_buf(answer503, strlen(answer503), conn);
  676. return 0;
  677. }
  678. log_fn(LOG_DEBUG,"Dumping %sdirectory to client.",
  679. deflated?"deflated ":"");
  680. format_rfc1123_time(date, time(NULL));
  681. tor_snprintf(tmp, sizeof(tmp), "HTTP/1.0 200 OK\r\nDate: %s\r\nContent-Length: %d\r\nContent-Type: text/plain\r\nContent-Encoding: %s\r\n\r\n",
  682. date,
  683. (int)dlen,
  684. deflated?"deflate":"identity");
  685. connection_write_to_buf(tmp, strlen(tmp), conn);
  686. connection_write_to_buf(cp, dlen, conn);
  687. return 0;
  688. }
  689. if(!strcmp(url,"/tor/running-routers")) { /* running-routers fetch */
  690. tor_free(url);
  691. if(!authdir_mode(get_options())) {
  692. /* XXX008 for now, we don't cache running-routers. Reject. */
  693. connection_write_to_buf(answer400, strlen(answer400), conn);
  694. return 0;
  695. }
  696. dlen = dirserv_get_runningrouters(&cp);
  697. if(!dlen) { /* we failed to create cp */
  698. connection_write_to_buf(answer503, strlen(answer503), conn);
  699. return 0;
  700. }
  701. format_rfc1123_time(date, time(NULL));
  702. tor_snprintf(tmp, sizeof(tmp), "HTTP/1.0 200 OK\r\nDate: %s\r\nContent-Length: %d\r\nContent-Type: text/plain\r\n\r\n",
  703. date,
  704. (int)dlen);
  705. connection_write_to_buf(tmp, strlen(tmp), conn);
  706. connection_write_to_buf(cp, strlen(cp), conn);
  707. return 0;
  708. }
  709. if(!strcmpstart(url,"/tor/rendezvous/")) {
  710. /* rendezvous descriptor fetch */
  711. const char *descp;
  712. size_t desc_len;
  713. if(!authdir_mode(get_options())) {
  714. /* We don't hand out rend descs. In fact, it could be a security
  715. * risk, since rend_cache_lookup_desc() below would provide it
  716. * if we're gone to the site recently, and 404 if we haven't.
  717. *
  718. * Reject. */
  719. connection_write_to_buf(answer400, strlen(answer400), conn);
  720. tor_free(url);
  721. return 0;
  722. }
  723. switch(rend_cache_lookup_desc(url+strlen("/tor/rendezvous/"), &descp, &desc_len)) {
  724. case 1: /* valid */
  725. format_rfc1123_time(date, time(NULL));
  726. tor_snprintf(tmp, sizeof(tmp), "HTTP/1.0 200 OK\r\nDate: %s\r\nContent-Length: %d\r\nContent-Type: application/octet-stream\r\n\r\n",
  727. date,
  728. (int)desc_len); /* can't include descp here, because it's got nuls */
  729. connection_write_to_buf(tmp, strlen(tmp), conn);
  730. connection_write_to_buf(descp, desc_len, conn);
  731. break;
  732. case 0: /* well-formed but not present */
  733. connection_write_to_buf(answer404, strlen(answer404), conn);
  734. break;
  735. case -1: /* not well-formed */
  736. connection_write_to_buf(answer400, strlen(answer400), conn);
  737. break;
  738. }
  739. tor_free(url);
  740. return 0;
  741. }
  742. /* we didn't recognize the url */
  743. connection_write_to_buf(answer404, strlen(answer404), conn);
  744. tor_free(url);
  745. return 0;
  746. }
  747. /** Helper function: called when a dirserver gets a complete HTTP POST
  748. * request. Look for an uploaded server descriptor or rendezvous
  749. * service descriptor. On finding one, process it and write a
  750. * response into conn-\>outbuf. If the request is unrecognized, send a
  751. * 400. Always return 0. */
  752. static int
  753. directory_handle_command_post(connection_t *conn, char *headers,
  754. char *body, size_t body_len)
  755. {
  756. const char *cp;
  757. char *url;
  758. log_fn(LOG_DEBUG,"Received POST command.");
  759. conn->state = DIR_CONN_STATE_SERVER_WRITING;
  760. if(!authdir_mode(get_options())) {
  761. /* we just provide cached directories; we don't want to
  762. * receive anything. */
  763. connection_write_to_buf(answer400, strlen(answer400), conn);
  764. return 0;
  765. }
  766. if (parse_http_url(headers, &url) < 0) {
  767. connection_write_to_buf(answer400, strlen(answer400), conn);
  768. return 0;
  769. }
  770. log_fn(LOG_INFO,"rewritten url as '%s'.", url);
  771. if(!strcmp(url,"/tor/")) { /* server descriptor post */
  772. cp = body;
  773. switch(dirserv_add_descriptor(&cp)) {
  774. case -1:
  775. /* malformed descriptor, or something wrong */
  776. connection_write_to_buf(answer400, strlen(answer400), conn);
  777. break;
  778. case 0:
  779. /* descriptor was well-formed but server has not been approved */
  780. connection_write_to_buf(answer403, strlen(answer403), conn);
  781. break;
  782. case 1:
  783. dirserv_get_directory(&cp, 0); /* rebuild and write to disk */
  784. connection_write_to_buf(answer200, strlen(answer200), conn);
  785. break;
  786. }
  787. tor_free(url);
  788. return 0;
  789. }
  790. if(!strcmpstart(url,"/tor/rendezvous/publish")) {
  791. /* rendezvous descriptor post */
  792. if(rend_cache_store(body, body_len) < 0)
  793. connection_write_to_buf(answer400, strlen(answer400), conn);
  794. else
  795. connection_write_to_buf(answer200, strlen(answer200), conn);
  796. tor_free(url);
  797. return 0;
  798. }
  799. /* we didn't recognize the url */
  800. connection_write_to_buf(answer404, strlen(answer404), conn);
  801. tor_free(url);
  802. return 0;
  803. }
  804. /** Called when a dirserver receives data on a directory connection;
  805. * looks for an HTTP request. If the request is complete, remove it
  806. * from the inbuf, try to process it; otherwise, leave it on the
  807. * buffer. Return a 0 on success, or -1 on error.
  808. */
  809. static int directory_handle_command(connection_t *conn) {
  810. char *headers=NULL, *body=NULL;
  811. size_t body_len=0;
  812. int r;
  813. tor_assert(conn);
  814. tor_assert(conn->type == CONN_TYPE_DIR);
  815. switch(fetch_from_buf_http(conn->inbuf,
  816. &headers, MAX_HEADERS_SIZE,
  817. &body, &body_len, MAX_BODY_SIZE)) {
  818. case -1: /* overflow */
  819. log_fn(LOG_WARN,"Invalid input. Closing.");
  820. return -1;
  821. case 0:
  822. log_fn(LOG_DEBUG,"command not all here yet.");
  823. return 0;
  824. /* case 1, fall through */
  825. }
  826. log_fn(LOG_DEBUG,"headers '%s', body '%s'.", headers, body);
  827. if(!strncasecmp(headers,"GET",3))
  828. r = directory_handle_command_get(conn, headers, body, body_len);
  829. else if (!strncasecmp(headers,"POST",4))
  830. r = directory_handle_command_post(conn, headers, body, body_len);
  831. else {
  832. log_fn(LOG_WARN,"Got headers '%s' with unknown command. Closing.", headers);
  833. r = -1;
  834. }
  835. tor_free(headers); tor_free(body);
  836. return r;
  837. }
  838. /** Write handler for directory connections; called when all data has
  839. * been flushed. Close the connection or wait for a response as
  840. * appropriate.
  841. */
  842. int connection_dir_finished_flushing(connection_t *conn) {
  843. tor_assert(conn);
  844. tor_assert(conn->type == CONN_TYPE_DIR);
  845. switch(conn->state) {
  846. case DIR_CONN_STATE_CLIENT_SENDING:
  847. log_fn(LOG_DEBUG,"client finished sending command.");
  848. conn->state = DIR_CONN_STATE_CLIENT_READING;
  849. connection_stop_writing(conn);
  850. return 0;
  851. case DIR_CONN_STATE_SERVER_WRITING:
  852. log_fn(LOG_INFO,"Finished writing server response. Closing.");
  853. connection_mark_for_close(conn);
  854. return 0;
  855. default:
  856. log_fn(LOG_WARN,"BUG: called in unexpected state %d.", conn->state);
  857. return -1;
  858. }
  859. return 0;
  860. }
  861. /** Connected handler for directory connections: begin sending data to the
  862. * server */
  863. int connection_dir_finished_connecting(connection_t *conn)
  864. {
  865. tor_assert(conn);
  866. tor_assert(conn->type == CONN_TYPE_DIR);
  867. tor_assert(conn->state == DIR_CONN_STATE_CONNECTING);
  868. log_fn(LOG_INFO,"Dir connection to router %s:%u established.",
  869. conn->address,conn->port);
  870. conn->state = DIR_CONN_STATE_CLIENT_SENDING; /* start flushing conn */
  871. return 0;
  872. }
  873. /*
  874. Local Variables:
  875. mode:c
  876. indent-tabs-mode:nil
  877. c-basic-offset:2
  878. End:
  879. */