directory.c 61 KB

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