directory.c 33 KB

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