directory.c 60 KB

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