directory.c 31 KB

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