directory.c 62 KB

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