directory.c 61 KB

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