directory.c 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209
  1. /* Copyright 2001-2004 Roger Dingledine.
  2. * Copyright 2004-2005 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 Code to send and fetch directories and router
  10. * descriptors via HTTP. Directories use dirserv.c to generate the
  11. * results; clients use routers.c to parse them.
  12. **/
  13. /* In-points to directory.c:
  14. *
  15. * - directory_post_to_dirservers(), called from
  16. * router_upload_dir_desc_to_dirservers() in router.c
  17. * upload_service_descriptor() in rendservice.c
  18. * - directory_get_from_dirserver(), called from
  19. * rend_client_refetch_renddesc() in rendclient.c
  20. * run_scheduled_events() in main.c
  21. * do_hup() in main.c
  22. * - connection_dir_process_inbuf(), called from
  23. * connection_process_inbuf() in connection.c
  24. * - connection_dir_finished_flushing(), called from
  25. * connection_finished_flushing() in connection.c
  26. * - connection_dir_finished_connecting(), called from
  27. * connection_finished_connecting() in connection.c
  28. */
  29. static void
  30. directory_initiate_command_trusted_dir(trusted_dir_server_t *dirserv,
  31. uint8_t purpose, int private_connection,
  32. const char *resource,
  33. const char *payload, size_t payload_len);
  34. static void
  35. directory_initiate_command(const char *address, uint32_t addr, uint16_t port,
  36. const char *platform,
  37. const char *digest, uint8_t purpose,
  38. int private_connection, const char *resource,
  39. const char *payload, size_t payload_len);
  40. static void
  41. directory_send_command(connection_t *conn, const char *platform,
  42. int purpose, const char *resource,
  43. const char *payload, size_t payload_len);
  44. static int directory_handle_command(connection_t *conn);
  45. static int body_is_plausible(const char *body, size_t body_len, int purpose);
  46. static int purpose_is_private(uint8_t purpose);
  47. /********* START VARIABLES **********/
  48. static addr_policy_t *dir_policy = NULL;
  49. #if 0 /* commented out for now, since for now what clients send is
  50. different from what servers want to receive */
  51. /** URL for publishing rendezvous descriptors. */
  52. char rend_publish_string[] = "/tor/rendezvous/publish";
  53. /** Prefix for downloading rendezvous descriptors. */
  54. char rend_fetch_url[] = "/tor/rendezvous/";
  55. #endif
  56. #define ALLOW_DIRECTORY_TIME_SKEW 30*60 /* 30 minutes */
  57. /********* END VARIABLES ************/
  58. /** Parse get_options()->DirPolicy, and put the processed version in
  59. * &dir_policy. Ignore port specifiers.
  60. */
  61. void
  62. parse_dir_policy(void)
  63. {
  64. addr_policy_t *n;
  65. if (dir_policy) {
  66. addr_policy_free(dir_policy);
  67. dir_policy = NULL;
  68. }
  69. config_parse_addr_policy(get_options()->DirPolicy, &dir_policy);
  70. /* ports aren't used. */
  71. for (n=dir_policy; n; n = n->next) {
  72. n->prt_min = 1;
  73. n->prt_max = 65535;
  74. }
  75. }
  76. /** Free storage used to hold parsed directory policy */
  77. void
  78. free_dir_policy(void)
  79. {
  80. addr_policy_free(dir_policy);
  81. dir_policy = NULL;
  82. }
  83. /** Return 1 if <b>addr</b> is permitted to connect to our dir port,
  84. * based on <b>dir_policy</b>. Else return 0.
  85. */
  86. int
  87. dir_policy_permits_address(uint32_t addr)
  88. {
  89. int a;
  90. if (!dir_policy) /* 'no dir policy' means 'accept' */
  91. return 1;
  92. a = router_compare_addr_to_addr_policy(addr, 1, dir_policy);
  93. if (a==ADDR_POLICY_REJECTED)
  94. return 0;
  95. else if (a==ADDR_POLICY_ACCEPTED)
  96. return 1;
  97. log_fn(LOG_WARN, "Bug: got unexpected 'maybe' answer from dir policy");
  98. return 0;
  99. }
  100. /** Return true iff the directory purpose 'purpose' must use an
  101. * anonymous connection to a directory. */
  102. static int
  103. purpose_is_private(uint8_t purpose)
  104. {
  105. if (purpose == DIR_PURPOSE_FETCH_DIR ||
  106. purpose == DIR_PURPOSE_UPLOAD_DIR ||
  107. purpose == DIR_PURPOSE_FETCH_RUNNING_LIST)
  108. return 0;
  109. return 1;
  110. }
  111. /** Start a connection to every known directory server, using
  112. * connection purpose 'purpose' and uploading the payload 'payload'
  113. * (length 'payload_len'). The purpose should be one of
  114. * 'DIR_PURPOSE_UPLOAD_DIR' or 'DIR_PURPOSE_UPLOAD_RENDDESC'.
  115. */
  116. void
  117. directory_post_to_dirservers(uint8_t purpose, const char *payload,
  118. size_t payload_len)
  119. {
  120. smartlist_t *dirservers;
  121. router_get_trusted_dir_servers(&dirservers);
  122. tor_assert(dirservers);
  123. /* This tries dirservers which we believe to be down, but ultimately, that's
  124. * harmless, and we may as well err on the side of getting things uploaded.
  125. */
  126. SMARTLIST_FOREACH(dirservers, trusted_dir_server_t *, ds,
  127. {
  128. /* Pay attention to fascistfirewall when we're uploading a
  129. * router descriptor, but not when uploading a service
  130. * descriptor -- those use Tor. */
  131. if (get_options()->FascistFirewall && purpose == DIR_PURPOSE_UPLOAD_DIR &&
  132. !get_options()->HttpProxy) {
  133. if (!smartlist_string_num_isin(get_options()->FirewallPorts, ds->dir_port))
  134. continue;
  135. }
  136. directory_initiate_command_trusted_dir(ds, purpose, purpose_is_private(purpose),
  137. NULL, payload, payload_len);
  138. });
  139. }
  140. /** Start a connection to a random running directory server, using
  141. * connection purpose 'purpose' requesting 'resource'. The purpose
  142. * should be one of 'DIR_PURPOSE_FETCH_DIR',
  143. * 'DIR_PURPOSE_FETCH_RENDDESC', 'DIR_PURPOSE_FETCH_RUNNING_LIST.'
  144. * If <b>retry_if_no_servers</b>, then if all the possible servers seem
  145. * down, mark them up and try again.
  146. */
  147. void
  148. directory_get_from_dirserver(uint8_t purpose, const char *resource,
  149. int retry_if_no_servers)
  150. {
  151. routerinfo_t *r = NULL;
  152. trusted_dir_server_t *ds = NULL;
  153. int fascistfirewall = get_options()->FascistFirewall;
  154. int directconn = purpose == DIR_PURPOSE_FETCH_DIR ||
  155. purpose == DIR_PURPOSE_FETCH_RUNNING_LIST;
  156. int fetch_fresh_first = advertised_server_mode();
  157. int priv = purpose_is_private(purpose);
  158. if (directconn) {
  159. if (fetch_fresh_first) {
  160. /* only ask authdirservers, and don't ask myself */
  161. ds = router_pick_trusteddirserver(1, fascistfirewall,
  162. retry_if_no_servers);
  163. }
  164. if (!ds) {
  165. /* anybody with a non-zero dirport will do */
  166. r = router_pick_directory_server(1, fascistfirewall,
  167. purpose==DIR_PURPOSE_FETCH_RUNNING_LIST,
  168. retry_if_no_servers);
  169. if (!r) {
  170. log_fn(LOG_INFO, "No router found for %s; falling back to dirserver list",
  171. purpose == DIR_PURPOSE_FETCH_RUNNING_LIST
  172. ? "status list" : "directory");
  173. ds = router_pick_trusteddirserver(1, fascistfirewall,
  174. retry_if_no_servers);
  175. }
  176. }
  177. } else { // (purpose == DIR_PURPOSE_FETCH_RENDDESC)
  178. /* only ask authdirservers, any of them will do */
  179. /* Never use fascistfirewall; we're going via Tor. */
  180. ds = router_pick_trusteddirserver(0, 0, retry_if_no_servers);
  181. }
  182. if (r)
  183. directory_initiate_command_router(r, purpose, priv, resource, NULL, 0);
  184. else if (ds)
  185. directory_initiate_command_trusted_dir(ds, purpose, priv, resource, NULL, 0);
  186. else {
  187. log_fn(LOG_NOTICE,"No running dirservers known. Not trying. (purpose %d)",
  188. purpose);
  189. if (directconn) {
  190. /* remember we tried them all and failed. */
  191. directory_all_unreachable(time(NULL));
  192. }
  193. }
  194. }
  195. /** Launch a new connection to the directory server <b>router</b> to upload or
  196. * download a service or rendezvous descriptor. <b>purpose</b> determines what
  197. * kind of directory connection we're launching, and must be one of
  198. * DIR_PURPOSE_{FETCH|UPLOAD}_{DIR|RENDDESC}.
  199. *
  200. * When uploading, <b>payload</b> and <b>payload_len</b> determine the content
  201. * of the HTTP post. Otherwise, <b>payload</b> should be NULL.
  202. *
  203. * When fetching a rendezvous descriptor, <b>resource</b> is the service ID we
  204. * want to fetch.
  205. */
  206. void
  207. directory_initiate_command_router(routerinfo_t *router, uint8_t purpose,
  208. int private_connection, const char *resource,
  209. const char *payload, size_t payload_len)
  210. {
  211. directory_initiate_command(router->address, router->addr, router->dir_port,
  212. router->platform, router->identity_digest,
  213. purpose, private_connection, resource,
  214. payload, payload_len);
  215. }
  216. /** As directory_initiate_command_router, but send the command to a trusted
  217. * directory server <b>dirserv</b>. **/
  218. static void
  219. directory_initiate_command_trusted_dir(trusted_dir_server_t *dirserv,
  220. uint8_t purpose, int private_connection,
  221. const char *resource,
  222. const char *payload, size_t payload_len)
  223. {
  224. directory_initiate_command(dirserv->address, dirserv->addr,dirserv->dir_port,
  225. NULL, dirserv->digest, purpose, private_connection, resource,
  226. payload, payload_len);
  227. }
  228. /** Called when we are unable to complete our connection to a
  229. * directory server: Mark the router as down and try again if possible.
  230. */
  231. void
  232. connection_dir_connect_failed(connection_t *conn)
  233. {
  234. router_mark_as_down(conn->identity_digest); /* don't try him again */
  235. if (conn->purpose == DIR_PURPOSE_FETCH_DIR ||
  236. conn->purpose == DIR_PURPOSE_FETCH_RUNNING_LIST) {
  237. log_fn(LOG_INFO, "Giving up on directory server at '%s'; retrying",
  238. conn->address);
  239. directory_get_from_dirserver(conn->purpose, NULL,
  240. 0 /* don't retry_if_no_servers */);
  241. }
  242. }
  243. /** Helper for directory_initiate_command_(router|trusted_dir): send the
  244. * command to a server whose address is <b>address</b>, whose IP is
  245. * <b>addr</b>, whose directory port is <b>dir_port</b>, whose tor version is
  246. * <b>platform</b>, and whose identity key digest is <b>digest</b>. The
  247. * <b>platform</b> argument is optional; the others are required. */
  248. static void
  249. directory_initiate_command(const char *address, uint32_t addr,
  250. uint16_t dir_port, const char *platform,
  251. const char *digest, uint8_t purpose,
  252. int private_connection, const char *resource,
  253. const char *payload, size_t payload_len)
  254. {
  255. connection_t *conn;
  256. tor_assert(address);
  257. tor_assert(addr);
  258. tor_assert(dir_port);
  259. tor_assert(digest);
  260. switch (purpose) {
  261. case DIR_PURPOSE_FETCH_DIR:
  262. log_fn(LOG_DEBUG,"initiating directory fetch");
  263. break;
  264. case DIR_PURPOSE_FETCH_RENDDESC:
  265. log_fn(LOG_DEBUG,"initiating hidden-service descriptor fetch");
  266. break;
  267. case DIR_PURPOSE_UPLOAD_DIR:
  268. log_fn(LOG_DEBUG,"initiating server descriptor upload");
  269. break;
  270. case DIR_PURPOSE_UPLOAD_RENDDESC:
  271. log_fn(LOG_DEBUG,"initiating hidden-service descriptor upload");
  272. break;
  273. case DIR_PURPOSE_FETCH_RUNNING_LIST:
  274. log_fn(LOG_DEBUG,"initiating running-routers fetch");
  275. break;
  276. default:
  277. log_fn(LOG_ERR, "Unrecognized directory connection purpose.");
  278. tor_assert(0);
  279. }
  280. conn = connection_new(CONN_TYPE_DIR);
  281. /* set up conn so it's got all the data we need to remember */
  282. conn->addr = addr;
  283. conn->port = dir_port;
  284. conn->address = tor_strdup(address);
  285. memcpy(conn->identity_digest, digest, DIGEST_LEN);
  286. conn->purpose = purpose;
  287. /* give it an initial state */
  288. conn->state = DIR_CONN_STATE_CONNECTING;
  289. if (!private_connection) {
  290. /* then we want to connect directly */
  291. if (get_options()->HttpProxy) {
  292. addr = get_options()->HttpProxyAddr;
  293. dir_port = get_options()->HttpProxyPort;
  294. }
  295. switch (connection_connect(conn, conn->address, addr, dir_port)) {
  296. case -1:
  297. connection_dir_connect_failed(conn);
  298. connection_free(conn);
  299. return;
  300. case 1:
  301. conn->state = DIR_CONN_STATE_CLIENT_SENDING; /* start flushing conn */
  302. /* fall through */
  303. case 0:
  304. /* queue the command on the outbuf */
  305. directory_send_command(conn, platform, purpose, resource,
  306. payload, payload_len);
  307. connection_watch_events(conn, EV_READ | EV_WRITE);
  308. /* writable indicates finish, readable indicates broken link,
  309. error indicates broken link in windowsland. */
  310. }
  311. } else { /* we want to connect via tor */
  312. /* make an AP connection
  313. * populate it and add it at the right state
  314. * socketpair and hook up both sides
  315. */
  316. conn->s = connection_ap_make_bridge(conn->address, conn->port);
  317. if (conn->s < 0) {
  318. log_fn(LOG_WARN,"Making AP bridge to dirserver failed.");
  319. connection_mark_for_close(conn);
  320. return;
  321. }
  322. conn->state = DIR_CONN_STATE_CLIENT_SENDING;
  323. connection_add(conn);
  324. /* queue the command on the outbuf */
  325. directory_send_command(conn, platform, purpose, resource,
  326. payload, payload_len);
  327. connection_watch_events(conn, EV_READ | EV_WRITE);
  328. }
  329. }
  330. /** Queue an appropriate HTTP command on conn-\>outbuf. The other args
  331. * are as in directory_initiate_command.
  332. */
  333. static void
  334. directory_send_command(connection_t *conn, const char *platform,
  335. int purpose, const char *resource,
  336. const char *payload, size_t payload_len)
  337. {
  338. char tmp[8192];
  339. char proxystring[256];
  340. char proxyauthstring[256];
  341. char hoststring[128];
  342. char url[128];
  343. const char *httpcommand = NULL;
  344. tor_assert(conn);
  345. tor_assert(conn->type == CONN_TYPE_DIR);
  346. /* come up with a string for which Host: we want */
  347. if (conn->port == 80) {
  348. strlcpy(hoststring, conn->address, sizeof(hoststring));
  349. } else {
  350. tor_snprintf(hoststring, sizeof(hoststring),"%s:%d",conn->address, conn->port);
  351. }
  352. /* come up with some proxy lines, if we're using one. */
  353. if (get_options()->HttpProxy) {
  354. char *base64_authenticator=NULL;
  355. const char *authenticator = get_options()->HttpProxyAuthenticator;
  356. tor_snprintf(proxystring, sizeof(proxystring),"http://%s", hoststring);
  357. if (authenticator) {
  358. base64_authenticator = alloc_http_authenticator(authenticator);
  359. if (!base64_authenticator)
  360. log_fn(LOG_WARN, "Encoding http authenticator failed");
  361. }
  362. if (base64_authenticator) {
  363. tor_snprintf(proxyauthstring, sizeof(proxyauthstring),
  364. "\r\nProxy-Authorization: Basic %s",
  365. base64_authenticator);
  366. tor_free(base64_authenticator);
  367. } else {
  368. proxyauthstring[0] = 0;
  369. }
  370. } else {
  371. proxystring[0] = 0;
  372. proxyauthstring[0] = 0;
  373. }
  374. switch (purpose) {
  375. case DIR_PURPOSE_FETCH_DIR:
  376. tor_assert(!resource);
  377. tor_assert(!payload);
  378. log_fn(LOG_DEBUG, "Asking for compressed directory from server running %s",
  379. platform?platform:"<unknown version>");
  380. httpcommand = "GET";
  381. strlcpy(url, "/tor/dir.z", sizeof(url));
  382. break;
  383. case DIR_PURPOSE_FETCH_RUNNING_LIST:
  384. tor_assert(!resource);
  385. tor_assert(!payload);
  386. httpcommand = "GET";
  387. strlcpy(url, "/tor/running-routers", sizeof(url));
  388. break;
  389. case DIR_PURPOSE_UPLOAD_DIR:
  390. tor_assert(!resource);
  391. tor_assert(payload);
  392. httpcommand = "POST";
  393. strlcpy(url, "/tor/", sizeof(url));
  394. break;
  395. case DIR_PURPOSE_FETCH_RENDDESC:
  396. tor_assert(resource);
  397. tor_assert(!payload);
  398. /* this must be true or we wouldn't be doing the lookup */
  399. tor_assert(strlen(resource) <= REND_SERVICE_ID_LEN);
  400. /* This breaks the function abstraction. */
  401. strlcpy(conn->rend_query, resource, sizeof(conn->rend_query));
  402. httpcommand = "GET";
  403. tor_snprintf(url, sizeof(url), "/tor/rendezvous/%s", resource);
  404. break;
  405. case DIR_PURPOSE_UPLOAD_RENDDESC:
  406. tor_assert(!resource);
  407. tor_assert(payload);
  408. httpcommand = "POST";
  409. tor_snprintf(url, sizeof(url), "/tor/rendezvous/publish");
  410. break;
  411. }
  412. tor_snprintf(tmp, sizeof(tmp), "%s %s%s HTTP/1.0\r\nContent-Length: %lu\r\nHost: %s%s\r\n\r\n",
  413. httpcommand,
  414. proxystring,
  415. url,
  416. payload ? (unsigned long)payload_len : 0,
  417. hoststring,
  418. proxyauthstring);
  419. connection_write_to_buf(tmp, strlen(tmp), conn);
  420. if (payload) {
  421. /* then send the payload afterwards too */
  422. connection_write_to_buf(payload, payload_len, conn);
  423. }
  424. }
  425. /** Parse an HTTP request string <b>headers</b> of the form
  426. * \verbatim
  427. * "\%s [http[s]://]\%s HTTP/1..."
  428. * \endverbatim
  429. * If it's well-formed, strdup the second \%s into *<b>url</b>, and
  430. * null-terminate it. If the url doesn't start with "/tor/", rewrite it
  431. * so it does. Return 0.
  432. * Otherwise, return -1.
  433. */
  434. static int
  435. parse_http_url(char *headers, char **url)
  436. {
  437. char *s, *start, *tmp;
  438. s = (char *)eat_whitespace_no_nl(headers);
  439. if (!*s) return -1;
  440. s = (char *)find_whitespace(s); /* get past GET/POST */
  441. if (!*s) return -1;
  442. s = (char *)eat_whitespace_no_nl(s);
  443. if (!*s) return -1;
  444. start = s; /* this is it, assuming it's valid */
  445. s = (char *)find_whitespace(start);
  446. if (!*s) return -1;
  447. /* tolerate the http[s] proxy style of putting the hostname in the url */
  448. if (s-start >= 4 && !strcmpstart(start,"http")) {
  449. tmp = start + 4;
  450. if (*tmp == 's')
  451. tmp++;
  452. if (s-tmp >= 3 && !strcmpstart(tmp,"://")) {
  453. tmp = strchr(tmp+3, '/');
  454. if (tmp && tmp < s) {
  455. log_fn(LOG_DEBUG,"Skipping over 'http[s]://hostname' string");
  456. start = tmp;
  457. }
  458. }
  459. }
  460. if (s-start < 5 || strcmpstart(start,"/tor/")) { /* need to rewrite it */
  461. *url = tor_malloc(s - start + 5);
  462. strlcpy(*url,"/tor", s-start+5);
  463. strlcat((*url)+4, start, s-start+1);
  464. } else {
  465. *url = tor_strndup(start, s-start);
  466. }
  467. return 0;
  468. }
  469. /** Parse an HTTP response string <b>headers</b> of the form
  470. * \verbatim
  471. * "HTTP/1.\%d \%d\%s\r\n...".
  472. * \endverbatim
  473. *
  474. * If it's well-formed, assign the status code to *<b>code</b> and
  475. * return 0. Otherwise, return -1.
  476. *
  477. * On success: If <b>date</b> is provided, set *date to the Date
  478. * header in the http headers, or 0 if no such header is found. If
  479. * <b>compression</b> is provided, set *<b>compression</b> to the
  480. * compression method given in the Content-Encoding header, or 0 if no
  481. * such header is found, or -1 if the value of the header is not
  482. * recognized. If <b>reason</b> is provided, strdup the reason string
  483. * into it.
  484. */
  485. int
  486. parse_http_response(const char *headers, int *code, time_t *date,
  487. int *compression, char **reason)
  488. {
  489. int n1, n2;
  490. char datestr[RFC1123_TIME_LEN+1];
  491. smartlist_t *parsed_headers;
  492. tor_assert(headers);
  493. tor_assert(code);
  494. while (TOR_ISSPACE(*headers)) headers++; /* tolerate leading whitespace */
  495. if (sscanf(headers, "HTTP/1.%d %d", &n1, &n2) < 2 ||
  496. (n1 != 0 && n1 != 1) ||
  497. (n2 < 100 || n2 >= 600)) {
  498. log_fn(LOG_WARN,"Failed to parse header '%s'",headers);
  499. return -1;
  500. }
  501. *code = n2;
  502. parsed_headers = smartlist_create();
  503. smartlist_split_string(parsed_headers, headers, "\n",
  504. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  505. if (reason) {
  506. smartlist_t *status_line_elements = smartlist_create();
  507. tor_assert(smartlist_len(parsed_headers));
  508. smartlist_split_string(status_line_elements,
  509. smartlist_get(parsed_headers, 0),
  510. " ", SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 3);
  511. tor_assert(smartlist_len(status_line_elements) <= 3);
  512. if (smartlist_len(status_line_elements) == 3) {
  513. *reason = smartlist_get(status_line_elements, 2);
  514. smartlist_set(status_line_elements, 2, NULL); /* Prevent free */
  515. }
  516. SMARTLIST_FOREACH(status_line_elements, char *, cp, tor_free(cp));
  517. smartlist_free(status_line_elements);
  518. }
  519. if (date) {
  520. *date = 0;
  521. SMARTLIST_FOREACH(parsed_headers, const char *, s,
  522. if (!strcmpstart(s, "Date: ")) {
  523. strlcpy(datestr, s+6, sizeof(datestr));
  524. /* This will do nothing on failure, so we don't need to check
  525. the result. We shouldn't warn, since there are many other valid
  526. date formats besides the one we use. */
  527. parse_rfc1123_time(datestr, date);
  528. break;
  529. });
  530. }
  531. if (compression) {
  532. const char *enc = NULL;
  533. SMARTLIST_FOREACH(parsed_headers, const char *, s,
  534. if (!strcmpstart(s, "Content-Encoding: ")) {
  535. enc = s+18; break;
  536. });
  537. if (!enc || !strcmp(enc, "identity")) {
  538. *compression = 0;
  539. } else if (!strcmp(enc, "deflate") || !strcmp(enc, "x-deflate")) {
  540. *compression = ZLIB_METHOD;
  541. } else if (!strcmp(enc, "gzip") || !strcmp(enc, "x-gzip")) {
  542. *compression = GZIP_METHOD;
  543. } else {
  544. log_fn(LOG_INFO, "Unrecognized content encoding: '%s'. Trying to deal.", enc);
  545. *compression = -1;
  546. }
  547. }
  548. SMARTLIST_FOREACH(parsed_headers, char *, s, tor_free(s));
  549. smartlist_free(parsed_headers);
  550. return 0;
  551. }
  552. /** Return true iff <b>body</b> doesn't start with a plausible router or
  553. * running-list or directory opening. This is a sign of possible compression.
  554. **/
  555. static int
  556. body_is_plausible(const char *body, size_t len, int purpose)
  557. {
  558. int i;
  559. if (len == 0)
  560. return 1; /* empty bodies don't need decompression */
  561. if (len < 32)
  562. return 0;
  563. if (purpose != DIR_PURPOSE_FETCH_RENDDESC) {
  564. if (!strcmpstart(body,"router") ||
  565. !strcmpstart(body,"signed-directory") ||
  566. !strcmpstart(body,"network-status") ||
  567. !strcmpstart(body,"running-routers"))
  568. return 1;
  569. for (i=0;i<32;++i) {
  570. if (!TOR_ISPRINT(body[i]) && !TOR_ISSPACE(body[i]))
  571. return 0;
  572. }
  573. return 1;
  574. } else {
  575. return 1;
  576. }
  577. }
  578. /** We are a client, and we've finished reading the server's
  579. * response. Parse and it and act appropriately.
  580. *
  581. * Return -1 if an error has occurred, or 0 normally. The caller
  582. * will take care of marking the connection for close.
  583. */
  584. static int
  585. connection_dir_client_reached_eof(connection_t *conn)
  586. {
  587. char *body;
  588. char *headers;
  589. char *reason = NULL;
  590. size_t body_len=0;
  591. int status_code;
  592. time_t now, date_header=0;
  593. int delta;
  594. int compression;
  595. int plausible;
  596. int skewed=0;
  597. switch (fetch_from_buf_http(conn->inbuf,
  598. &headers, MAX_HEADERS_SIZE,
  599. &body, &body_len, MAX_DIR_SIZE)) {
  600. case -1: /* overflow */
  601. log_fn(LOG_WARN,"'fetch' response too large (server '%s'). Failing.", conn->address);
  602. return -1;
  603. case 0:
  604. log_fn(LOG_INFO,"'fetch' response not all here, but we're at eof. Closing.");
  605. return -1;
  606. /* case 1, fall through */
  607. }
  608. if (parse_http_response(headers, &status_code, &date_header,
  609. &compression, &reason) < 0) {
  610. log_fn(LOG_WARN,"Unparseable headers (server '%s'). Closing.", conn->address);
  611. tor_free(body); tor_free(headers);
  612. return -1;
  613. }
  614. if (!reason) reason = tor_strdup("[no reason given]");
  615. log_fn(LOG_DEBUG,
  616. "Received response from directory server '%s': %d \"%s\"",
  617. conn->address, status_code, reason);
  618. if (date_header > 0) {
  619. now = time(NULL);
  620. delta = now-date_header;
  621. if (abs(delta)>ALLOW_DIRECTORY_TIME_SKEW) {
  622. log_fn(router_digest_is_trusted_dir(conn->identity_digest) ? LOG_WARN : LOG_INFO,
  623. "Received directory with skewed time (server '%s'): we are %d minutes %s, or the directory is %d minutes %s.",
  624. conn->address,
  625. abs(delta)/60, delta>0 ? "ahead" : "behind",
  626. abs(delta)/60, delta>0 ? "behind" : "ahead");
  627. skewed = 1; /* don't check the recommended-versions line */
  628. } else {
  629. log_fn(LOG_INFO, "Time on received directory is within tolerance; we are %d seconds skewed. (That's okay.)", delta);
  630. }
  631. }
  632. plausible = body_is_plausible(body, body_len, conn->purpose);
  633. if (compression || !plausible) {
  634. char *new_body = NULL;
  635. size_t new_len = 0;
  636. int guessed = detect_compression_method(body, body_len);
  637. if (compression <= 0 || guessed != compression) {
  638. /* Tell the user if we don't believe what we're told about compression.*/
  639. const char *description1, *description2;
  640. if (compression == ZLIB_METHOD)
  641. description1 = "as deflated";
  642. else if (compression == GZIP_METHOD)
  643. description1 = "as gzipped";
  644. else if (compression == 0)
  645. description1 = "as uncompressed";
  646. else
  647. description1 = "with an unknown Content-Encoding";
  648. if (guessed == ZLIB_METHOD)
  649. description2 = "deflated";
  650. else if (guessed == GZIP_METHOD)
  651. description2 = "gzipped";
  652. else if (!plausible)
  653. description2 = "confusing binary junk";
  654. else
  655. description2 = "uncompressed";
  656. log_fn(LOG_INFO, "HTTP body from server '%s' was labeled %s, "
  657. "but it seems to be %s.%s",
  658. conn->address, description1, description2,
  659. (compression>0 && guessed>0)?" Trying both.":"");
  660. }
  661. /* Try declared compression first if we can. */
  662. if (compression > 0)
  663. tor_gzip_uncompress(&new_body, &new_len, body, body_len, compression);
  664. /* Okay, if that didn't work, and we think that it was compressed
  665. * differently, try that. */
  666. if (!new_body && guessed > 0 && compression != guessed)
  667. tor_gzip_uncompress(&new_body, &new_len, body, body_len, guessed);
  668. /* If we're pretty sure that we have a compressed directory, and
  669. * we didn't manage to uncompress it, then warn and bail. */
  670. if (!plausible && !new_body) {
  671. log_fn(LOG_WARN, "Unable to decompress HTTP body (server '%s').", conn->address);
  672. tor_free(body); tor_free(headers); tor_free(reason);
  673. return -1;
  674. }
  675. if (new_body) {
  676. tor_free(body);
  677. body = new_body;
  678. body_len = new_len;
  679. }
  680. }
  681. if (conn->purpose == DIR_PURPOSE_FETCH_DIR) {
  682. /* fetch/process the directory to learn about new routers. */
  683. log_fn(LOG_INFO,"Received directory (size %d) from server '%s'",
  684. (int)body_len, conn->address);
  685. if (status_code == 503 || body_len == 0) {
  686. log_fn(LOG_INFO,"Empty directory; status %d (\"%s\") Ignoring.",
  687. status_code, reason);
  688. tor_free(body); tor_free(headers); tor_free(reason);
  689. return 0;
  690. }
  691. if (status_code != 200) {
  692. log_fn(LOG_WARN,"Received http status code %d (\"%s\") from server '%s'. Failing.",
  693. status_code, reason, conn->address);
  694. tor_free(body); tor_free(headers); tor_free(reason);
  695. return -1;
  696. }
  697. if (router_load_routerlist_from_directory(body, NULL, !skewed, 0) < 0) {
  698. log_fn(LOG_NOTICE,"I failed to parse the directory I fetched from %s:%d. Ignoring.", conn->address, conn->port);
  699. } else {
  700. log_fn(LOG_INFO,"updated routers.");
  701. }
  702. /* do things we've been waiting to do */
  703. directory_has_arrived(time(NULL), conn->identity_digest);
  704. }
  705. if (conn->purpose == DIR_PURPOSE_FETCH_RUNNING_LIST) {
  706. running_routers_t *rrs;
  707. routerlist_t *rl;
  708. /* just update our list of running routers, if this list is new info */
  709. log_fn(LOG_INFO,"Received running-routers list (size %d)", (int)body_len);
  710. if (status_code != 200) {
  711. log_fn(LOG_WARN,"Received http status code %d (\"%s\") from server '%s'. Failing.",
  712. status_code, reason, conn->address);
  713. tor_free(body); tor_free(headers); tor_free(reason);
  714. return -1;
  715. }
  716. if (!(rrs = router_parse_runningrouters(body, 1))) {
  717. log_fn(LOG_WARN, "Can't parse runningrouters list (server '%s')", conn->address);
  718. tor_free(body); tor_free(headers); tor_free(reason);
  719. return -1;
  720. }
  721. router_get_routerlist(&rl);
  722. if (rl) {
  723. routerlist_set_runningrouters(rl,rrs);
  724. } else {
  725. running_routers_free(rrs);
  726. }
  727. }
  728. if (conn->purpose == DIR_PURPOSE_UPLOAD_DIR) {
  729. switch (status_code) {
  730. case 200:
  731. log_fn(LOG_INFO,"eof (status 200) after uploading server descriptor: finished.");
  732. break;
  733. case 400:
  734. log_fn(LOG_WARN,"http status 400 (\"%s\") response from dirserver '%s'. Malformed server descriptor?", reason, conn->address);
  735. break;
  736. case 403:
  737. log_fn(LOG_WARN,"http status 403 (\"%s\") response from dirserver '%s'. Is your clock skewed? Have you mailed us your key fingerprint? Are you using the right key? Are you using a private IP address? See http://tor.eff.org/doc/tor-doc.html#server.", reason, conn->address);
  738. break;
  739. default:
  740. log_fn(LOG_WARN,"http status %d (\"%s\") reason unexpected (server '%s').", status_code, reason, conn->address);
  741. break;
  742. }
  743. }
  744. if (conn->purpose == DIR_PURPOSE_FETCH_RENDDESC) {
  745. log_fn(LOG_INFO,"Received rendezvous descriptor (size %d, status %d (\"%s\"))",
  746. (int)body_len, status_code, reason);
  747. switch (status_code) {
  748. case 200:
  749. if (rend_cache_store(body, body_len) < 0) {
  750. log_fn(LOG_WARN,"Failed to store rendezvous descriptor.");
  751. /* alice's ap_stream will notice when connection_mark_for_close
  752. * cleans it up */
  753. } else {
  754. /* success. notify pending connections about this. */
  755. conn->purpose = DIR_PURPOSE_HAS_FETCHED_RENDDESC;
  756. rend_client_desc_here(conn->rend_query);
  757. }
  758. break;
  759. case 404:
  760. /* not there. pending connections will be notified when
  761. * connection_mark_for_close cleans it up. */
  762. break;
  763. case 400:
  764. log_fn(LOG_WARN,"http status 400 (\"%s\"). Dirserver didn't like our rendezvous query?", reason);
  765. break;
  766. default:
  767. log_fn(LOG_WARN,"http status %d (\"%s\") response unexpected (server '%s').", status_code, reason, conn->address);
  768. break;
  769. }
  770. }
  771. if (conn->purpose == DIR_PURPOSE_UPLOAD_RENDDESC) {
  772. switch (status_code) {
  773. case 200:
  774. log_fn(LOG_INFO,"Uploading rendezvous descriptor: finished with status 200 (\"%s\")", reason);
  775. break;
  776. case 400:
  777. log_fn(LOG_WARN,"http status 400 (\"%s\") response from dirserver. Malformed rendezvous descriptor?", reason);
  778. break;
  779. default:
  780. log_fn(LOG_WARN,"http status %d (\"%s\") response unexpected (server '%s').", status_code, reason, conn->address);
  781. break;
  782. }
  783. }
  784. tor_free(body); tor_free(headers); tor_free(reason);
  785. return 0;
  786. }
  787. /** Called when a directory connection reaches EOF */
  788. int
  789. connection_dir_reached_eof(connection_t *conn)
  790. {
  791. int retval;
  792. if (conn->state != DIR_CONN_STATE_CLIENT_READING) {
  793. log_fn(LOG_INFO,"conn reached eof, not reading. Closing.");
  794. connection_close_immediate(conn); /* it was an error; give up on flushing */
  795. connection_mark_for_close(conn);
  796. return -1;
  797. }
  798. retval = connection_dir_client_reached_eof(conn);
  799. connection_mark_for_close(conn);
  800. return retval;
  801. }
  802. /** Read handler for directory connections. (That's connections <em>to</em>
  803. * directory servers and connections <em>at</em> directory servers.)
  804. */
  805. int connection_dir_process_inbuf(connection_t *conn)
  806. {
  807. tor_assert(conn);
  808. tor_assert(conn->type == CONN_TYPE_DIR);
  809. /* Directory clients write, then read data until they receive EOF;
  810. * directory servers read data until they get an HTTP command, then
  811. * write their response (when it's finished flushing, they mark for
  812. * close).
  813. */
  814. /* If we're on the dirserver side, look for a command. */
  815. if (conn->state == DIR_CONN_STATE_SERVER_COMMAND_WAIT) {
  816. if (directory_handle_command(conn) < 0) {
  817. connection_mark_for_close(conn);
  818. return -1;
  819. }
  820. return 0;
  821. }
  822. /* XXX for READ states, might want to make sure inbuf isn't too big */
  823. log_fn(LOG_DEBUG,"Got data, not eof. Leaving on inbuf.");
  824. return 0;
  825. }
  826. /** Create an http response for the client <b>conn</b> out of
  827. * <b>status</b> and <b>reason_phrase</b>. Write it to <b>conn</b>.
  828. */
  829. static void
  830. write_http_status_line(connection_t *conn, int status,
  831. const char *reason_phrase)
  832. {
  833. char buf[256];
  834. if (tor_snprintf(buf, sizeof(buf), "HTTP/1.0 %d %s\r\n\r\n",
  835. status, reason_phrase) < 0) {
  836. log_fn(LOG_WARN,"Bug: status line too long.");
  837. return;
  838. }
  839. connection_write_to_buf(buf, strlen(buf), conn);
  840. }
  841. /** Helper function: return 1 if there are any dir conns of purpose
  842. * <b>purpose</b> that are going elsewhere than our own ORPort/Dirport.
  843. * Else return 0.
  844. */
  845. static int
  846. already_fetching_directory(int purpose)
  847. {
  848. int i, n;
  849. connection_t *conn;
  850. connection_t **carray;
  851. get_connection_array(&carray,&n);
  852. for (i=0;i<n;i++) {
  853. conn = carray[i];
  854. if (conn->type == CONN_TYPE_DIR &&
  855. conn->purpose == purpose &&
  856. !conn->marked_for_close &&
  857. !router_digest_is_me(conn->identity_digest))
  858. return 1;
  859. }
  860. return 0;
  861. }
  862. /** Helper function: called when a dirserver gets a complete HTTP GET
  863. * request. Look for a request for a directory or for a rendezvous
  864. * service descriptor. On finding one, write a response into
  865. * conn-\>outbuf. If the request is unrecognized, send a 400.
  866. * Always return 0. */
  867. static int
  868. directory_handle_command_get(connection_t *conn, char *headers,
  869. char *body, size_t body_len)
  870. {
  871. size_t dlen;
  872. const char *cp;
  873. char *url;
  874. char tmp[8192];
  875. char date[RFC1123_TIME_LEN+1];
  876. log_fn(LOG_DEBUG,"Received GET command.");
  877. conn->state = DIR_CONN_STATE_SERVER_WRITING;
  878. if (parse_http_url(headers, &url) < 0) {
  879. write_http_status_line(conn, 400, "Bad request");
  880. return 0;
  881. }
  882. log_fn(LOG_INFO,"rewritten url as '%s'.", url);
  883. if (!strcmp(url,"/tor/") || !strcmp(url,"/tor/dir.z")) { /* directory fetch */
  884. int deflated = !strcmp(url,"/tor/dir.z");
  885. dlen = dirserv_get_directory(&cp, deflated);
  886. tor_free(url);
  887. if (dlen == 0) {
  888. log_fn(LOG_NOTICE,"Client asked for the mirrored directory, but we don't have a good one yet. Sending 503 Dir not available.");
  889. write_http_status_line(conn, 503, "Directory unavailable");
  890. /* try to get a new one now */
  891. if (!already_fetching_directory(DIR_PURPOSE_FETCH_DIR))
  892. directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL, 1);
  893. return 0;
  894. }
  895. log_fn(LOG_DEBUG,"Dumping %sdirectory to client.",
  896. deflated?"deflated ":"");
  897. format_rfc1123_time(date, time(NULL));
  898. 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",
  899. date,
  900. (int)dlen,
  901. deflated?"deflate":"identity");
  902. connection_write_to_buf(tmp, strlen(tmp), conn);
  903. connection_write_to_buf(cp, dlen, conn);
  904. return 0;
  905. }
  906. if (!strcmp(url,"/tor/running-routers") ||
  907. !strcmp(url,"/tor/running-routers.z")) { /* running-routers fetch */
  908. int deflated = !strcmp(url,"/tor/dir.z");
  909. tor_free(url);
  910. dlen = dirserv_get_runningrouters(&cp, deflated);
  911. if (!dlen) { /* we failed to create/cache cp */
  912. write_http_status_line(conn, 503, "Directory unavailable");
  913. /* try to get a new one now */
  914. if (!already_fetching_directory(DIR_PURPOSE_FETCH_RUNNING_LIST))
  915. directory_get_from_dirserver(DIR_PURPOSE_FETCH_RUNNING_LIST, NULL, 1);
  916. return 0;
  917. }
  918. format_rfc1123_time(date, time(NULL));
  919. 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",
  920. date,
  921. (int)dlen,
  922. deflated?"deflate":"identity");
  923. connection_write_to_buf(tmp, strlen(tmp), conn);
  924. connection_write_to_buf(cp, strlen(cp), conn);
  925. return 0;
  926. }
  927. if (!strcmpstart(url,"/tor/rendezvous/")) {
  928. /* rendezvous descriptor fetch */
  929. const char *descp;
  930. size_t desc_len;
  931. if (!authdir_mode(get_options())) {
  932. /* We don't hand out rend descs. In fact, it could be a security
  933. * risk, since rend_cache_lookup_desc() below would provide it
  934. * if we're gone to the site recently, and 404 if we haven't.
  935. *
  936. * Reject. */
  937. write_http_status_line(conn, 400, "Nonauthoritative directory does not not store rendezvous descriptors.");
  938. tor_free(url);
  939. return 0;
  940. }
  941. switch (rend_cache_lookup_desc(url+strlen("/tor/rendezvous/"), &descp, &desc_len)) {
  942. case 1: /* valid */
  943. format_rfc1123_time(date, time(NULL));
  944. 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",
  945. date,
  946. (int)desc_len); /* can't include descp here, because it's got nuls */
  947. connection_write_to_buf(tmp, strlen(tmp), conn);
  948. connection_write_to_buf(descp, desc_len, conn);
  949. break;
  950. case 0: /* well-formed but not present */
  951. write_http_status_line(conn, 404, "Not found");
  952. break;
  953. case -1: /* not well-formed */
  954. write_http_status_line(conn, 400, "Bad request");
  955. break;
  956. }
  957. tor_free(url);
  958. return 0;
  959. }
  960. /* we didn't recognize the url */
  961. write_http_status_line(conn, 404, "Not found");
  962. tor_free(url);
  963. return 0;
  964. }
  965. /** Helper function: called when a dirserver gets a complete HTTP POST
  966. * request. Look for an uploaded server descriptor or rendezvous
  967. * service descriptor. On finding one, process it and write a
  968. * response into conn-\>outbuf. If the request is unrecognized, send a
  969. * 400. Always return 0. */
  970. static int
  971. directory_handle_command_post(connection_t *conn, char *headers,
  972. char *body, size_t body_len)
  973. {
  974. const char *cp;
  975. char *url;
  976. log_fn(LOG_DEBUG,"Received POST command.");
  977. conn->state = DIR_CONN_STATE_SERVER_WRITING;
  978. if (!authdir_mode(get_options())) {
  979. /* we just provide cached directories; we don't want to
  980. * receive anything. */
  981. write_http_status_line(conn, 400, "Nonauthoritative directory does not not store server descriptors.");
  982. return 0;
  983. }
  984. if (parse_http_url(headers, &url) < 0) {
  985. write_http_status_line(conn, 400, "Bad request");
  986. return 0;
  987. }
  988. log_fn(LOG_INFO,"rewritten url as '%s'.", url);
  989. if (!strcmp(url,"/tor/")) { /* server descriptor post */
  990. const char *msg;
  991. cp = body;
  992. switch (dirserv_add_descriptor(&cp, &msg)) {
  993. case -2:
  994. case -1:
  995. /* malformed descriptor, or something wrong */
  996. write_http_status_line(conn, 400, msg?msg:"Malformed or unacceptable server descriptor");
  997. log_fn(LOG_NOTICE,"Rejected descriptor published by '%s'.", conn->address);
  998. break;
  999. case 0:
  1000. /* descriptor was well-formed but server has not been approved */
  1001. write_http_status_line(conn, 200, msg?msg:"Unverified server descriptor accepted");
  1002. break;
  1003. case 1:
  1004. dirserv_get_directory(&cp, 0); /* rebuild and write to disk */
  1005. write_http_status_line(conn, 200, msg?msg:"Verified server descriptor accepted");
  1006. break;
  1007. }
  1008. tor_free(url);
  1009. return 0;
  1010. }
  1011. if (!strcmpstart(url,"/tor/rendezvous/publish")) {
  1012. /* rendezvous descriptor post */
  1013. if (rend_cache_store(body, body_len) < 0)
  1014. write_http_status_line(conn, 400, "Invalid service descriptor rejected");
  1015. else
  1016. write_http_status_line(conn, 200, "Service descriptor stored");
  1017. tor_free(url);
  1018. return 0;
  1019. }
  1020. /* we didn't recognize the url */
  1021. write_http_status_line(conn, 404, "Not found");
  1022. tor_free(url);
  1023. return 0;
  1024. }
  1025. /** Called when a dirserver receives data on a directory connection;
  1026. * looks for an HTTP request. If the request is complete, remove it
  1027. * from the inbuf, try to process it; otherwise, leave it on the
  1028. * buffer. Return a 0 on success, or -1 on error.
  1029. */
  1030. static int
  1031. directory_handle_command(connection_t *conn)
  1032. {
  1033. char *headers=NULL, *body=NULL;
  1034. size_t body_len=0;
  1035. int r;
  1036. tor_assert(conn);
  1037. tor_assert(conn->type == CONN_TYPE_DIR);
  1038. switch (fetch_from_buf_http(conn->inbuf,
  1039. &headers, MAX_HEADERS_SIZE,
  1040. &body, &body_len, MAX_BODY_SIZE)) {
  1041. case -1: /* overflow */
  1042. log_fn(LOG_WARN,"Invalid input from address '%s'. Closing.", conn->address);
  1043. return -1;
  1044. case 0:
  1045. log_fn(LOG_DEBUG,"command not all here yet.");
  1046. return 0;
  1047. /* case 1, fall through */
  1048. }
  1049. log_fn(LOG_DEBUG,"headers '%s', body '%s'.", headers, body);
  1050. if (!strncasecmp(headers,"GET",3))
  1051. r = directory_handle_command_get(conn, headers, body, body_len);
  1052. else if (!strncasecmp(headers,"POST",4))
  1053. r = directory_handle_command_post(conn, headers, body, body_len);
  1054. else {
  1055. log_fn(LOG_WARN,"Got headers '%s' with unknown command. Closing.", headers);
  1056. r = -1;
  1057. }
  1058. tor_free(headers); tor_free(body);
  1059. return r;
  1060. }
  1061. /** Write handler for directory connections; called when all data has
  1062. * been flushed. Close the connection or wait for a response as
  1063. * appropriate.
  1064. */
  1065. int
  1066. connection_dir_finished_flushing(connection_t *conn)
  1067. {
  1068. tor_assert(conn);
  1069. tor_assert(conn->type == CONN_TYPE_DIR);
  1070. switch (conn->state) {
  1071. case DIR_CONN_STATE_CLIENT_SENDING:
  1072. log_fn(LOG_DEBUG,"client finished sending command.");
  1073. conn->state = DIR_CONN_STATE_CLIENT_READING;
  1074. connection_stop_writing(conn);
  1075. return 0;
  1076. case DIR_CONN_STATE_SERVER_WRITING:
  1077. log_fn(LOG_INFO,"Finished writing server response. Closing.");
  1078. connection_mark_for_close(conn);
  1079. return 0;
  1080. default:
  1081. log_fn(LOG_WARN,"Bug: called in unexpected state %d.", conn->state);
  1082. tor_fragile_assert();
  1083. return -1;
  1084. }
  1085. return 0;
  1086. }
  1087. /** Connected handler for directory connections: begin sending data to the
  1088. * server */
  1089. int
  1090. connection_dir_finished_connecting(connection_t *conn)
  1091. {
  1092. tor_assert(conn);
  1093. tor_assert(conn->type == CONN_TYPE_DIR);
  1094. tor_assert(conn->state == DIR_CONN_STATE_CONNECTING);
  1095. log_fn(LOG_INFO,"Dir connection to router %s:%u established.",
  1096. conn->address,conn->port);
  1097. conn->state = DIR_CONN_STATE_CLIENT_SENDING; /* start flushing conn */
  1098. return 0;
  1099. }