directory.c 27 KB

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