directory.c 32 KB

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