directory.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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. static void directory_send_command(connection_t *conn, int purpose,
  10. const char *payload, int payload_len);
  11. static int directory_handle_command(connection_t *conn);
  12. /********* START VARIABLES **********/
  13. extern or_options_t options; /* command-line and config-file options */
  14. /** URL for publishing rendezvous descriptors. */
  15. char rend_publish_string[] = "/rendezvous/publish";
  16. /** Prefix for downloading rendezvous descriptors. */
  17. char rend_fetch_url[] = "/rendezvous/";
  18. #define MAX_HEADERS_SIZE 10000
  19. #define MAX_BODY_SIZE 500000
  20. /********* END VARIABLES ************/
  21. /** Launch a new connection to the directory server 'router' to upload
  22. * or download a service or rendezvous descriptor. 'purpose' determines what
  23. * kind of directory connection we're launching, and must be one of
  24. * DIR_PURPOSE_{FETCH|UPLOAD}_{DIR|RENDDESC}.
  25. *
  26. * When uploading, 'payload' and 'payload_len' determine the content
  27. * of the HTTP post. When fetching a rendezvous descriptor, 'payload'
  28. * and 'payload_len' are the service ID we want to fetch.
  29. */
  30. void directory_initiate_command(routerinfo_t *router, int purpose,
  31. const char *payload, int payload_len) {
  32. connection_t *conn;
  33. switch (purpose)
  34. {
  35. case DIR_PURPOSE_FETCH_DIR:
  36. log_fn(LOG_DEBUG,"initiating directory fetch");
  37. break;
  38. case DIR_PURPOSE_FETCH_RENDDESC:
  39. log_fn(LOG_DEBUG,"initiating hidden-service descriptor fetch");
  40. break;
  41. case DIR_PURPOSE_UPLOAD_DIR:
  42. log_fn(LOG_DEBUG,"initiating server descriptor upload");
  43. break;
  44. case DIR_PURPOSE_UPLOAD_RENDDESC:
  45. log_fn(LOG_DEBUG,"initiating hidden-service descriptor upload");
  46. break;
  47. default:
  48. log_fn(LOG_ERR, "Unrecognized directory connection purpose.");
  49. tor_assert(0);
  50. }
  51. if (!router) { /* i guess they didn't have one in mind for me to use */
  52. log_fn(LOG_WARN,"No running dirservers known. Not trying. (purpose %d)", purpose);
  53. return;
  54. }
  55. conn = connection_new(CONN_TYPE_DIR);
  56. /* set up conn so it's got all the data we need to remember */
  57. conn->addr = router->addr;
  58. conn->port = router->dir_port;
  59. conn->address = tor_strdup(router->address);
  60. conn->nickname = tor_strdup(router->nickname);
  61. tor_assert(router->identity_pkey);
  62. conn->identity_pkey = crypto_pk_dup_key(router->identity_pkey);
  63. conn->purpose = purpose;
  64. /* give it an initial state */
  65. conn->state = DIR_CONN_STATE_CONNECTING;
  66. if(purpose == DIR_PURPOSE_FETCH_DIR ||
  67. purpose == DIR_PURPOSE_UPLOAD_DIR) {
  68. /* then we want to connect directly */
  69. switch(connection_connect(conn, conn->address, conn->addr, conn->port)) {
  70. case -1:
  71. router_mark_as_down(conn->nickname); /* don't try him again */
  72. connection_free(conn);
  73. return;
  74. case 1:
  75. conn->state = DIR_CONN_STATE_CLIENT_SENDING; /* start flushing conn */
  76. /* fall through */
  77. case 0:
  78. /* queue the command on the outbuf */
  79. directory_send_command(conn, purpose, payload, payload_len);
  80. connection_watch_events(conn, POLLIN | POLLOUT | POLLERR);
  81. /* writable indicates finish, readable indicates broken link,
  82. error indicates broken link in windowsland. */
  83. }
  84. } else { /* we want to connect via tor */
  85. /* make an AP connection
  86. * populate it and add it at the right state
  87. * socketpair and hook up both sides
  88. */
  89. conn->s = connection_ap_make_bridge(conn->address, conn->port);
  90. if(conn->s < 0) {
  91. log_fn(LOG_WARN,"Making AP bridge to dirserver failed.");
  92. connection_mark_for_close(conn, 0);
  93. return;
  94. }
  95. conn->state = DIR_CONN_STATE_CLIENT_SENDING;
  96. connection_add(conn);
  97. /* queue the command on the outbuf */
  98. directory_send_command(conn, purpose, payload, payload_len);
  99. connection_watch_events(conn, POLLIN | POLLOUT | POLLERR);
  100. }
  101. }
  102. /** Queue an appropriate HTTP command on conn->outbuf. The args
  103. * 'purpose', 'payload', and 'payload_len' are as in
  104. * directory_initiate_command.
  105. */
  106. static void directory_send_command(connection_t *conn, int purpose,
  107. const char *payload, int payload_len) {
  108. char fetchstring[] = "GET / HTTP/1.0\r\n\r\n";
  109. char tmp[8192];
  110. tor_assert(conn && conn->type == CONN_TYPE_DIR);
  111. switch(purpose) {
  112. case DIR_PURPOSE_FETCH_DIR:
  113. tor_assert(payload == NULL);
  114. connection_write_to_buf(fetchstring, strlen(fetchstring), conn);
  115. break;
  116. case DIR_PURPOSE_UPLOAD_DIR:
  117. tor_assert(payload);
  118. snprintf(tmp, sizeof(tmp), "POST / HTTP/1.0\r\nContent-Length: %d\r\n\r\n",
  119. payload_len);
  120. connection_write_to_buf(tmp, strlen(tmp), conn);
  121. connection_write_to_buf(payload, payload_len, conn);
  122. break;
  123. case DIR_PURPOSE_FETCH_RENDDESC:
  124. tor_assert(payload);
  125. /* this must be true or we wouldn't be doing the lookup */
  126. tor_assert(payload_len <= REND_SERVICE_ID_LEN);
  127. /* This breaks the function abstraction. */
  128. memcpy(conn->rend_query, payload, payload_len);
  129. conn->rend_query[payload_len] = 0;
  130. snprintf(tmp, sizeof(tmp), "GET %s%s HTTP/1.0\r\n\r\n", rend_fetch_url, payload);
  131. connection_write_to_buf(tmp, strlen(tmp), conn);
  132. break;
  133. case DIR_PURPOSE_UPLOAD_RENDDESC:
  134. tor_assert(payload);
  135. snprintf(tmp, sizeof(tmp),
  136. "POST %s HTTP/1.0\r\nContent-Length: %d\r\n\r\n", rend_publish_string, payload_len);
  137. connection_write_to_buf(tmp, strlen(tmp), conn);
  138. /* could include nuls, need to write it separately */
  139. connection_write_to_buf(payload, payload_len, conn);
  140. break;
  141. }
  142. }
  143. /** Parse an HTTP request string 'headers' of the form "%s %s HTTP/1..."
  144. * If it's well-formed, point *url to the second %s,
  145. * null-terminate it (this modifies headers!) and return 0.
  146. * Otherwise, return -1.
  147. */
  148. int parse_http_url(char *headers, char **url) {
  149. char *s, *tmp;
  150. s = (char *)eat_whitespace_no_nl(headers);
  151. if (!*s) return -1;
  152. s = (char *)find_whitespace(s); /* get past GET/POST */
  153. if (!*s) return -1;
  154. s = (char *)eat_whitespace_no_nl(s);
  155. if (!*s) return -1;
  156. tmp = s; /* this is it, assuming it's valid */
  157. s = (char *)find_whitespace(s);
  158. if (!*s) return -1;
  159. *s = 0;
  160. *url = tmp;
  161. return 0;
  162. }
  163. /** Parse an HTTP response string 'headers' of the form "HTTP/1.%d %d%s\r\n...".
  164. * If it's well-formed, assign *code, point *message to the first
  165. * non-space character after code if there is one and message is non-NULL
  166. * (else leave it alone), and return 0.
  167. * Otherwise, return -1.
  168. */
  169. int parse_http_response(char *headers, int *code, char **message) {
  170. int n1, n2;
  171. tor_assert(headers && code);
  172. while(isspace((int)*headers)) headers++; /* tolerate leading whitespace */
  173. if(sscanf(headers, "HTTP/1.%d %d", &n1, &n2) < 2 ||
  174. (n1 != 0 && n1 != 1) ||
  175. (n2 < 100 || n2 >= 600)) {
  176. log_fn(LOG_WARN,"Failed to parse header '%s'",headers);
  177. return -1;
  178. }
  179. *code = n2;
  180. if(message) {
  181. /* XXX should set *message correctly */
  182. }
  183. return 0;
  184. }
  185. /** Read handler for directory connections. (That's connections *to*
  186. * directory servers and connections *at* directory servers.)
  187. */
  188. int connection_dir_process_inbuf(connection_t *conn) {
  189. char *body;
  190. char *headers;
  191. int body_len=0;
  192. int status_code;
  193. tor_assert(conn && conn->type == CONN_TYPE_DIR);
  194. /* Directory clients write, then read data until they receive EOF;
  195. * directory servers read data until they get an HTTP command, then
  196. * write their response (when it's finished flushing, they mark for
  197. * close).
  198. */
  199. if(conn->inbuf_reached_eof) {
  200. if(conn->state != DIR_CONN_STATE_CLIENT_READING) {
  201. log_fn(LOG_INFO,"conn reached eof, not reading. Closing.");
  202. connection_close_immediate(conn); /* it was an error; give up on flushing */
  203. connection_mark_for_close(conn,0);
  204. return -1;
  205. }
  206. switch(fetch_from_buf_http(conn->inbuf,
  207. &headers, MAX_HEADERS_SIZE,
  208. &body, &body_len, MAX_DIR_SIZE)) {
  209. case -1: /* overflow */
  210. log_fn(LOG_WARN,"'fetch' response too large. Failing.");
  211. connection_mark_for_close(conn,0);
  212. return -1;
  213. case 0:
  214. log_fn(LOG_INFO,"'fetch' response not all here, but we're at eof. Closing.");
  215. connection_mark_for_close(conn,0);
  216. return -1;
  217. /* case 1, fall through */
  218. }
  219. if(parse_http_response(headers, &status_code, NULL) < 0) {
  220. log_fn(LOG_WARN,"Unparseable headers. Closing.");
  221. free(body); free(headers);
  222. connection_mark_for_close(conn,0);
  223. return -1;
  224. }
  225. if(conn->purpose == DIR_PURPOSE_FETCH_DIR) {
  226. /* fetch/process the directory to learn about new routers. */
  227. log_fn(LOG_INFO,"Received directory (size %d):\n%s", body_len, body);
  228. if(status_code == 503 || body_len == 0) {
  229. log_fn(LOG_INFO,"Empty directory. Ignoring.");
  230. free(body); free(headers);
  231. connection_mark_for_close(conn,0);
  232. return 0;
  233. }
  234. if(status_code != 200) {
  235. log_fn(LOG_WARN,"Received http status code %d from dirserver. Failing.",
  236. status_code);
  237. free(body); free(headers);
  238. connection_mark_for_close(conn,0);
  239. return -1;
  240. }
  241. if(router_set_routerlist_from_directory(body, conn->identity_pkey) < 0){
  242. log_fn(LOG_INFO,"...but parsing failed. Ignoring.");
  243. } else {
  244. log_fn(LOG_INFO,"updated routers.");
  245. }
  246. directory_has_arrived(); /* do things we've been waiting to do */
  247. }
  248. if(conn->purpose == DIR_PURPOSE_UPLOAD_DIR) {
  249. switch(status_code) {
  250. case 200:
  251. log_fn(LOG_INFO,"eof (status 200) after uploading server descriptor: finished.");
  252. break;
  253. case 400:
  254. log_fn(LOG_WARN,"http status 400 (bad request) response from dirserver. Malformed server descriptor?");
  255. break;
  256. case 403:
  257. 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.");
  258. break;
  259. default:
  260. log_fn(LOG_WARN,"http status %d response unrecognized.", status_code);
  261. break;
  262. }
  263. }
  264. if(conn->purpose == DIR_PURPOSE_FETCH_RENDDESC) {
  265. log_fn(LOG_INFO,"Received rendezvous descriptor (size %d, status code %d)",
  266. body_len, status_code);
  267. switch(status_code) {
  268. case 200:
  269. if(rend_cache_store(body, body_len) < 0) {
  270. log_fn(LOG_WARN,"Failed to store rendezvous descriptor.");
  271. /* alice's ap_stream will notice when connection_mark_for_close
  272. * cleans it up */
  273. } else {
  274. /* success. notify pending connections about this. */
  275. rend_client_desc_fetched(conn->rend_query, 1);
  276. conn->purpose = DIR_PURPOSE_HAS_FETCHED_RENDDESC;
  277. }
  278. break;
  279. case 404:
  280. /* not there. pending connections will be notified when
  281. * connection_mark_for_close cleans it up. */
  282. break;
  283. case 400:
  284. log_fn(LOG_WARN,"http status 400 (bad request). Dirserver didn't like our rendezvous query?");
  285. break;
  286. }
  287. }
  288. if(conn->purpose == DIR_PURPOSE_UPLOAD_RENDDESC) {
  289. switch(status_code) {
  290. case 200:
  291. log_fn(LOG_INFO,"eof (status 200) after uploading rendezvous descriptor: finished.");
  292. break;
  293. case 400:
  294. log_fn(LOG_WARN,"http status 400 (bad request) response from dirserver. Malformed rendezvous descriptor?");
  295. break;
  296. default:
  297. log_fn(LOG_WARN,"http status %d response unrecognized.", status_code);
  298. break;
  299. }
  300. }
  301. free(body); free(headers);
  302. connection_mark_for_close(conn,0);
  303. return 0;
  304. } /* endif 'reached eof' */
  305. /* If we're on the dirserver side, look for a command. */
  306. if(conn->state == DIR_CONN_STATE_SERVER_COMMAND_WAIT) {
  307. if (directory_handle_command(conn) < 0) {
  308. connection_mark_for_close(conn,0);
  309. return -1;
  310. }
  311. return 0;
  312. }
  313. /* XXX for READ states, might want to make sure inbuf isn't too big */
  314. log_fn(LOG_DEBUG,"Got data, not eof. Leaving on inbuf.");
  315. return 0;
  316. }
  317. static char answer200[] = "HTTP/1.0 200 OK\r\n\r\n";
  318. static char answer400[] = "HTTP/1.0 400 Bad request\r\n\r\n";
  319. static char answer403[] = "HTTP/1.0 403 Unapproved server\r\n\r\n";
  320. static char answer404[] = "HTTP/1.0 404 Not found\r\n\r\n";
  321. static char answer503[] = "HTTP/1.0 503 Directory unavailable\r\n\r\n";
  322. /** Helper function: called when a dirserver gets a complete HTTP GET
  323. * request. Look for a request for a directory or for a rendezvous
  324. * service descriptor. On finding one, write a response into
  325. * conn->outbuf. If the request is unrecognized, send a 404.
  326. * Always return 0. */
  327. static int directory_handle_command_get(connection_t *conn,
  328. char *headers, char *body,
  329. int body_len) {
  330. size_t dlen;
  331. const char *cp;
  332. char *url;
  333. char tmp[8192];
  334. log_fn(LOG_DEBUG,"Received GET command.");
  335. conn->state = DIR_CONN_STATE_SERVER_WRITING;
  336. if (parse_http_url(headers, &url) < 0) {
  337. connection_write_to_buf(answer400, strlen(answer400), conn);
  338. return 0;
  339. }
  340. if(!strcmp(url,"/")) { /* directory fetch */
  341. dlen = dirserv_get_directory(&cp);
  342. if(dlen == 0) {
  343. log_fn(LOG_WARN,"My directory is empty. Closing.");
  344. connection_write_to_buf(answer503, strlen(answer503), conn);
  345. return 0;
  346. }
  347. log_fn(LOG_DEBUG,"Dumping directory to client.");
  348. snprintf(tmp, sizeof(tmp), "HTTP/1.0 200 OK\r\nContent-Length: %d\r\nContent-Type: text/plain\r\n\r\n",
  349. (int)dlen);
  350. connection_write_to_buf(tmp, strlen(tmp), conn);
  351. connection_write_to_buf(cp, strlen(cp), conn);
  352. return 0;
  353. }
  354. if(!strncmp(url,rend_fetch_url,strlen(rend_fetch_url))) {
  355. /* rendezvous descriptor fetch */
  356. const char *descp;
  357. int desc_len;
  358. switch(rend_cache_lookup_desc(url+strlen(rend_fetch_url), &descp, &desc_len)) {
  359. case 1: /* valid */
  360. snprintf(tmp, sizeof(tmp), "HTTP/1.0 200 OK\r\nContent-Length: %d\r\nContent-Type: application/octet-stream\r\n\r\n",
  361. desc_len); /* can't include descp here, because it's got nuls */
  362. connection_write_to_buf(tmp, strlen(tmp), conn);
  363. connection_write_to_buf(descp, desc_len, conn);
  364. break;
  365. case 0: /* well-formed but not present */
  366. connection_write_to_buf(answer404, strlen(answer404), conn);
  367. break;
  368. case -1: /* not well-formed */
  369. connection_write_to_buf(answer400, strlen(answer400), conn);
  370. break;
  371. }
  372. return 0;
  373. }
  374. /* we didn't recognize the url */
  375. connection_write_to_buf(answer404, strlen(answer404), conn);
  376. return 0;
  377. }
  378. /** Helper function: called when a dirserver gets a complete HTTP POST
  379. * request. Look for an uploaded server descriptor or rendezvous
  380. * service descriptor. On finding one, process it and write a
  381. * response into conn->outbuf. If the request is unrecognized, send a
  382. * 404. Always return 0. */
  383. static int directory_handle_command_post(connection_t *conn,
  384. char *headers, char *body,
  385. int body_len) {
  386. const char *cp;
  387. char *url;
  388. log_fn(LOG_DEBUG,"Received POST command.");
  389. conn->state = DIR_CONN_STATE_SERVER_WRITING;
  390. if (parse_http_url(headers, &url) < 0) {
  391. connection_write_to_buf(answer400, strlen(answer400), conn);
  392. return 0;
  393. }
  394. log_fn(LOG_INFO,"url '%s' posted to us.", url);
  395. if(!strcmp(url,"/")) { /* server descriptor post */
  396. cp = body;
  397. switch(dirserv_add_descriptor(&cp)) {
  398. case -1:
  399. /* malformed descriptor, or something wrong */
  400. connection_write_to_buf(answer400, strlen(answer400), conn);
  401. break;
  402. case 0:
  403. /* descriptor was well-formed but server has not been approved */
  404. connection_write_to_buf(answer403, strlen(answer403), conn);
  405. break;
  406. case 1:
  407. dirserv_get_directory(&cp); /* rebuild and write to disk */
  408. connection_write_to_buf(answer200, strlen(answer200), conn);
  409. break;
  410. }
  411. return 0;
  412. }
  413. if(!strncmp(url,rend_publish_string,strlen(rend_publish_string))) {
  414. /* rendezvous descriptor post */
  415. if(rend_cache_store(body, body_len) < 0)
  416. connection_write_to_buf(answer400, strlen(answer400), conn);
  417. else
  418. connection_write_to_buf(answer200, strlen(answer200), conn);
  419. return 0;
  420. }
  421. /* we didn't recognize the url */
  422. connection_write_to_buf(answer404, strlen(answer404), conn);
  423. return 0;
  424. }
  425. /** Called when a dirserver receives data on a directory connection;
  426. * looks for an HTTP request. If the request is complete, remove it
  427. * from the inbuf, try to process it; otherwise, leave it on the
  428. * buffer. Return a 0 on success, or -1 on error.
  429. */
  430. static int directory_handle_command(connection_t *conn) {
  431. char *headers=NULL, *body=NULL;
  432. int body_len=0;
  433. int r;
  434. tor_assert(conn && conn->type == CONN_TYPE_DIR);
  435. switch(fetch_from_buf_http(conn->inbuf,
  436. &headers, MAX_HEADERS_SIZE,
  437. &body, &body_len, MAX_BODY_SIZE)) {
  438. case -1: /* overflow */
  439. log_fn(LOG_WARN,"input too large. Failing.");
  440. return -1;
  441. case 0:
  442. log_fn(LOG_DEBUG,"command not all here yet.");
  443. return 0;
  444. /* case 1, fall through */
  445. }
  446. log_fn(LOG_DEBUG,"headers '%s', body '%s'.", headers, body);
  447. if(!strncasecmp(headers,"GET",3))
  448. r = directory_handle_command_get(conn, headers, body, body_len);
  449. else if (!strncasecmp(headers,"POST",4))
  450. r = directory_handle_command_post(conn, headers, body, body_len);
  451. else {
  452. log_fn(LOG_WARN,"Got headers '%s' with unknown command. Closing.", headers);
  453. r = -1;
  454. }
  455. tor_free(headers); tor_free(body);
  456. return r;
  457. }
  458. /** Write handler for directory connections; called when all data has
  459. * been flushed. Handle a completed connection: close the connection
  460. * or wait for a response as appropriate.
  461. */
  462. int connection_dir_finished_flushing(connection_t *conn) {
  463. int e, len=sizeof(e);
  464. tor_assert(conn && conn->type == CONN_TYPE_DIR);
  465. switch(conn->state) {
  466. case DIR_CONN_STATE_CONNECTING:
  467. if (getsockopt(conn->s, SOL_SOCKET, SO_ERROR, (void*)&e, &len) < 0) { /* not yet */
  468. if(!ERRNO_IS_CONN_EINPROGRESS(tor_socket_errno(conn->s))) {
  469. log_fn(LOG_DEBUG,"in-progress connect failed. Removing.");
  470. router_mark_as_down(conn->nickname); /* don't try him again */
  471. connection_mark_for_close(conn,0);
  472. return -1;
  473. } else {
  474. return 0; /* no change, see if next time is better */
  475. }
  476. }
  477. /* the connect has finished. */
  478. log_fn(LOG_INFO,"Dir connection to router %s:%u established.",
  479. conn->address,conn->port);
  480. conn->state = DIR_CONN_STATE_CLIENT_SENDING; /* start flushing conn */
  481. return 0;
  482. case DIR_CONN_STATE_CLIENT_SENDING:
  483. log_fn(LOG_DEBUG,"client finished sending command.");
  484. conn->state = DIR_CONN_STATE_CLIENT_READING;
  485. connection_stop_writing(conn);
  486. return 0;
  487. case DIR_CONN_STATE_SERVER_WRITING:
  488. log_fn(LOG_INFO,"Finished writing server response. Closing.");
  489. connection_mark_for_close(conn,0);
  490. return 0;
  491. default:
  492. log_fn(LOG_WARN,"BUG: called in unexpected state %d.", conn->state);
  493. return -1;
  494. }
  495. return 0;
  496. }
  497. /*
  498. Local Variables:
  499. mode:c
  500. indent-tabs-mode:nil
  501. c-basic-offset:2
  502. End:
  503. */