directory.c 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582
  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. static char *http_get_header(const char *headers, const char *which);
  48. static char *http_get_origin(const char *headers, connection_t *conn);
  49. static void connection_dir_download_networkstatus_failed(connection_t *conn);
  50. static void connection_dir_download_routerdesc_failed(connection_t *conn);
  51. static void dir_networkstatus_download_failed(smartlist_t *failed);
  52. static void dir_routerdesc_download_failed(smartlist_t *failed);
  53. /********* START VARIABLES **********/
  54. static addr_policy_t *dir_policy = NULL;
  55. #define ALLOW_DIRECTORY_TIME_SKEW 30*60 /* 30 minutes */
  56. /********* END VARIABLES ************/
  57. /** Parse get_options()->DirPolicy, and put the processed version in
  58. * &dir_policy. Ignore port specifiers.
  59. */
  60. void
  61. parse_dir_policy(void)
  62. {
  63. addr_policy_t *n;
  64. if (dir_policy) {
  65. addr_policy_free(dir_policy);
  66. dir_policy = NULL;
  67. }
  68. config_parse_addr_policy(get_options()->DirPolicy, &dir_policy, -1);
  69. /* ports aren't used. */
  70. for (n=dir_policy; n; n = n->next) {
  71. n->prt_min = 1;
  72. n->prt_max = 65535;
  73. }
  74. }
  75. /** Free storage used to hold parsed directory policy */
  76. void
  77. free_dir_policy(void)
  78. {
  79. addr_policy_free(dir_policy);
  80. dir_policy = NULL;
  81. }
  82. /** Return 1 if <b>addr</b> is permitted to connect to our dir port,
  83. * based on <b>dir_policy</b>. Else return 0.
  84. */
  85. int
  86. dir_policy_permits_address(uint32_t addr)
  87. {
  88. int a;
  89. if (!dir_policy) /* 'no dir policy' means 'accept' */
  90. return 1;
  91. a = router_compare_addr_to_addr_policy(addr, 1, dir_policy);
  92. if (a==ADDR_POLICY_REJECTED)
  93. return 0;
  94. else if (a==ADDR_POLICY_ACCEPTED)
  95. return 1;
  96. log_fn(LOG_WARN, "Bug: got unexpected 'maybe' answer from dir policy");
  97. return 0;
  98. }
  99. /** Return true iff the directory purpose 'purpose' must use an
  100. * anonymous connection to a directory. */
  101. static int
  102. purpose_is_private(uint8_t purpose)
  103. {
  104. if (purpose == DIR_PURPOSE_FETCH_DIR ||
  105. purpose == DIR_PURPOSE_UPLOAD_DIR ||
  106. purpose == DIR_PURPOSE_FETCH_RUNNING_LIST ||
  107. purpose == DIR_PURPOSE_FETCH_NETWORKSTATUS ||
  108. purpose == DIR_PURPOSE_FETCH_SERVERDESC)
  109. return 0;
  110. return 1;
  111. }
  112. /** Start a connection to every known directory server, using
  113. * connection purpose 'purpose' and uploading the payload 'payload'
  114. * (length 'payload_len'). The purpose should be one of
  115. * 'DIR_PURPOSE_UPLOAD_DIR' or 'DIR_PURPOSE_UPLOAD_RENDDESC'.
  116. */
  117. void
  118. directory_post_to_dirservers(uint8_t purpose, const char *payload,
  119. size_t payload_len)
  120. {
  121. smartlist_t *dirservers;
  122. router_get_trusted_dir_servers(&dirservers);
  123. tor_assert(dirservers);
  124. /* This tries dirservers which we believe to be down, but ultimately, that's
  125. * harmless, and we may as well err on the side of getting things uploaded.
  126. */
  127. SMARTLIST_FOREACH(dirservers, trusted_dir_server_t *, ds,
  128. {
  129. /* Pay attention to fascistfirewall when we're uploading a
  130. * router descriptor, but not when uploading a service
  131. * descriptor -- those use Tor. */
  132. if (purpose == DIR_PURPOSE_UPLOAD_DIR && !get_options()->HttpProxy) {
  133. if (!fascist_firewall_allows_address(ds->addr,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 = firewall_is_fascist();
  154. or_options_t *options = get_options();
  155. int fetch_fresh_first = server_mode(options) && options->DirPort != 0;
  156. int directconn = !purpose_is_private(purpose);
  157. int need_v1_support = purpose == DIR_PURPOSE_FETCH_DIR ||
  158. purpose == DIR_PURPOSE_FETCH_RUNNING_LIST;
  159. int need_v2_support = purpose == DIR_PURPOSE_FETCH_NETWORKSTATUS ||
  160. purpose == DIR_PURPOSE_FETCH_SERVERDESC;
  161. if (directconn) {
  162. if (fetch_fresh_first && purpose == DIR_PURPOSE_FETCH_NETWORKSTATUS &&
  163. !strcmpstart(resource,"fp/") && strlen(resource) == HEX_DIGEST_LEN+3) {
  164. /* Try to ask the actual dirserver its opinion. */
  165. char digest[DIGEST_LEN];
  166. base16_decode(digest, DIGEST_LEN, resource+3, HEX_DIGEST_LEN);
  167. ds = router_get_trusteddirserver_by_digest(digest);
  168. }
  169. if (!ds && fetch_fresh_first) {
  170. /* only ask authdirservers, and don't ask myself */
  171. ds = router_pick_trusteddirserver(need_v1_support, 1, fascistfirewall,
  172. retry_if_no_servers);
  173. }
  174. if (!ds) {
  175. /* anybody with a non-zero dirport will do */
  176. r = router_pick_directory_server(1, fascistfirewall, need_v2_support,
  177. retry_if_no_servers);
  178. if (!r) {
  179. const char *which;
  180. if (purpose == DIR_PURPOSE_FETCH_DIR)
  181. which = "directory";
  182. else if (purpose == DIR_PURPOSE_FETCH_RUNNING_LIST)
  183. which = "status list";
  184. else if (purpose == DIR_PURPOSE_FETCH_NETWORKSTATUS)
  185. which = "network status";
  186. else // if (purpose == DIR_PURPOSE_FETCH_NETWORKSTATUS)
  187. which = "server descriptors";
  188. log_fn(LOG_INFO,
  189. "No router found for %s; falling back to dirserver list",which);
  190. ds = router_pick_trusteddirserver(1, 1, fascistfirewall,
  191. retry_if_no_servers);
  192. }
  193. }
  194. } else { // (purpose == DIR_PURPOSE_FETCH_RENDDESC)
  195. /* only ask authdirservers, any of them will do */
  196. /* Never use fascistfirewall; we're going via Tor. */
  197. ds = router_pick_trusteddirserver(0, 0, 0, retry_if_no_servers);
  198. }
  199. if (r)
  200. directory_initiate_command_router(r, purpose, !directconn, resource, NULL, 0);
  201. else if (ds)
  202. directory_initiate_command_trusted_dir(ds, purpose, !directconn, resource, NULL, 0);
  203. else {
  204. log_fn(LOG_NOTICE,"No running dirservers known. Will try again later. (purpose %d)",
  205. purpose);
  206. if (directconn) {
  207. /* remember we tried them all and failed. */
  208. directory_all_unreachable(time(NULL));
  209. }
  210. }
  211. }
  212. /** Launch a new connection to the directory server <b>router</b> to upload or
  213. * download a service or rendezvous descriptor. <b>purpose</b> determines what
  214. * kind of directory connection we're launching, and must be one of
  215. * DIR_PURPOSE_{FETCH|UPLOAD}_{DIR|RENDDESC}.
  216. *
  217. * When uploading, <b>payload</b> and <b>payload_len</b> determine the content
  218. * of the HTTP post. Otherwise, <b>payload</b> should be NULL.
  219. *
  220. * When fetching a rendezvous descriptor, <b>resource</b> is the service ID we
  221. * want to fetch.
  222. */
  223. void
  224. directory_initiate_command_router(routerinfo_t *router, uint8_t purpose,
  225. int private_connection, const char *resource,
  226. const char *payload, size_t payload_len)
  227. {
  228. directory_initiate_command(router->address, router->addr, router->dir_port,
  229. router->platform, router->identity_digest,
  230. purpose, private_connection, resource,
  231. payload, payload_len);
  232. }
  233. /** As directory_initiate_command_router, but send the command to a trusted
  234. * directory server <b>dirserv</b>. **/
  235. static void
  236. directory_initiate_command_trusted_dir(trusted_dir_server_t *dirserv,
  237. uint8_t purpose, int private_connection,
  238. const char *resource,
  239. const char *payload, size_t payload_len)
  240. {
  241. directory_initiate_command(dirserv->address, dirserv->addr,dirserv->dir_port,
  242. NULL, dirserv->digest, purpose, private_connection, resource,
  243. payload, payload_len);
  244. }
  245. /** Called when we are unable to complete the client's request to a
  246. * directory server: Mark the router as down and try again if possible.
  247. */
  248. void
  249. connection_dir_request_failed(connection_t *conn)
  250. {
  251. if (router_digest_is_me(conn->identity_digest))
  252. return; /* this was a test fetch. don't retry. */
  253. router_mark_as_down(conn->identity_digest); /* don't try him again */
  254. if (conn->purpose == DIR_PURPOSE_FETCH_DIR ||
  255. conn->purpose == DIR_PURPOSE_FETCH_RUNNING_LIST) {
  256. log_fn(LOG_INFO, "Giving up on directory server at '%s:%d'; retrying",
  257. conn->address, conn->port);
  258. directory_get_from_dirserver(conn->purpose, NULL,
  259. 0 /* don't retry_if_no_servers */);
  260. } else if (conn->purpose == DIR_PURPOSE_FETCH_NETWORKSTATUS) {
  261. log_fn(LOG_INFO, "Giving up on directory server at '%s'; retrying",
  262. conn->address);
  263. connection_dir_download_networkstatus_failed(conn);
  264. } else if (conn->purpose == DIR_PURPOSE_FETCH_NETWORKSTATUS) {
  265. log_fn(LOG_INFO, "Giving up on directory server at '%s'; retrying",
  266. conn->address);
  267. connection_dir_download_routerdesc_failed(conn);
  268. }
  269. }
  270. /** Called when an attempt to download one or network status documents
  271. * on connection <b>conn</b> failed.
  272. */
  273. static void
  274. connection_dir_download_networkstatus_failed(connection_t *conn)
  275. {
  276. if (!strcmpstart(conn->requested_resource, "all")) {
  277. /* We're a non-authoritative directory cache; try again. */
  278. directory_get_from_dirserver(conn->purpose, "all.z",
  279. 0 /* don't retry_if_no_servers */);
  280. } else if (!strcmpstart(conn->requested_resource, "fp/")) {
  281. /* We were trying to download by fingerprint; mark them all has having
  282. * failed, and possibly retry them later.*/
  283. smartlist_t *failed = smartlist_create();
  284. /* XXXX NM this splitting logic is duplicated someplace. Fix that. */
  285. smartlist_split_string(failed, conn->requested_resource+3, "+", 0, 0);
  286. if (smartlist_len(failed)) {
  287. char *last = smartlist_get(failed,smartlist_len(failed)-1);
  288. size_t last_len = strlen(last);
  289. if (!strcmp(last+last_len-2, ".z"))
  290. last[last_len-2] = '\0';
  291. dir_networkstatus_download_failed(failed);
  292. SMARTLIST_FOREACH(failed, char *, cp, tor_free(cp));
  293. }
  294. smartlist_free(failed);
  295. }
  296. }
  297. /** Called when an attempt to download one or network status documents
  298. * on connection <b>conn</b> failed.
  299. */
  300. static void
  301. connection_dir_download_routerdesc_failed(connection_t *conn)
  302. {
  303. /* try again. */
  304. update_router_descriptor_downloads(time(NULL));
  305. }
  306. /** Helper for directory_initiate_command_(router|trusted_dir): send the
  307. * command to a server whose address is <b>address</b>, whose IP is
  308. * <b>addr</b>, whose directory port is <b>dir_port</b>, whose tor version is
  309. * <b>platform</b>, and whose identity key digest is <b>digest</b>. The
  310. * <b>platform</b> argument is optional; the others are required. */
  311. static void
  312. directory_initiate_command(const char *address, uint32_t addr,
  313. uint16_t dir_port, const char *platform,
  314. const char *digest, uint8_t purpose,
  315. int private_connection, const char *resource,
  316. const char *payload, size_t payload_len)
  317. {
  318. connection_t *conn;
  319. tor_assert(address);
  320. tor_assert(addr);
  321. tor_assert(dir_port);
  322. tor_assert(digest);
  323. switch (purpose) {
  324. case DIR_PURPOSE_FETCH_DIR:
  325. log_fn(LOG_DEBUG,"initiating directory fetch");
  326. break;
  327. case DIR_PURPOSE_FETCH_RENDDESC:
  328. log_fn(LOG_DEBUG,"initiating hidden-service descriptor fetch");
  329. break;
  330. case DIR_PURPOSE_UPLOAD_DIR:
  331. log_fn(LOG_DEBUG,"initiating server descriptor upload");
  332. break;
  333. case DIR_PURPOSE_UPLOAD_RENDDESC:
  334. log_fn(LOG_DEBUG,"initiating hidden-service descriptor upload");
  335. break;
  336. case DIR_PURPOSE_FETCH_RUNNING_LIST:
  337. log_fn(LOG_DEBUG,"initiating running-routers fetch");
  338. break;
  339. case DIR_PURPOSE_FETCH_NETWORKSTATUS:
  340. log_fn(LOG_DEBUG,"initiating network-status fetch");
  341. break;
  342. case DIR_PURPOSE_FETCH_SERVERDESC:
  343. log_fn(LOG_DEBUG,"initiating server descriptor fetch");
  344. break;
  345. default:
  346. log_fn(LOG_ERR, "Unrecognized directory connection purpose.");
  347. tor_assert(0);
  348. }
  349. conn = connection_new(CONN_TYPE_DIR);
  350. /* set up conn so it's got all the data we need to remember */
  351. conn->addr = addr;
  352. conn->port = dir_port;
  353. conn->address = tor_strdup(address);
  354. memcpy(conn->identity_digest, digest, DIGEST_LEN);
  355. conn->purpose = purpose;
  356. /* give it an initial state */
  357. conn->state = DIR_CONN_STATE_CONNECTING;
  358. if (!private_connection) {
  359. /* then we want to connect directly */
  360. if (get_options()->HttpProxy) {
  361. addr = get_options()->HttpProxyAddr;
  362. dir_port = get_options()->HttpProxyPort;
  363. }
  364. switch (connection_connect(conn, conn->address, addr, dir_port)) {
  365. case -1:
  366. connection_dir_request_failed(conn); /* retry if we want */
  367. connection_free(conn);
  368. return;
  369. case 1:
  370. conn->state = DIR_CONN_STATE_CLIENT_SENDING; /* start flushing conn */
  371. /* fall through */
  372. case 0:
  373. /* queue the command on the outbuf */
  374. directory_send_command(conn, platform, purpose, resource,
  375. payload, payload_len);
  376. connection_watch_events(conn, EV_READ | EV_WRITE);
  377. /* writable indicates finish, readable indicates broken link,
  378. error indicates broken link in windowsland. */
  379. }
  380. } else { /* we want to connect via tor */
  381. /* make an AP connection
  382. * populate it and add it at the right state
  383. * socketpair and hook up both sides
  384. */
  385. conn->s = connection_ap_make_bridge(conn->address, conn->port);
  386. if (conn->s < 0) {
  387. log_fn(LOG_WARN,"Making AP bridge to dirserver failed.");
  388. connection_mark_for_close(conn);
  389. return;
  390. }
  391. conn->state = DIR_CONN_STATE_CLIENT_SENDING;
  392. connection_add(conn);
  393. /* queue the command on the outbuf */
  394. directory_send_command(conn, platform, purpose, resource,
  395. payload, payload_len);
  396. connection_watch_events(conn, EV_READ | EV_WRITE);
  397. }
  398. }
  399. /** Queue an appropriate HTTP command on conn-\>outbuf. The other args
  400. * are as in directory_initiate_command.
  401. */
  402. static void
  403. directory_send_command(connection_t *conn, const char *platform,
  404. int purpose, const char *resource,
  405. const char *payload, size_t payload_len)
  406. {
  407. char proxystring[256];
  408. char proxyauthstring[256];
  409. char hoststring[128];
  410. char *url;
  411. char request[8192];
  412. const char *httpcommand = NULL;
  413. size_t len;
  414. tor_assert(conn);
  415. tor_assert(conn->type == CONN_TYPE_DIR);
  416. tor_free(conn->requested_resource);
  417. if (resource)
  418. conn->requested_resource = tor_strdup(resource);
  419. /* come up with a string for which Host: we want */
  420. if (conn->port == 80) {
  421. strlcpy(hoststring, conn->address, sizeof(hoststring));
  422. } else {
  423. tor_snprintf(hoststring, sizeof(hoststring),"%s:%d",conn->address, conn->port);
  424. }
  425. /* come up with some proxy lines, if we're using one. */
  426. if (get_options()->HttpProxy) {
  427. char *base64_authenticator=NULL;
  428. const char *authenticator = get_options()->HttpProxyAuthenticator;
  429. tor_snprintf(proxystring, sizeof(proxystring),"http://%s", hoststring);
  430. if (authenticator) {
  431. base64_authenticator = alloc_http_authenticator(authenticator);
  432. if (!base64_authenticator)
  433. log_fn(LOG_WARN, "Encoding http authenticator failed");
  434. }
  435. if (base64_authenticator) {
  436. tor_snprintf(proxyauthstring, sizeof(proxyauthstring),
  437. "\r\nProxy-Authorization: Basic %s",
  438. base64_authenticator);
  439. tor_free(base64_authenticator);
  440. } else {
  441. proxyauthstring[0] = 0;
  442. }
  443. } else {
  444. proxystring[0] = 0;
  445. proxyauthstring[0] = 0;
  446. }
  447. switch (purpose) {
  448. case DIR_PURPOSE_FETCH_DIR:
  449. tor_assert(!resource);
  450. tor_assert(!payload);
  451. log_fn(LOG_DEBUG, "Asking for compressed directory from server running %s",
  452. platform?platform:"<unknown version>");
  453. httpcommand = "GET";
  454. url = tor_strdup("/tor/dir.z");
  455. break;
  456. case DIR_PURPOSE_FETCH_RUNNING_LIST:
  457. tor_assert(!resource);
  458. tor_assert(!payload);
  459. httpcommand = "GET";
  460. url = tor_strdup("/tor/running-routers");
  461. break;
  462. case DIR_PURPOSE_FETCH_NETWORKSTATUS:
  463. httpcommand = "GET";
  464. len = strlen(resource)+32;
  465. url = tor_malloc(len);
  466. tor_snprintf(url, len, "/tor/status/%s", resource);
  467. break;
  468. case DIR_PURPOSE_FETCH_SERVERDESC:
  469. httpcommand = "GET";
  470. len = strlen(resource)+32;
  471. url = tor_malloc(len);
  472. tor_snprintf(url, len, "/tor/server/%s", resource);
  473. break;
  474. case DIR_PURPOSE_UPLOAD_DIR:
  475. tor_assert(!resource);
  476. tor_assert(payload);
  477. httpcommand = "POST";
  478. url = tor_strdup("/tor/");
  479. break;
  480. case DIR_PURPOSE_FETCH_RENDDESC:
  481. tor_assert(resource);
  482. tor_assert(!payload);
  483. /* this must be true or we wouldn't be doing the lookup */
  484. tor_assert(strlen(resource) <= REND_SERVICE_ID_LEN);
  485. /* This breaks the function abstraction. */
  486. strlcpy(conn->rend_query, resource, sizeof(conn->rend_query));
  487. httpcommand = "GET";
  488. /* Request the most recent versioned descriptor. */
  489. // XXXX011
  490. //tor_snprintf(url, sizeof(url), "/tor/rendezvous1/%s", resource);
  491. len = strlen(resource)+32;
  492. url = tor_malloc(len);
  493. tor_snprintf(url, len, "/tor/rendezvous/%s", resource);
  494. break;
  495. case DIR_PURPOSE_UPLOAD_RENDDESC:
  496. tor_assert(!resource);
  497. tor_assert(payload);
  498. httpcommand = "POST";
  499. url = tor_strdup("/tor/rendezvous/publish");
  500. break;
  501. default:
  502. tor_assert(0);
  503. return;
  504. }
  505. tor_snprintf(request, sizeof(request), "%s %s", httpcommand, proxystring);
  506. connection_write_to_buf(request, strlen(request), conn);
  507. connection_write_to_buf(url, strlen(url), conn);
  508. tor_free(url);
  509. tor_snprintf(request, sizeof(request), " HTTP/1.0\r\nContent-Length: %lu\r\nHost: %s%s\r\n\r\n",
  510. payload ? (unsigned long)payload_len : 0,
  511. hoststring,
  512. proxyauthstring);
  513. connection_write_to_buf(request, strlen(request), conn);
  514. if (payload) {
  515. /* then send the payload afterwards too */
  516. connection_write_to_buf(payload, payload_len, conn);
  517. }
  518. }
  519. /** Parse an HTTP request string <b>headers</b> of the form
  520. * \verbatim
  521. * "\%s [http[s]://]\%s HTTP/1..."
  522. * \endverbatim
  523. * If it's well-formed, strdup the second \%s into *<b>url</b>, and
  524. * null-terminate it. If the url doesn't start with "/tor/", rewrite it
  525. * so it does. Return 0.
  526. * Otherwise, return -1.
  527. */
  528. static int
  529. parse_http_url(char *headers, char **url)
  530. {
  531. char *s, *start, *tmp;
  532. s = (char *)eat_whitespace_no_nl(headers);
  533. if (!*s) return -1;
  534. s = (char *)find_whitespace(s); /* get past GET/POST */
  535. if (!*s) return -1;
  536. s = (char *)eat_whitespace_no_nl(s);
  537. if (!*s) return -1;
  538. start = s; /* this is it, assuming it's valid */
  539. s = (char *)find_whitespace(start);
  540. if (!*s) return -1;
  541. /* tolerate the http[s] proxy style of putting the hostname in the url */
  542. if (s-start >= 4 && !strcmpstart(start,"http")) {
  543. tmp = start + 4;
  544. if (*tmp == 's')
  545. tmp++;
  546. if (s-tmp >= 3 && !strcmpstart(tmp,"://")) {
  547. tmp = strchr(tmp+3, '/');
  548. if (tmp && tmp < s) {
  549. log_fn(LOG_DEBUG,"Skipping over 'http[s]://hostname' string");
  550. start = tmp;
  551. }
  552. }
  553. }
  554. if (s-start < 5 || strcmpstart(start,"/tor/")) { /* need to rewrite it */
  555. *url = tor_malloc(s - start + 5);
  556. strlcpy(*url,"/tor", s-start+5);
  557. strlcat((*url)+4, start, s-start+1);
  558. } else {
  559. *url = tor_strndup(start, s-start);
  560. }
  561. return 0;
  562. }
  563. /** Return a copy of the first HTTP header in <b>headers</b> whose key is
  564. * <b>which</b>. The key should be given with a terminating colon and space;
  565. * this function copies everything after, up to but not including the
  566. * following \\r\\n. */
  567. static char *
  568. http_get_header(const char *headers, const char *which)
  569. {
  570. const char *cp = headers;
  571. while (cp) {
  572. if (!strcmpstart(cp, which)) {
  573. char *eos;
  574. cp += strlen(which);
  575. if ((eos = strchr(cp,'\r')))
  576. return tor_strndup(cp, eos-cp);
  577. else
  578. return tor_strdup(cp);
  579. }
  580. cp = strchr(cp, '\n');
  581. if (cp)
  582. ++cp;
  583. }
  584. return NULL;
  585. }
  586. /** Allocate and return a string describing the source of an HTTP request with
  587. * headers <b>headers</b> received on <b>conn</b>. The format is either
  588. * "'1.2.3.4'", or "'1.2.3.4' (forwarded for '5.6.7.8')".
  589. */
  590. static char *
  591. http_get_origin(const char *headers, connection_t *conn)
  592. {
  593. char *fwd;
  594. fwd = http_get_header(headers, "Forwarded-For: ");
  595. if (!fwd)
  596. fwd = http_get_header(headers, "X-Forwarded-For: ");
  597. if (fwd) {
  598. size_t len = strlen(fwd)+strlen(conn->address)+32;
  599. char *result = tor_malloc(len);
  600. tor_snprintf(result, len, "'%s' (forwarded for '%s')", conn->address, fwd);
  601. tor_free(fwd);
  602. return result;
  603. } else {
  604. size_t len = strlen(conn->address)+3;
  605. char *result = tor_malloc(len);
  606. tor_snprintf(result, len, "'%s'", conn->address);
  607. return result;
  608. }
  609. }
  610. /** Parse an HTTP response string <b>headers</b> of the form
  611. * \verbatim
  612. * "HTTP/1.\%d \%d\%s\r\n...".
  613. * \endverbatim
  614. *
  615. * If it's well-formed, assign the status code to *<b>code</b> and
  616. * return 0. Otherwise, return -1.
  617. *
  618. * On success: If <b>date</b> is provided, set *date to the Date
  619. * header in the http headers, or 0 if no such header is found. If
  620. * <b>compression</b> is provided, set *<b>compression</b> to the
  621. * compression method given in the Content-Encoding header, or 0 if no
  622. * such header is found, or -1 if the value of the header is not
  623. * recognized. If <b>reason</b> is provided, strdup the reason string
  624. * into it.
  625. */
  626. int
  627. parse_http_response(const char *headers, int *code, time_t *date,
  628. int *compression, char **reason)
  629. {
  630. int n1, n2;
  631. char datestr[RFC1123_TIME_LEN+1];
  632. smartlist_t *parsed_headers;
  633. tor_assert(headers);
  634. tor_assert(code);
  635. while (TOR_ISSPACE(*headers)) headers++; /* tolerate leading whitespace */
  636. if (sscanf(headers, "HTTP/1.%d %d", &n1, &n2) < 2 ||
  637. (n1 != 0 && n1 != 1) ||
  638. (n2 < 100 || n2 >= 600)) {
  639. log_fn(LOG_WARN,"Failed to parse header '%s'",headers);
  640. return -1;
  641. }
  642. *code = n2;
  643. parsed_headers = smartlist_create();
  644. smartlist_split_string(parsed_headers, headers, "\n",
  645. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  646. if (reason) {
  647. smartlist_t *status_line_elements = smartlist_create();
  648. tor_assert(smartlist_len(parsed_headers));
  649. smartlist_split_string(status_line_elements,
  650. smartlist_get(parsed_headers, 0),
  651. " ", SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 3);
  652. tor_assert(smartlist_len(status_line_elements) <= 3);
  653. if (smartlist_len(status_line_elements) == 3) {
  654. *reason = smartlist_get(status_line_elements, 2);
  655. smartlist_set(status_line_elements, 2, NULL); /* Prevent free */
  656. }
  657. SMARTLIST_FOREACH(status_line_elements, char *, cp, tor_free(cp));
  658. smartlist_free(status_line_elements);
  659. }
  660. if (date) {
  661. *date = 0;
  662. SMARTLIST_FOREACH(parsed_headers, const char *, s,
  663. if (!strcmpstart(s, "Date: ")) {
  664. strlcpy(datestr, s+6, sizeof(datestr));
  665. /* This will do nothing on failure, so we don't need to check
  666. the result. We shouldn't warn, since there are many other valid
  667. date formats besides the one we use. */
  668. parse_rfc1123_time(datestr, date);
  669. break;
  670. });
  671. }
  672. if (compression) {
  673. const char *enc = NULL;
  674. SMARTLIST_FOREACH(parsed_headers, const char *, s,
  675. if (!strcmpstart(s, "Content-Encoding: ")) {
  676. enc = s+18; break;
  677. });
  678. if (!enc || !strcmp(enc, "identity")) {
  679. *compression = 0;
  680. } else if (!strcmp(enc, "deflate") || !strcmp(enc, "x-deflate")) {
  681. *compression = ZLIB_METHOD;
  682. } else if (!strcmp(enc, "gzip") || !strcmp(enc, "x-gzip")) {
  683. *compression = GZIP_METHOD;
  684. } else {
  685. log_fn(LOG_INFO, "Unrecognized content encoding: '%s'. Trying to deal.", enc);
  686. *compression = -1;
  687. }
  688. }
  689. SMARTLIST_FOREACH(parsed_headers, char *, s, tor_free(s));
  690. smartlist_free(parsed_headers);
  691. return 0;
  692. }
  693. /** Return true iff <b>body</b> doesn't start with a plausible router or
  694. * running-list or directory opening. This is a sign of possible compression.
  695. **/
  696. static int
  697. body_is_plausible(const char *body, size_t len, int purpose)
  698. {
  699. int i;
  700. if (len == 0)
  701. return 1; /* empty bodies don't need decompression */
  702. if (len < 32)
  703. return 0;
  704. if (purpose != DIR_PURPOSE_FETCH_RENDDESC) {
  705. if (!strcmpstart(body,"router") ||
  706. !strcmpstart(body,"signed-directory") ||
  707. !strcmpstart(body,"network-status") ||
  708. !strcmpstart(body,"running-routers"))
  709. return 1;
  710. for (i=0;i<32;++i) {
  711. if (!TOR_ISPRINT(body[i]) && !TOR_ISSPACE(body[i]))
  712. return 0;
  713. }
  714. return 1;
  715. } else {
  716. return 1;
  717. }
  718. }
  719. /** We are a client, and we've finished reading the server's
  720. * response. Parse and it and act appropriately.
  721. *
  722. * If we're happy with the result (we get it and it's useful),
  723. * return 0. Otherwise return -1, and the caller should consider
  724. * trying the request again.
  725. *
  726. * The caller will take care of marking the connection for close.
  727. */
  728. static int
  729. connection_dir_client_reached_eof(connection_t *conn)
  730. {
  731. char *body;
  732. char *headers;
  733. char *reason = NULL;
  734. size_t body_len=0;
  735. int status_code;
  736. time_t now, date_header=0;
  737. int delta;
  738. int compression;
  739. int plausible;
  740. int skewed=0;
  741. switch (fetch_from_buf_http(conn->inbuf,
  742. &headers, MAX_HEADERS_SIZE,
  743. &body, &body_len, MAX_DIR_SIZE)) {
  744. case -1: /* overflow */
  745. log_fn(LOG_WARN,"'fetch' response too large (server '%s:%d'). Closing.", conn->address, conn->port);
  746. return -1;
  747. case 0:
  748. log_fn(LOG_INFO,"'fetch' response not all here, but we're at eof. Closing.");
  749. return -1;
  750. /* case 1, fall through */
  751. }
  752. if (parse_http_response(headers, &status_code, &date_header,
  753. &compression, &reason) < 0) {
  754. log_fn(LOG_WARN,"Unparseable headers (server '%s:%d'). Closing.", conn->address, conn->port);
  755. tor_free(body); tor_free(headers);
  756. return -1;
  757. }
  758. if (!reason) reason = tor_strdup("[no reason given]");
  759. log_fn(LOG_DEBUG,
  760. "Received response from directory server '%s:%d': %d \"%s\"",
  761. conn->address, conn->port, status_code, reason);
  762. if (date_header > 0) {
  763. now = time(NULL);
  764. delta = now-date_header;
  765. if (abs(delta)>ALLOW_DIRECTORY_TIME_SKEW) {
  766. log_fn(router_digest_is_trusted_dir(conn->identity_digest) ? LOG_WARN : LOG_INFO,
  767. "Received directory with skewed time (server '%s:%d'): we are %d minutes %s, or the directory is %d minutes %s.",
  768. conn->address, conn->port,
  769. abs(delta)/60, delta>0 ? "ahead" : "behind",
  770. abs(delta)/60, delta>0 ? "behind" : "ahead");
  771. skewed = 1; /* don't check the recommended-versions line */
  772. } else {
  773. log_fn(LOG_INFO, "Time on received directory is within tolerance; we are %d seconds skewed. (That's okay.)", delta);
  774. }
  775. }
  776. plausible = body_is_plausible(body, body_len, conn->purpose);
  777. if (compression || !plausible) {
  778. char *new_body = NULL;
  779. size_t new_len = 0;
  780. int guessed = detect_compression_method(body, body_len);
  781. if (compression <= 0 || guessed != compression) {
  782. /* Tell the user if we don't believe what we're told about compression.*/
  783. const char *description1, *description2;
  784. if (compression == ZLIB_METHOD)
  785. description1 = "as deflated";
  786. else if (compression == GZIP_METHOD)
  787. description1 = "as gzipped";
  788. else if (compression == 0)
  789. description1 = "as uncompressed";
  790. else
  791. description1 = "with an unknown Content-Encoding";
  792. if (guessed == ZLIB_METHOD)
  793. description2 = "deflated";
  794. else if (guessed == GZIP_METHOD)
  795. description2 = "gzipped";
  796. else if (!plausible)
  797. description2 = "confusing binary junk";
  798. else
  799. description2 = "uncompressed";
  800. log_fn(LOG_INFO, "HTTP body from server '%s:%d' was labeled %s, "
  801. "but it seems to be %s.%s",
  802. conn->address, conn->port, description1, description2,
  803. (compression>0 && guessed>0)?" Trying both.":"");
  804. }
  805. /* Try declared compression first if we can. */
  806. if (compression > 0)
  807. tor_gzip_uncompress(&new_body, &new_len, body, body_len, compression);
  808. /* Okay, if that didn't work, and we think that it was compressed
  809. * differently, try that. */
  810. if (!new_body && guessed > 0 && compression != guessed)
  811. tor_gzip_uncompress(&new_body, &new_len, body, body_len, guessed);
  812. /* If we're pretty sure that we have a compressed directory, and
  813. * we didn't manage to uncompress it, then warn and bail. */
  814. if (!plausible && !new_body) {
  815. log_fn(LOG_WARN, "Unable to decompress HTTP body (server '%s:%d').",
  816. conn->address, conn->port);
  817. tor_free(body); tor_free(headers); tor_free(reason);
  818. return -1;
  819. }
  820. if (new_body) {
  821. tor_free(body);
  822. body = new_body;
  823. body_len = new_len;
  824. }
  825. }
  826. if (conn->purpose == DIR_PURPOSE_FETCH_DIR) {
  827. /* fetch/process the directory to learn about new routers. */
  828. log_fn(LOG_INFO,"Received directory (size %d) from server '%s:%d'",
  829. (int)body_len, conn->address, conn->port);
  830. if (status_code == 503 || body_len == 0) {
  831. log_fn(LOG_INFO,"Empty directory; status %d (\"%s\") Ignoring.",
  832. status_code, reason);
  833. tor_free(body); tor_free(headers); tor_free(reason);
  834. return -1;
  835. }
  836. if (status_code != 200) {
  837. log_fn(LOG_WARN,"Received http status code %d (\"%s\") from server '%s:%d'. I'll try again soon.",
  838. status_code, reason, conn->address, conn->port);
  839. tor_free(body); tor_free(headers); tor_free(reason);
  840. return -1;
  841. }
  842. if (router_parse_directory(body) < 0) {
  843. log_fn(LOG_NOTICE,"I failed to parse the directory I fetched from '%s:%d'. Ignoring.", conn->address, conn->port);
  844. }
  845. #if 0
  846. if (router_load_routerlist_from_directory(body, NULL, !skewed, 0) < 0) {
  847. log_fn(LOG_NOTICE,"I failed to parse the directory I fetched from '%s:%d'. Ignoring.", conn->address, conn->port);
  848. tor_free(body); tor_free(headers); tor_free(reason);
  849. return -1;
  850. }
  851. /* do things we've been waiting to do */
  852. directory_has_arrived(time(NULL), conn->identity_digest);
  853. #endif
  854. }
  855. if (conn->purpose == DIR_PURPOSE_FETCH_RUNNING_LIST) {
  856. /* just update our list of running routers, if this list is new info */
  857. log_fn(LOG_INFO,"Received running-routers list (size %d)", (int)body_len);
  858. if (status_code != 200) {
  859. log_fn(LOG_WARN,"Received http status code %d (\"%s\") from server '%s:%d'. I'll try again soon.",
  860. status_code, reason, conn->address, conn->port);
  861. tor_free(body); tor_free(headers); tor_free(reason);
  862. return -1;
  863. }
  864. if (router_parse_runningrouters(body)<0) {
  865. log_fn(LOG_WARN,"Bad running-routers from server '%s:%d'. I'll try again soon.",
  866. conn->address, conn->port);
  867. tor_free(body); tor_free(headers); tor_free(reason);
  868. return -1;
  869. }
  870. #if 0
  871. if (!(rrs = router_parse_runningrouters(body, 1))) {
  872. log_fn(LOG_WARN, "Can't parse runningrouters list (server '%s:%d')",
  873. conn->address, conn->port);
  874. tor_free(body); tor_free(headers); tor_free(reason);
  875. return -1;
  876. }
  877. router_get_routerlist(&rl);
  878. if (rl) {
  879. routerlist_set_runningrouters(rl,rrs);
  880. helper_nodes_set_status_from_directory();
  881. } else {
  882. running_routers_free(rrs);
  883. }
  884. #endif
  885. }
  886. if (conn->purpose == DIR_PURPOSE_FETCH_NETWORKSTATUS) {
  887. smartlist_t *which = NULL;
  888. char *cp;
  889. log_fn(LOG_INFO,"Received networkstatus objects (size %d) from server '%s:%d'",(int) body_len, conn->address, conn->port);
  890. if (status_code != 200) {
  891. log_fn(LOG_WARN,"Received http status code %d (\"%s\") from server '%s:%d' while fetching \"/tor/status/%s\". I'll try again soon.",
  892. status_code, reason, conn->address, conn->port,
  893. conn->requested_resource);
  894. tor_free(body); tor_free(headers); tor_free(reason);
  895. connection_dir_download_networkstatus_failed(conn);
  896. return -1;
  897. }
  898. if (conn->requested_resource &&
  899. !strcmpstart(conn->requested_resource,"fp/")) {
  900. int n;
  901. which = smartlist_create();
  902. smartlist_split_string(which, conn->requested_resource+3, "+", 0, -1);
  903. n = smartlist_len(which);
  904. if (n && strlen(smartlist_get(which,n-1))==HEX_DIGEST_LEN+2)
  905. ((char*)smartlist_get(which,n-1))[HEX_DIGEST_LEN] = '\0';
  906. }
  907. cp = body;
  908. while (*cp) {
  909. char *next = strstr(cp, "\nnetwork-status-version");
  910. if (next)
  911. next[1] = '\0';
  912. if (router_set_networkstatus(cp, time(NULL), NS_FROM_DIR, which)<0)
  913. break;
  914. if (next) {
  915. next[1] = 'n';
  916. cp = next+1;
  917. }
  918. else
  919. break;
  920. }
  921. routers_update_all_from_networkstatus();/*launches router downloads*/
  922. directory_info_has_arrived(time(NULL),0);
  923. if (which) {
  924. if (smartlist_len(which)) {
  925. dir_networkstatus_download_failed(which);
  926. }
  927. SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
  928. smartlist_free(which);
  929. }
  930. }
  931. if (conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC) {
  932. smartlist_t *which = NULL;
  933. /* XXXX NM implement this. */
  934. log_fn(LOG_INFO,"Received server info (size %d) from server '%s:%d'",
  935. (int)body_len, conn->address, conn->port);
  936. if (status_code != 200) {
  937. log_fn(LOG_WARN,"Received http status code %d (\"%s\") from server '%s:%d' while fetching \"/tor/server/%s\". I'll try again soon.",
  938. status_code, reason, conn->address, conn->port,
  939. conn->requested_resource);
  940. tor_free(body); tor_free(headers); tor_free(reason);
  941. connection_dir_download_routerdesc_failed(conn);
  942. return -1;
  943. }
  944. if (conn->requested_resource &&
  945. !strcmpstart(conn->requested_resource,"fp/")) {
  946. int n;
  947. which = smartlist_create();
  948. smartlist_split_string(which, conn->requested_resource+3, "+", 0, -1);
  949. n = smartlist_len(which);
  950. if (n && strlen(smartlist_get(which,n-1))==HEX_DIGEST_LEN+2)
  951. ((char*)smartlist_get(which,n-1))[HEX_DIGEST_LEN] = '\0';
  952. }
  953. router_load_routers_from_string(body, 0, which);
  954. directory_info_has_arrived(time(NULL),0);
  955. if (which) {
  956. if (smartlist_len(which)) {
  957. dir_routerdesc_download_failed(which);
  958. }
  959. SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
  960. smartlist_free(which);
  961. }
  962. }
  963. if (conn->purpose == DIR_PURPOSE_UPLOAD_DIR) {
  964. switch (status_code) {
  965. case 200:
  966. log_fn(LOG_INFO,"eof (status 200) after uploading server descriptor: finished.");
  967. break;
  968. case 400:
  969. log_fn(LOG_WARN,"http status 400 (\"%s\") response from dirserver '%s:%d'. Please correct.", reason, conn->address, conn->port);
  970. break;
  971. case 403:
  972. log_fn(LOG_WARN,"http status 403 (\"%s\") response from dirserver '%s:%d'. 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-server.html", reason, conn->address, conn->port);
  973. break;
  974. default:
  975. log_fn(LOG_WARN,"http status %d (\"%s\") reason unexpected (server '%s:%d').", status_code, reason, conn->address, conn->port);
  976. break;
  977. }
  978. /* return 0 in all cases, since we don't want to mark any
  979. * dirservers down just because they don't like us. */
  980. }
  981. if (conn->purpose == DIR_PURPOSE_FETCH_RENDDESC) {
  982. log_fn(LOG_INFO,"Received rendezvous descriptor (size %d, status %d (\"%s\"))",
  983. (int)body_len, status_code, reason);
  984. switch (status_code) {
  985. case 200:
  986. if (rend_cache_store(body, body_len) < 0) {
  987. log_fn(LOG_WARN,"Failed to store rendezvous descriptor.");
  988. /* alice's ap_stream will notice when connection_mark_for_close
  989. * cleans it up */
  990. } else {
  991. /* success. notify pending connections about this. */
  992. conn->purpose = DIR_PURPOSE_HAS_FETCHED_RENDDESC;
  993. rend_client_desc_here(conn->rend_query);
  994. }
  995. break;
  996. case 404:
  997. /* not there. pending connections will be notified when
  998. * connection_mark_for_close cleans it up. */
  999. break;
  1000. case 400:
  1001. log_fn(LOG_WARN,"http status 400 (\"%s\"). Dirserver didn't like our rendezvous query?", reason);
  1002. break;
  1003. default:
  1004. log_fn(LOG_WARN,"http status %d (\"%s\") response unexpected (server '%s:%d').", status_code, reason, conn->address, conn->port);
  1005. break;
  1006. }
  1007. }
  1008. if (conn->purpose == DIR_PURPOSE_UPLOAD_RENDDESC) {
  1009. switch (status_code) {
  1010. case 200:
  1011. log_fn(LOG_INFO,"Uploading rendezvous descriptor: finished with status 200 (\"%s\")", reason);
  1012. break;
  1013. case 400:
  1014. log_fn(LOG_WARN,"http status 400 (\"%s\") response from dirserver '%s:%d'. Malformed rendezvous descriptor?", reason, conn->address, conn->port);
  1015. break;
  1016. default:
  1017. log_fn(LOG_WARN,"http status %d (\"%s\") response unexpected (server '%s:%d').", status_code, reason, conn->address, conn->port);
  1018. break;
  1019. }
  1020. }
  1021. tor_free(body); tor_free(headers); tor_free(reason);
  1022. return 0;
  1023. }
  1024. /** Called when a directory connection reaches EOF */
  1025. int
  1026. connection_dir_reached_eof(connection_t *conn)
  1027. {
  1028. int retval;
  1029. if (conn->state != DIR_CONN_STATE_CLIENT_READING) {
  1030. log_fn(LOG_INFO,"conn reached eof, not reading. Closing.");
  1031. connection_close_immediate(conn); /* it was an error; give up on flushing */
  1032. connection_mark_for_close(conn);
  1033. return -1;
  1034. }
  1035. retval = connection_dir_client_reached_eof(conn);
  1036. if (retval == 0) /* success */
  1037. conn->state = DIR_CONN_STATE_CLIENT_FINISHED;
  1038. connection_mark_for_close(conn);
  1039. return retval;
  1040. }
  1041. /** Read handler for directory connections. (That's connections <em>to</em>
  1042. * directory servers and connections <em>at</em> directory servers.)
  1043. */
  1044. int connection_dir_process_inbuf(connection_t *conn)
  1045. {
  1046. tor_assert(conn);
  1047. tor_assert(conn->type == CONN_TYPE_DIR);
  1048. /* Directory clients write, then read data until they receive EOF;
  1049. * directory servers read data until they get an HTTP command, then
  1050. * write their response (when it's finished flushing, they mark for
  1051. * close).
  1052. */
  1053. /* If we're on the dirserver side, look for a command. */
  1054. if (conn->state == DIR_CONN_STATE_SERVER_COMMAND_WAIT) {
  1055. if (directory_handle_command(conn) < 0) {
  1056. connection_mark_for_close(conn);
  1057. return -1;
  1058. }
  1059. return 0;
  1060. }
  1061. /* XXX for READ states, might want to make sure inbuf isn't too big */
  1062. log_fn(LOG_DEBUG,"Got data, not eof. Leaving on inbuf.");
  1063. return 0;
  1064. }
  1065. /** Create an http response for the client <b>conn</b> out of
  1066. * <b>status</b> and <b>reason_phrase</b>. Write it to <b>conn</b>.
  1067. */
  1068. static void
  1069. write_http_status_line(connection_t *conn, int status,
  1070. const char *reason_phrase)
  1071. {
  1072. char buf[256];
  1073. if (tor_snprintf(buf, sizeof(buf), "HTTP/1.0 %d %s\r\n\r\n",
  1074. status, reason_phrase) < 0) {
  1075. log_fn(LOG_WARN,"Bug: status line too long.");
  1076. return;
  1077. }
  1078. connection_write_to_buf(buf, strlen(buf), conn);
  1079. }
  1080. /** Helper function: return 1 if there are any dir conns of purpose
  1081. * <b>purpose</b> that are going elsewhere than our own ORPort/Dirport.
  1082. * Else return 0.
  1083. */
  1084. static int
  1085. already_fetching_directory(int purpose)
  1086. {
  1087. int i, n;
  1088. connection_t *conn;
  1089. connection_t **carray;
  1090. get_connection_array(&carray,&n);
  1091. for (i=0;i<n;i++) {
  1092. conn = carray[i];
  1093. if (conn->type == CONN_TYPE_DIR &&
  1094. conn->purpose == purpose &&
  1095. !conn->marked_for_close &&
  1096. !router_digest_is_me(conn->identity_digest))
  1097. return 1;
  1098. }
  1099. return 0;
  1100. }
  1101. /** Helper function: called when a dirserver gets a complete HTTP GET
  1102. * request. Look for a request for a directory or for a rendezvous
  1103. * service descriptor. On finding one, write a response into
  1104. * conn-\>outbuf. If the request is unrecognized, send a 400.
  1105. * Always return 0. */
  1106. static int
  1107. directory_handle_command_get(connection_t *conn, char *headers,
  1108. char *body, size_t body_len)
  1109. {
  1110. size_t dlen;
  1111. const char *cp;
  1112. char *url = NULL;
  1113. char tmp[8192];
  1114. char date[RFC1123_TIME_LEN+1];
  1115. log_fn(LOG_DEBUG,"Received GET command.");
  1116. conn->state = DIR_CONN_STATE_SERVER_WRITING;
  1117. if (parse_http_url(headers, &url) < 0) {
  1118. write_http_status_line(conn, 400, "Bad request");
  1119. return 0;
  1120. }
  1121. log_fn(LOG_INFO,"rewritten url as '%s'.", url);
  1122. if (!strcmp(url,"/tor/") || !strcmp(url,"/tor/dir.z")) { /* directory fetch */
  1123. int deflated = !strcmp(url,"/tor/dir.z");
  1124. dlen = dirserv_get_directory(&cp, deflated);
  1125. tor_free(url);
  1126. if (dlen == 0) {
  1127. log_fn(LOG_NOTICE,"Client asked for the mirrored directory, but we don't have a good one yet. Sending 503 Dir not available.");
  1128. write_http_status_line(conn, 503, "Directory unavailable");
  1129. /* try to get a new one now */
  1130. if (!already_fetching_directory(DIR_PURPOSE_FETCH_DIR))
  1131. directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL, 1);
  1132. return 0;
  1133. }
  1134. log_fn(LOG_DEBUG,"Dumping %sdirectory to client.",
  1135. deflated?"deflated ":"");
  1136. format_rfc1123_time(date, time(NULL));
  1137. 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",
  1138. date,
  1139. (int)dlen,
  1140. deflated?"deflate":"identity");
  1141. connection_write_to_buf(tmp, strlen(tmp), conn);
  1142. connection_write_to_buf(cp, dlen, conn);
  1143. return 0;
  1144. }
  1145. if (!strcmp(url,"/tor/running-routers") ||
  1146. !strcmp(url,"/tor/running-routers.z")) { /* running-routers fetch */
  1147. int deflated = !strcmp(url,"/tor/running-routers.z");
  1148. tor_free(url);
  1149. dlen = dirserv_get_runningrouters(&cp, deflated);
  1150. if (!dlen) { /* we failed to create/cache cp */
  1151. write_http_status_line(conn, 503, "Directory unavailable");
  1152. /* try to get a new one now */
  1153. if (!already_fetching_directory(DIR_PURPOSE_FETCH_RUNNING_LIST))
  1154. directory_get_from_dirserver(DIR_PURPOSE_FETCH_RUNNING_LIST, NULL, 1);
  1155. return 0;
  1156. }
  1157. format_rfc1123_time(date, time(NULL));
  1158. 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",
  1159. date,
  1160. (int)dlen,
  1161. deflated?"deflate":"identity");
  1162. connection_write_to_buf(tmp, strlen(tmp), conn);
  1163. connection_write_to_buf(cp, strlen(cp), conn);
  1164. return 0;
  1165. }
  1166. if (!strcmpstart(url,"/tor/status/")) {
  1167. /* v2 network status fetch. */
  1168. size_t url_len = strlen(url);
  1169. int deflated = !strcmp(url+url_len-2, ".z");
  1170. smartlist_t *dir_objs = smartlist_create();
  1171. const char *key = url + strlen("/tor/status/");
  1172. if (deflated)
  1173. url[url_len-2] = '\0';
  1174. if (dirserv_get_networkstatus_v2(dir_objs, key)) {
  1175. smartlist_free(dir_objs);
  1176. return 0;
  1177. }
  1178. tor_free(url);
  1179. if (!smartlist_len(dir_objs)) { /* we failed to create/cache cp */
  1180. write_http_status_line(conn, 503, "Network status object unavailable");
  1181. smartlist_free(dir_objs);
  1182. return 0;
  1183. }
  1184. dlen = 0;
  1185. SMARTLIST_FOREACH(dir_objs, cached_dir_t *, d,
  1186. dlen += deflated?d->dir_z_len:d->dir_len);
  1187. format_rfc1123_time(date, time(NULL));
  1188. 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",
  1189. date,
  1190. (int)dlen,
  1191. deflated?"deflate":"identity");
  1192. connection_write_to_buf(tmp, strlen(tmp), conn);
  1193. SMARTLIST_FOREACH(dir_objs, cached_dir_t *, d,
  1194. {
  1195. if (deflated)
  1196. connection_write_to_buf(d->dir_z, d->dir_z_len, conn);
  1197. else
  1198. connection_write_to_buf(d->dir, d->dir_len, conn);
  1199. });
  1200. smartlist_free(dir_objs);
  1201. return 0;
  1202. }
  1203. if (!strcmpstart(url,"/tor/server/")) {
  1204. size_t url_len = strlen(url);
  1205. int deflated = !strcmp(url+url_len-2, ".z");
  1206. smartlist_t *descs = smartlist_create();
  1207. if (deflated)
  1208. url[url_len-2] = '\0';
  1209. dirserv_get_routerdescs(descs, url);
  1210. tor_free(url);
  1211. if (!smartlist_len(descs)) {
  1212. write_http_status_line(conn, 400, "Servers unavailable.");
  1213. } else {
  1214. size_t len = 0;
  1215. format_rfc1123_time(date, time(NULL));
  1216. SMARTLIST_FOREACH(descs, routerinfo_t *, ri,
  1217. len += ri->signed_descriptor_len);
  1218. if (deflated) {
  1219. size_t compressed_len;
  1220. char *compressed;
  1221. char *inp = tor_malloc(len+smartlist_len(descs)+1);
  1222. char *cp = inp;
  1223. SMARTLIST_FOREACH(descs, routerinfo_t *, ri,
  1224. {
  1225. memcpy(cp, ri->signed_descriptor,
  1226. ri->signed_descriptor_len);
  1227. cp += ri->signed_descriptor_len;
  1228. *cp++ = '\n';
  1229. });
  1230. *cp = '\0';
  1231. /* XXXX NM This could be way more efficiently handled. */
  1232. if (tor_gzip_compress(&compressed, &compressed_len,
  1233. inp, cp-inp, ZLIB_METHOD)<0) {
  1234. tor_free(inp);
  1235. smartlist_free(descs);
  1236. return -1;
  1237. }
  1238. tor_free(inp);
  1239. 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",
  1240. date,
  1241. (int)compressed_len);
  1242. connection_write_to_buf(tmp, strlen(tmp), conn);
  1243. connection_write_to_buf(compressed, compressed_len, conn);
  1244. tor_free(compressed);
  1245. } else {
  1246. 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",
  1247. date,
  1248. (int)len);
  1249. connection_write_to_buf(tmp, strlen(tmp), conn);
  1250. SMARTLIST_FOREACH(descs, routerinfo_t *, ri,
  1251. connection_write_to_buf(ri->signed_descriptor,
  1252. ri->signed_descriptor_len,
  1253. conn));
  1254. }
  1255. }
  1256. smartlist_free(descs);
  1257. return 0;
  1258. }
  1259. if (!strcmpstart(url,"/tor/rendezvous/") ||
  1260. !strcmpstart(url,"/tor/rendezvous1/")) {
  1261. /* rendezvous descriptor fetch */
  1262. const char *descp;
  1263. size_t desc_len;
  1264. int versioned = !strcmpstart(url,"/tor/rendezvous1/");
  1265. const char *query = url+strlen("/tor/rendezvous/")+(versioned?1:0);
  1266. if (!authdir_mode(get_options())) {
  1267. /* We don't hand out rend descs. In fact, it could be a security
  1268. * risk, since rend_cache_lookup_desc() below would provide it
  1269. * if we're gone to the site recently, and 404 if we haven't.
  1270. *
  1271. * Reject. */
  1272. write_http_status_line(conn, 400, "Nonauthoritative directory does not not store rendezvous descriptors.");
  1273. tor_free(url);
  1274. return 0;
  1275. }
  1276. switch (rend_cache_lookup_desc(query, versioned?-1:0, &descp, &desc_len)) {
  1277. case 1: /* valid */
  1278. format_rfc1123_time(date, time(NULL));
  1279. 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",
  1280. date,
  1281. (int)desc_len); /* can't include descp here, because it's got nuls */
  1282. connection_write_to_buf(tmp, strlen(tmp), conn);
  1283. connection_write_to_buf(descp, desc_len, conn);
  1284. break;
  1285. case 0: /* well-formed but not present */
  1286. write_http_status_line(conn, 404, "Not found");
  1287. break;
  1288. case -1: /* not well-formed */
  1289. write_http_status_line(conn, 400, "Bad request");
  1290. break;
  1291. }
  1292. tor_free(url);
  1293. return 0;
  1294. }
  1295. /* we didn't recognize the url */
  1296. write_http_status_line(conn, 404, "Not found");
  1297. tor_free(url);
  1298. return 0;
  1299. }
  1300. /** Helper function: called when a dirserver gets a complete HTTP POST
  1301. * request. Look for an uploaded server descriptor or rendezvous
  1302. * service descriptor. On finding one, process it and write a
  1303. * response into conn-\>outbuf. If the request is unrecognized, send a
  1304. * 400. Always return 0. */
  1305. static int
  1306. directory_handle_command_post(connection_t *conn, char *headers,
  1307. char *body, size_t body_len)
  1308. {
  1309. const char *cp;
  1310. char *origin = NULL;
  1311. char *url = NULL;
  1312. log_fn(LOG_DEBUG,"Received POST command.");
  1313. conn->state = DIR_CONN_STATE_SERVER_WRITING;
  1314. if (!authdir_mode(get_options())) {
  1315. /* we just provide cached directories; we don't want to
  1316. * receive anything. */
  1317. write_http_status_line(conn, 400, "Nonauthoritative directory does not not store server descriptors.");
  1318. return 0;
  1319. }
  1320. if (parse_http_url(headers, &url) < 0) {
  1321. write_http_status_line(conn, 400, "Bad request");
  1322. return 0;
  1323. }
  1324. log_fn(LOG_INFO,"rewritten url as '%s'.", url);
  1325. origin = http_get_origin(headers, conn);
  1326. if (!strcmp(url,"/tor/")) { /* server descriptor post */
  1327. const char *msg;
  1328. int r = dirserv_add_descriptor(body, &msg);
  1329. tor_assert(msg);
  1330. if (r > 0)
  1331. dirserv_get_directory(&cp, 0); /* rebuild and write to disk */
  1332. switch (r) {
  1333. case -2:
  1334. case -1:
  1335. case 1:
  1336. log_fn(LOG_NOTICE,"Rejected descriptor from %s.", origin);
  1337. /* malformed descriptor, or something wrong */
  1338. write_http_status_line(conn, 400, msg);
  1339. break;
  1340. case 0: /* accepted but discarded */
  1341. case 2: /* accepted */
  1342. write_http_status_line(conn, 200, msg);
  1343. break;
  1344. }
  1345. goto done;
  1346. }
  1347. if (!strcmpstart(url,"/tor/rendezvous/publish")) {
  1348. /* rendezvous descriptor post */
  1349. if (rend_cache_store(body, body_len) < 0)
  1350. write_http_status_line(conn, 400, "Invalid service descriptor rejected");
  1351. else
  1352. write_http_status_line(conn, 200, "Service descriptor stored");
  1353. goto done;
  1354. }
  1355. /* we didn't recognize the url */
  1356. write_http_status_line(conn, 404, "Not found");
  1357. done:
  1358. tor_free(url);
  1359. tor_free(origin);
  1360. return 0;
  1361. }
  1362. /** Called when a dirserver receives data on a directory connection;
  1363. * looks for an HTTP request. If the request is complete, remove it
  1364. * from the inbuf, try to process it; otherwise, leave it on the
  1365. * buffer. Return a 0 on success, or -1 on error.
  1366. */
  1367. static int
  1368. directory_handle_command(connection_t *conn)
  1369. {
  1370. char *headers=NULL, *body=NULL;
  1371. size_t body_len=0;
  1372. int r;
  1373. tor_assert(conn);
  1374. tor_assert(conn->type == CONN_TYPE_DIR);
  1375. switch (fetch_from_buf_http(conn->inbuf,
  1376. &headers, MAX_HEADERS_SIZE,
  1377. &body, &body_len, MAX_BODY_SIZE)) {
  1378. case -1: /* overflow */
  1379. log_fn(LOG_WARN,"Invalid input from address '%s'. Closing.", conn->address);
  1380. return -1;
  1381. case 0:
  1382. log_fn(LOG_DEBUG,"command not all here yet.");
  1383. return 0;
  1384. /* case 1, fall through */
  1385. }
  1386. log_fn(LOG_DEBUG,"headers '%s', body '%s'.", headers, body);
  1387. if (!strncasecmp(headers,"GET",3))
  1388. r = directory_handle_command_get(conn, headers, body, body_len);
  1389. else if (!strncasecmp(headers,"POST",4))
  1390. r = directory_handle_command_post(conn, headers, body, body_len);
  1391. else {
  1392. log_fn(LOG_WARN,"Got headers '%s' with unknown command. Closing.", headers);
  1393. r = -1;
  1394. }
  1395. tor_free(headers); tor_free(body);
  1396. return r;
  1397. }
  1398. /** Write handler for directory connections; called when all data has
  1399. * been flushed. Close the connection or wait for a response as
  1400. * appropriate.
  1401. */
  1402. int
  1403. connection_dir_finished_flushing(connection_t *conn)
  1404. {
  1405. tor_assert(conn);
  1406. tor_assert(conn->type == CONN_TYPE_DIR);
  1407. switch (conn->state) {
  1408. case DIR_CONN_STATE_CLIENT_SENDING:
  1409. log_fn(LOG_DEBUG,"client finished sending command.");
  1410. conn->state = DIR_CONN_STATE_CLIENT_READING;
  1411. connection_stop_writing(conn);
  1412. return 0;
  1413. case DIR_CONN_STATE_SERVER_WRITING:
  1414. log_fn(LOG_INFO,"Finished writing server response. Closing.");
  1415. connection_mark_for_close(conn);
  1416. return 0;
  1417. default:
  1418. log_fn(LOG_WARN,"Bug: called in unexpected state %d.", conn->state);
  1419. tor_fragile_assert();
  1420. return -1;
  1421. }
  1422. return 0;
  1423. }
  1424. /** Connected handler for directory connections: begin sending data to the
  1425. * server */
  1426. int
  1427. connection_dir_finished_connecting(connection_t *conn)
  1428. {
  1429. tor_assert(conn);
  1430. tor_assert(conn->type == CONN_TYPE_DIR);
  1431. tor_assert(conn->state == DIR_CONN_STATE_CONNECTING);
  1432. log_fn(LOG_INFO,"Dir connection to router %s:%u established.",
  1433. conn->address,conn->port);
  1434. conn->state = DIR_CONN_STATE_CLIENT_SENDING; /* start flushing conn */
  1435. return 0;
  1436. }
  1437. /** Called when one or more networkstatus fetches have failed (with uppercase
  1438. * fingerprints listed in <b>fp</>). Mark those fingerprints has having
  1439. * failed once. */
  1440. static void
  1441. dir_networkstatus_download_failed(smartlist_t *failed)
  1442. {
  1443. SMARTLIST_FOREACH(failed, const char *, fp,
  1444. {
  1445. char digest[DIGEST_LEN];
  1446. trusted_dir_server_t *dir;
  1447. base16_decode(digest, DIGEST_LEN, fp, strlen(fp));
  1448. dir = router_get_trusteddirserver_by_digest(digest);
  1449. ++dir->n_networkstatus_failures;
  1450. });
  1451. }
  1452. /* DOCDOC */
  1453. static void
  1454. dir_routerdesc_download_failed(smartlist_t *failed)
  1455. {
  1456. /* XXXX writeme! Give up after a while! */
  1457. }