directory.c 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186
  1. /* Copyright 2001-2004 Roger Dingledine.
  2. * Copyright 2004-2007 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_send_command(dir_connection_t *conn,
  32. int purpose, int direct, const char *resource,
  33. const char *payload, size_t payload_len);
  34. static int directory_handle_command(dir_connection_t *conn);
  35. static int body_is_plausible(const char *body, size_t body_len, int purpose);
  36. static int purpose_is_private(uint8_t purpose);
  37. static char *http_get_header(const char *headers, const char *which);
  38. static void http_set_address_origin(const char *headers, connection_t *conn);
  39. static void connection_dir_download_networkstatus_failed(
  40. dir_connection_t *conn, int status_code);
  41. static void connection_dir_download_routerdesc_failed(dir_connection_t *conn);
  42. static void dir_networkstatus_download_failed(smartlist_t *failed,
  43. int status_code);
  44. static void dir_routerdesc_download_failed(smartlist_t *failed,
  45. int status_code);
  46. static void note_request(const char *key, size_t bytes);
  47. /********* START VARIABLES **********/
  48. /** How far in the future do we allow a directory server to tell us it is
  49. * before deciding that one of us has the wrong time? */
  50. #define ALLOW_DIRECTORY_TIME_SKEW (30*60)
  51. #define X_ADDRESS_HEADER "X-Your-Address-Is: "
  52. /** HTTP cache control: how long do we tell proxies they can cache each
  53. * kind of document we serve? */
  54. #define FULL_DIR_CACHE_LIFETIME (60*60)
  55. #define RUNNINGROUTERS_CACHE_LIFETIME (20*60)
  56. #define NETWORKSTATUS_CACHE_LIFETIME (5*60)
  57. #define ROUTERDESC_CACHE_LIFETIME (30*60)
  58. #define ROUTERDESC_BY_DIGEST_CACHE_LIFETIME (48*60*60)
  59. #define ROBOTS_CACHE_LIFETIME (24*60*60)
  60. /********* END VARIABLES ************/
  61. /** Return true iff the directory purpose 'purpose' must use an
  62. * anonymous connection to a directory. */
  63. static int
  64. purpose_is_private(uint8_t purpose)
  65. {
  66. if (get_options()->AllDirActionsPrivate)
  67. return 1;
  68. if (purpose == DIR_PURPOSE_FETCH_DIR ||
  69. purpose == DIR_PURPOSE_UPLOAD_DIR ||
  70. purpose == DIR_PURPOSE_FETCH_RUNNING_LIST ||
  71. purpose == DIR_PURPOSE_FETCH_NETWORKSTATUS ||
  72. purpose == DIR_PURPOSE_FETCH_SERVERDESC)
  73. return 0;
  74. return 1;
  75. }
  76. /** Start a connection to every suitable directory server, using
  77. * connection purpose 'purpose' and uploading the payload 'payload'
  78. * (length 'payload_len'). The purpose should be one of
  79. * 'DIR_PURPOSE_UPLOAD_DIR' or 'DIR_PURPOSE_UPLOAD_RENDDESC'.
  80. *
  81. * <b>type</b> specifies what sort of dir authorities (V1, V2,
  82. * HIDSERV, BRIDGE) we should upload to.
  83. *
  84. * DOCDOC extrainfo_len is in addition to payload_len.
  85. */
  86. void
  87. directory_post_to_dirservers(uint8_t purpose, authority_type_t type,
  88. const char *payload,
  89. size_t payload_len, size_t extrainfo_len)
  90. {
  91. int post_via_tor;
  92. smartlist_t *dirservers = router_get_trusted_dir_servers();
  93. tor_assert(dirservers);
  94. /* This tries dirservers which we believe to be down, but ultimately, that's
  95. * harmless, and we may as well err on the side of getting things uploaded.
  96. */
  97. SMARTLIST_FOREACH(dirservers, trusted_dir_server_t *, ds,
  98. {
  99. routerstatus_t *rs = &(ds->fake_status.status);
  100. local_routerstatus_t *lrs = router_get_combined_status_by_digest(
  101. ds->digest);
  102. int new_enough;
  103. size_t upload_len = payload_len;
  104. if (type == HIDSERV_AUTHORITY && !ds->is_hidserv_authority)
  105. continue;
  106. if (type == BRIDGE_AUTHORITY && !ds->is_bridge_authority)
  107. continue;
  108. if (type == V1_AUTHORITY && !ds->is_v1_authority)
  109. continue;
  110. if (type == V2_AUTHORITY && !ds->is_v2_authority)
  111. continue;
  112. if (purpose == DIR_PURPOSE_UPLOAD_DIR)
  113. ds->has_accepted_serverdesc = 0;
  114. new_enough = (lrs && lrs->status.version_supports_extrainfo_upload) ||
  115. (router_digest_version_as_new_as(ds->digest,
  116. "Tor 0.2.0.0-alpha-dev (r10070)"));
  117. if (extrainfo_len && new_enough) {
  118. upload_len += extrainfo_len;
  119. log_info(LD_DIR, "Uploading an extrainfo (length %d)",
  120. (int) extrainfo_len);
  121. }
  122. post_via_tor = purpose_is_private(purpose) ||
  123. !fascist_firewall_allows_address_dir(ds->addr, ds->dir_port);
  124. directory_initiate_command_routerstatus(rs, purpose, post_via_tor,
  125. NULL, payload, upload_len);
  126. });
  127. }
  128. /** Start a connection to a random running directory server, using
  129. * connection purpose 'purpose' and requesting 'resource'.
  130. * If <b>retry_if_no_servers</b>, then if all the possible servers seem
  131. * down, mark them up and try again.
  132. */
  133. void
  134. directory_get_from_dirserver(uint8_t purpose, const char *resource,
  135. int retry_if_no_servers)
  136. {
  137. routerstatus_t *rs = NULL;
  138. or_options_t *options = get_options();
  139. int prefer_authority = server_mode(options) && options->DirPort != 0;
  140. int directconn = !purpose_is_private(purpose);
  141. authority_type_t type;
  142. /* FFFF we could break this switch into its own function, and call
  143. * it elsewhere in directory.c. -RD */
  144. switch (purpose) {
  145. case DIR_PURPOSE_FETCH_NETWORKSTATUS:
  146. case DIR_PURPOSE_FETCH_SERVERDESC:
  147. type = V2_AUTHORITY;
  148. break;
  149. case DIR_PURPOSE_FETCH_DIR:
  150. case DIR_PURPOSE_FETCH_RUNNING_LIST:
  151. type = V1_AUTHORITY;
  152. break;
  153. case DIR_PURPOSE_FETCH_RENDDESC:
  154. type = HIDSERV_AUTHORITY;
  155. break;
  156. default:
  157. log_warn(LD_BUG, "Unexpected purpose %d", (int)purpose);
  158. return;
  159. }
  160. if (!options->FetchServerDescriptors && type != HIDSERV_AUTHORITY)
  161. return;
  162. if (directconn) {
  163. if (prefer_authority) {
  164. /* only ask authdirservers, and don't ask myself */
  165. rs = router_pick_trusteddirserver(type, 1, 1,
  166. retry_if_no_servers);
  167. }
  168. if (!rs) {
  169. /* anybody with a non-zero dirport will do */
  170. rs = router_pick_directory_server(1, 1, type==V2_AUTHORITY,
  171. retry_if_no_servers);
  172. if (!rs) {
  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. log_info(LD_DIR,
  183. "No router found for %s; falling back to dirserver list",
  184. which);
  185. rs = router_pick_trusteddirserver(type, 1, 1,
  186. retry_if_no_servers);
  187. if (!rs)
  188. directconn = 0; /* last resort: try routing it via Tor */
  189. }
  190. }
  191. }
  192. if (!directconn) {
  193. /* Never use fascistfirewall; we're going via Tor. */
  194. if (purpose == DIR_PURPOSE_FETCH_RENDDESC) {
  195. /* only ask hidserv authorities, any of them will do */
  196. rs = router_pick_trusteddirserver(HIDSERV_AUTHORITY, 0, 0,
  197. retry_if_no_servers);
  198. } else {
  199. /* anybody with a non-zero dirport will do. Disregard firewalls. */
  200. rs = router_pick_directory_server(1, 0, type == V2_AUTHORITY,
  201. retry_if_no_servers);
  202. /* If we have any hope of building an indirect conn, we know some router
  203. * descriptors. If (rs==NULL), we can't build circuits anyway, so
  204. * there's no point in falling back to the authorities in this case. */
  205. }
  206. }
  207. if (rs)
  208. directory_initiate_command_routerstatus(rs, purpose, !directconn,
  209. resource, NULL, 0);
  210. else {
  211. log_notice(LD_DIR,
  212. "While fetching directory info, "
  213. "no running dirservers known. Will try again later. "
  214. "(purpose %d)", purpose);
  215. if (!purpose_is_private(purpose)) {
  216. /* remember we tried them all and failed. */
  217. directory_all_unreachable(time(NULL));
  218. }
  219. }
  220. }
  221. /** Launch a new connection to the directory server <b>status</b> to upload or
  222. * download a server or rendezvous descriptor. <b>purpose</b> determines what
  223. * kind of directory connection we're launching, and must be one of
  224. * DIR_PURPOSE_{FETCH|UPLOAD}_{DIR|RENDDESC}.
  225. *
  226. * When uploading, <b>payload</b> and <b>payload_len</b> determine the content
  227. * of the HTTP post. Otherwise, <b>payload</b> should be NULL.
  228. *
  229. * When fetching a rendezvous descriptor, <b>resource</b> is the service ID we
  230. * want to fetch.
  231. */
  232. void
  233. directory_initiate_command_routerstatus(routerstatus_t *status,
  234. uint8_t purpose,
  235. int private_connection,
  236. const char *resource,
  237. const char *payload,
  238. size_t payload_len)
  239. {
  240. routerinfo_t *router;
  241. char address_buf[INET_NTOA_BUF_LEN+1];
  242. struct in_addr in;
  243. const char *address;
  244. if ((router = router_get_by_digest(status->identity_digest))) {
  245. address = router->address;
  246. } else {
  247. in.s_addr = htonl(status->addr);
  248. tor_inet_ntoa(&in, address_buf, sizeof(address_buf));
  249. address = address_buf;
  250. }
  251. directory_initiate_command(address, status->addr,
  252. status->or_port, status->dir_port,
  253. status->version_supports_begindir,
  254. status->identity_digest,
  255. purpose, private_connection, resource,
  256. payload, payload_len);
  257. }
  258. /** Return true iff <b>conn</b> is the client side of a directory connection
  259. * we launched to ourself in order to determine the reachability of our
  260. * dir_port. */
  261. static int
  262. directory_conn_is_self_reachability_test(dir_connection_t *conn)
  263. {
  264. if (conn->requested_resource &&
  265. !strcmpstart(conn->requested_resource,"authority")) {
  266. routerinfo_t *me = router_get_my_routerinfo();
  267. if (me &&
  268. router_digest_is_me(conn->identity_digest) &&
  269. me->addr == conn->_base.addr &&
  270. me->dir_port == conn->_base.port)
  271. return 1;
  272. }
  273. return 0;
  274. }
  275. /** Called when we are unable to complete the client's request to a directory
  276. * server due to a network error: Mark the router as down and try again if
  277. * possible.
  278. */
  279. void
  280. connection_dir_request_failed(dir_connection_t *conn)
  281. {
  282. if (directory_conn_is_self_reachability_test(conn)) {
  283. routerinfo_t *me = router_get_my_routerinfo();
  284. if (me)
  285. control_event_server_status(LOG_WARN,
  286. "REACHABILITY_FAILED DIRADDRESS=%s:%d",
  287. me->address, me->dir_port);
  288. return; /* this was a test fetch. don't retry. */
  289. }
  290. router_set_status(conn->identity_digest, 0); /* don't try him again */
  291. if (conn->_base.purpose == DIR_PURPOSE_FETCH_DIR ||
  292. conn->_base.purpose == DIR_PURPOSE_FETCH_RUNNING_LIST) {
  293. log_info(LD_DIR, "Giving up on directory server at '%s:%d'; retrying",
  294. conn->_base.address, conn->_base.port);
  295. directory_get_from_dirserver(conn->_base.purpose, NULL,
  296. 0 /* don't retry_if_no_servers */);
  297. } else if (conn->_base.purpose == DIR_PURPOSE_FETCH_NETWORKSTATUS) {
  298. log_info(LD_DIR, "Giving up on directory server at '%s'; retrying",
  299. conn->_base.address);
  300. connection_dir_download_networkstatus_failed(conn, -1);
  301. } else if (conn->_base.purpose == DIR_PURPOSE_FETCH_SERVERDESC) {
  302. log_info(LD_DIR, "Giving up on directory server at '%s'; retrying",
  303. conn->_base.address);
  304. connection_dir_download_routerdesc_failed(conn);
  305. }
  306. }
  307. /** Called when an attempt to download one or more network status
  308. * documents on connection <b>conn</b> failed. Decide whether to
  309. * retry the fetch now, later, or never.
  310. */
  311. static void
  312. connection_dir_download_networkstatus_failed(dir_connection_t *conn,
  313. int status_code)
  314. {
  315. if (!conn->requested_resource) {
  316. /* We never reached directory_send_command, which means that we never
  317. * opened a network connection. Either we're out of sockets, or the
  318. * network is down. Either way, retrying would be pointless. */
  319. return;
  320. }
  321. if (!strcmpstart(conn->requested_resource, "all")) {
  322. /* We're a non-authoritative directory cache; try again. Ignore status
  323. * code, since we don't want to keep trying forever in a tight loop
  324. * if all the authorities are shutting us out. */
  325. smartlist_t *trusted_dirs = router_get_trusted_dir_servers();
  326. SMARTLIST_FOREACH(trusted_dirs, trusted_dir_server_t *, ds,
  327. ++ds->n_networkstatus_failures);
  328. directory_get_from_dirserver(conn->_base.purpose, "all.z",
  329. 0 /* don't retry_if_no_servers */);
  330. } else if (!strcmpstart(conn->requested_resource, "fp/")) {
  331. /* We were trying to download by fingerprint; mark them all as having
  332. * failed, and possibly retry them later.*/
  333. smartlist_t *failed = smartlist_create();
  334. dir_split_resource_into_fingerprints(conn->requested_resource+3,
  335. failed, NULL, 0, 0);
  336. if (smartlist_len(failed)) {
  337. dir_networkstatus_download_failed(failed, status_code);
  338. SMARTLIST_FOREACH(failed, char *, cp, tor_free(cp));
  339. }
  340. smartlist_free(failed);
  341. }
  342. }
  343. /** Called when an attempt to download one or more router descriptors
  344. * on connection <b>conn</b> failed.
  345. */
  346. static void
  347. connection_dir_download_routerdesc_failed(dir_connection_t *conn)
  348. {
  349. /* No need to increment the failure count for routerdescs, since
  350. * it's not their fault. */
  351. /* No need to relaunch descriptor downloads here: we already do it
  352. * every 10 seconds (DESCRIPTOR_RETRY_INTERVAL) in main.c. */
  353. (void) conn;
  354. }
  355. /** Helper for directory_initiate_command_(router|trusted_dir): send the
  356. * command to a server whose address is <b>address</b>, whose IP is
  357. * <b>addr</b>, whose directory port is <b>dir_port</b>, whose tor version
  358. * <b>supports_begindir</b>, and whose identity key digest is
  359. * <b>digest</b>. */
  360. void
  361. directory_initiate_command(const char *address, uint32_t addr,
  362. uint16_t or_port, uint16_t dir_port,
  363. int supports_begindir,
  364. const char *digest, uint8_t purpose,
  365. int private_connection, const char *resource,
  366. const char *payload, size_t payload_len)
  367. {
  368. dir_connection_t *conn;
  369. or_options_t *options = get_options();
  370. int want_to_tunnel = options->TunnelDirConns && supports_begindir &&
  371. !private_connection && or_port &&
  372. fascist_firewall_allows_address_or(addr, or_port);
  373. tor_assert(address);
  374. tor_assert(addr);
  375. tor_assert(dir_port);
  376. tor_assert(digest);
  377. log_debug(LD_DIR, "private %d, want_to_tunnel %d.",
  378. private_connection, want_to_tunnel);
  379. switch (purpose) {
  380. case DIR_PURPOSE_FETCH_DIR:
  381. log_debug(LD_DIR,"initiating directory fetch");
  382. break;
  383. case DIR_PURPOSE_FETCH_RENDDESC:
  384. log_debug(LD_DIR,"initiating hidden-service descriptor fetch");
  385. break;
  386. case DIR_PURPOSE_UPLOAD_DIR:
  387. log_debug(LD_OR,"initiating server descriptor upload");
  388. break;
  389. case DIR_PURPOSE_UPLOAD_RENDDESC:
  390. log_debug(LD_REND,"initiating hidden-service descriptor upload");
  391. break;
  392. case DIR_PURPOSE_FETCH_RUNNING_LIST:
  393. log_debug(LD_DIR,"initiating running-routers fetch");
  394. break;
  395. case DIR_PURPOSE_FETCH_NETWORKSTATUS:
  396. log_debug(LD_DIR,"initiating network-status fetch");
  397. break;
  398. case DIR_PURPOSE_FETCH_SERVERDESC:
  399. log_debug(LD_DIR,"initiating server descriptor fetch");
  400. break;
  401. default:
  402. log_err(LD_BUG, "Unrecognized directory connection purpose.");
  403. tor_assert(0);
  404. }
  405. conn = TO_DIR_CONN(connection_new(CONN_TYPE_DIR));
  406. /* set up conn so it's got all the data we need to remember */
  407. conn->_base.addr = addr;
  408. conn->_base.port = want_to_tunnel ? or_port : dir_port;
  409. conn->_base.address = tor_strdup(address);
  410. memcpy(conn->identity_digest, digest, DIGEST_LEN);
  411. conn->_base.purpose = purpose;
  412. /* give it an initial state */
  413. conn->_base.state = DIR_CONN_STATE_CONNECTING;
  414. if (!private_connection && !want_to_tunnel) {
  415. /* then we want to connect directly */
  416. conn->dirconn_direct = 1;
  417. if (options->HttpProxy) {
  418. addr = options->HttpProxyAddr;
  419. dir_port = options->HttpProxyPort;
  420. }
  421. switch (connection_connect(TO_CONN(conn), conn->_base.address, addr,
  422. dir_port)) {
  423. case -1:
  424. connection_dir_request_failed(conn); /* retry if we want */
  425. connection_free(TO_CONN(conn));
  426. return;
  427. case 1:
  428. /* start flushing conn */
  429. conn->_base.state = DIR_CONN_STATE_CLIENT_SENDING;
  430. /* fall through */
  431. case 0:
  432. /* queue the command on the outbuf */
  433. directory_send_command(conn, purpose, 1, resource,
  434. payload, payload_len);
  435. connection_watch_events(TO_CONN(conn), EV_READ | EV_WRITE);
  436. /* writable indicates finish, readable indicates broken link,
  437. error indicates broken link in windowsland. */
  438. }
  439. } else { /* we want to connect via tor */
  440. edge_connection_t *linked_conn;
  441. /* make an AP connection
  442. * populate it and add it at the right state
  443. * hook up both sides
  444. */
  445. conn->dirconn_direct = 0;
  446. linked_conn =
  447. connection_ap_make_bridge(conn->_base.address, conn->_base.port,
  448. digest,
  449. private_connection ?
  450. SOCKS_COMMAND_CONNECT :
  451. SOCKS_COMMAND_CONNECT_DIR);
  452. if (!linked_conn) {
  453. log_warn(LD_NET,"Making AP bridge to dirserver failed.");
  454. connection_mark_for_close(TO_CONN(conn));
  455. return;
  456. }
  457. connection_link_connections(TO_CONN(conn), TO_CONN(linked_conn));
  458. if (connection_add(TO_CONN(conn)) < 0) {
  459. log_warn(LD_NET,"Unable to add AP bridge to dirserver.");
  460. connection_mark_for_close(TO_CONN(conn));
  461. return;
  462. }
  463. conn->_base.state = DIR_CONN_STATE_CLIENT_SENDING;
  464. /* queue the command on the outbuf */
  465. directory_send_command(conn, purpose, 0, resource,
  466. payload, payload_len);
  467. connection_watch_events(TO_CONN(conn), EV_READ | EV_WRITE);
  468. connection_start_reading(TO_CONN(linked_conn));
  469. }
  470. }
  471. /** Queue an appropriate HTTP command on conn-\>outbuf. The other args
  472. * are as in directory_initiate_command.
  473. */
  474. static void
  475. directory_send_command(dir_connection_t *conn,
  476. int purpose, int direct, const char *resource,
  477. const char *payload, size_t payload_len)
  478. {
  479. char proxystring[256];
  480. char proxyauthstring[256];
  481. char hoststring[128];
  482. char *url;
  483. char request[8192];
  484. const char *httpcommand = NULL;
  485. size_t len;
  486. tor_assert(conn);
  487. tor_assert(conn->_base.type == CONN_TYPE_DIR);
  488. tor_free(conn->requested_resource);
  489. if (resource)
  490. conn->requested_resource = tor_strdup(resource);
  491. /* come up with a string for which Host: we want */
  492. if (conn->_base.port == 80) {
  493. strlcpy(hoststring, conn->_base.address, sizeof(hoststring));
  494. } else {
  495. tor_snprintf(hoststring, sizeof(hoststring),"%s:%d",
  496. conn->_base.address, conn->_base.port);
  497. }
  498. /* come up with some proxy lines, if we're using one. */
  499. if (direct && get_options()->HttpProxy) {
  500. char *base64_authenticator=NULL;
  501. const char *authenticator = get_options()->HttpProxyAuthenticator;
  502. tor_snprintf(proxystring, sizeof(proxystring),"http://%s", hoststring);
  503. if (authenticator) {
  504. base64_authenticator = alloc_http_authenticator(authenticator);
  505. if (!base64_authenticator)
  506. log_warn(LD_BUG, "Encoding http authenticator failed");
  507. }
  508. if (base64_authenticator) {
  509. tor_snprintf(proxyauthstring, sizeof(proxyauthstring),
  510. "\r\nProxy-Authorization: Basic %s",
  511. base64_authenticator);
  512. tor_free(base64_authenticator);
  513. } else {
  514. proxyauthstring[0] = 0;
  515. }
  516. } else {
  517. proxystring[0] = 0;
  518. proxyauthstring[0] = 0;
  519. }
  520. switch (purpose) {
  521. case DIR_PURPOSE_FETCH_DIR:
  522. tor_assert(!resource);
  523. tor_assert(!payload);
  524. httpcommand = "GET";
  525. url = tor_strdup("/tor/dir.z");
  526. break;
  527. case DIR_PURPOSE_FETCH_RUNNING_LIST:
  528. tor_assert(!resource);
  529. tor_assert(!payload);
  530. httpcommand = "GET";
  531. url = tor_strdup("/tor/running-routers");
  532. break;
  533. case DIR_PURPOSE_FETCH_NETWORKSTATUS:
  534. httpcommand = "GET";
  535. len = strlen(resource)+32;
  536. url = tor_malloc(len);
  537. tor_snprintf(url, len, "/tor/status/%s", resource);
  538. break;
  539. case DIR_PURPOSE_FETCH_SERVERDESC:
  540. httpcommand = "GET";
  541. len = strlen(resource)+32;
  542. url = tor_malloc(len);
  543. tor_snprintf(url, len, "/tor/server/%s", resource);
  544. break;
  545. case DIR_PURPOSE_UPLOAD_DIR:
  546. tor_assert(!resource);
  547. tor_assert(payload);
  548. httpcommand = "POST";
  549. url = tor_strdup("/tor/");
  550. break;
  551. case DIR_PURPOSE_FETCH_RENDDESC:
  552. tor_assert(resource);
  553. tor_assert(!payload);
  554. /* this must be true or we wouldn't be doing the lookup */
  555. tor_assert(strlen(resource) <= REND_SERVICE_ID_LEN);
  556. /* This breaks the function abstraction. */
  557. strlcpy(conn->rend_query, resource, sizeof(conn->rend_query));
  558. httpcommand = "GET";
  559. /* Request the most recent versioned descriptor. */
  560. // (XXXX We were going to switch this to fetch rendezvous1 descriptors,
  561. // but that never got testing, and it wasn't a good design.)
  562. len = strlen(resource)+32;
  563. url = tor_malloc(len);
  564. tor_snprintf(url, len, "/tor/rendezvous/%s", resource);
  565. break;
  566. case DIR_PURPOSE_UPLOAD_RENDDESC:
  567. tor_assert(!resource);
  568. tor_assert(payload);
  569. httpcommand = "POST";
  570. url = tor_strdup("/tor/rendezvous/publish");
  571. break;
  572. default:
  573. tor_assert(0);
  574. return;
  575. }
  576. if (strlen(proxystring) + strlen(url) >= 4096) {
  577. log_warn(LD_BUG,
  578. "Squid does not like URLs longer than 4095 bytes, this "
  579. "one is %d bytes long: %s%s",
  580. (int)(strlen(proxystring) + strlen(url)), proxystring, url);
  581. }
  582. tor_snprintf(request, sizeof(request), "%s %s", httpcommand, proxystring);
  583. connection_write_to_buf(request, strlen(request), TO_CONN(conn));
  584. connection_write_to_buf(url, strlen(url), TO_CONN(conn));
  585. tor_free(url);
  586. if (!strcmp(httpcommand, "GET") && !payload) {
  587. tor_snprintf(request, sizeof(request),
  588. " HTTP/1.0\r\nHost: %s%s\r\n\r\n",
  589. hoststring,
  590. proxyauthstring);
  591. } else {
  592. tor_snprintf(request, sizeof(request),
  593. " HTTP/1.0\r\nContent-Length: %lu\r\nHost: %s%s\r\n\r\n",
  594. payload ? (unsigned long)payload_len : 0,
  595. hoststring,
  596. proxyauthstring);
  597. }
  598. connection_write_to_buf(request, strlen(request), TO_CONN(conn));
  599. if (payload) {
  600. /* then send the payload afterwards too */
  601. connection_write_to_buf(payload, payload_len, TO_CONN(conn));
  602. }
  603. }
  604. /** Parse an HTTP request string <b>headers</b> of the form
  605. * \verbatim
  606. * "\%s [http[s]://]\%s HTTP/1..."
  607. * \endverbatim
  608. * If it's well-formed, strdup the second \%s into *<b>url</b>, and
  609. * nul-terminate it. If the url doesn't start with "/tor/", rewrite it
  610. * so it does. Return 0.
  611. * Otherwise, return -1.
  612. */
  613. static int
  614. parse_http_url(const char *headers, char **url)
  615. {
  616. char *s, *start, *tmp;
  617. s = (char *)eat_whitespace_no_nl(headers);
  618. if (!*s) return -1;
  619. s = (char *)find_whitespace(s); /* get past GET/POST */
  620. if (!*s) return -1;
  621. s = (char *)eat_whitespace_no_nl(s);
  622. if (!*s) return -1;
  623. start = s; /* this is it, assuming it's valid */
  624. s = (char *)find_whitespace(start);
  625. if (!*s) return -1;
  626. /* tolerate the http[s] proxy style of putting the hostname in the url */
  627. if (s-start >= 4 && !strcmpstart(start,"http")) {
  628. tmp = start + 4;
  629. if (*tmp == 's')
  630. tmp++;
  631. if (s-tmp >= 3 && !strcmpstart(tmp,"://")) {
  632. tmp = strchr(tmp+3, '/');
  633. if (tmp && tmp < s) {
  634. log_debug(LD_DIR,"Skipping over 'http[s]://hostname' string");
  635. start = tmp;
  636. }
  637. }
  638. }
  639. if (s-start < 5 || strcmpstart(start,"/tor/")) { /* need to rewrite it */
  640. *url = tor_malloc(s - start + 5);
  641. strlcpy(*url,"/tor", s-start+5);
  642. strlcat((*url)+4, start, s-start+1);
  643. } else {
  644. *url = tor_strndup(start, s-start);
  645. }
  646. return 0;
  647. }
  648. /** Return a copy of the first HTTP header in <b>headers</b> whose key is
  649. * <b>which</b>. The key should be given with a terminating colon and space;
  650. * this function copies everything after, up to but not including the
  651. * following \\r\\n. */
  652. static char *
  653. http_get_header(const char *headers, const char *which)
  654. {
  655. const char *cp = headers;
  656. while (cp) {
  657. if (!strcmpstart(cp, which)) {
  658. char *eos;
  659. cp += strlen(which);
  660. if ((eos = strchr(cp,'\r')))
  661. return tor_strndup(cp, eos-cp);
  662. else
  663. return tor_strdup(cp);
  664. }
  665. cp = strchr(cp, '\n');
  666. if (cp)
  667. ++cp;
  668. }
  669. return NULL;
  670. }
  671. /** If <b>headers</b> indicates that a proxy was involved, then rewrite
  672. * <b>conn</b>-\>address to describe our best guess of the address that
  673. * originated this HTTP request. */
  674. static void
  675. http_set_address_origin(const char *headers, connection_t *conn)
  676. {
  677. char *fwd;
  678. fwd = http_get_header(headers, "Forwarded-For: ");
  679. if (!fwd)
  680. fwd = http_get_header(headers, "X-Forwarded-For: ");
  681. if (fwd) {
  682. struct in_addr in;
  683. if (!tor_inet_aton(fwd, &in) || is_internal_IP(ntohl(in.s_addr), 0)) {
  684. log_debug(LD_DIR, "Ignoring unrecognized or internal IP %s",
  685. escaped(fwd));
  686. tor_free(fwd);
  687. return;
  688. }
  689. tor_free(conn->address);
  690. conn->address = tor_strdup(fwd);
  691. tor_free(fwd);
  692. }
  693. }
  694. /** Parse an HTTP response string <b>headers</b> of the form
  695. * \verbatim
  696. * "HTTP/1.\%d \%d\%s\r\n...".
  697. * \endverbatim
  698. *
  699. * If it's well-formed, assign the status code to *<b>code</b> and
  700. * return 0. Otherwise, return -1.
  701. *
  702. * On success: If <b>date</b> is provided, set *date to the Date
  703. * header in the http headers, or 0 if no such header is found. If
  704. * <b>compression</b> is provided, set *<b>compression</b> to the
  705. * compression method given in the Content-Encoding header, or 0 if no
  706. * such header is found, or -1 if the value of the header is not
  707. * recognized. If <b>reason</b> is provided, strdup the reason string
  708. * into it.
  709. */
  710. int
  711. parse_http_response(const char *headers, int *code, time_t *date,
  712. compress_method_t *compression, char **reason)
  713. {
  714. int n1, n2;
  715. char datestr[RFC1123_TIME_LEN+1];
  716. smartlist_t *parsed_headers;
  717. tor_assert(headers);
  718. tor_assert(code);
  719. while (TOR_ISSPACE(*headers)) headers++; /* tolerate leading whitespace */
  720. if (sscanf(headers, "HTTP/1.%d %d", &n1, &n2) < 2 ||
  721. (n1 != 0 && n1 != 1) ||
  722. (n2 < 100 || n2 >= 600)) {
  723. log_warn(LD_HTTP,"Failed to parse header %s",escaped(headers));
  724. return -1;
  725. }
  726. *code = n2;
  727. parsed_headers = smartlist_create();
  728. smartlist_split_string(parsed_headers, headers, "\n",
  729. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  730. if (reason) {
  731. smartlist_t *status_line_elements = smartlist_create();
  732. tor_assert(smartlist_len(parsed_headers));
  733. smartlist_split_string(status_line_elements,
  734. smartlist_get(parsed_headers, 0),
  735. " ", SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 3);
  736. tor_assert(smartlist_len(status_line_elements) <= 3);
  737. if (smartlist_len(status_line_elements) == 3) {
  738. *reason = smartlist_get(status_line_elements, 2);
  739. smartlist_set(status_line_elements, 2, NULL); /* Prevent free */
  740. }
  741. SMARTLIST_FOREACH(status_line_elements, char *, cp, tor_free(cp));
  742. smartlist_free(status_line_elements);
  743. }
  744. if (date) {
  745. *date = 0;
  746. SMARTLIST_FOREACH(parsed_headers, const char *, s,
  747. if (!strcmpstart(s, "Date: ")) {
  748. strlcpy(datestr, s+6, sizeof(datestr));
  749. /* This will do nothing on failure, so we don't need to check
  750. the result. We shouldn't warn, since there are many other valid
  751. date formats besides the one we use. */
  752. parse_rfc1123_time(datestr, date);
  753. break;
  754. });
  755. }
  756. if (compression) {
  757. const char *enc = NULL;
  758. SMARTLIST_FOREACH(parsed_headers, const char *, s,
  759. if (!strcmpstart(s, "Content-Encoding: ")) {
  760. enc = s+18; break;
  761. });
  762. if (!enc || !strcmp(enc, "identity")) {
  763. *compression = NO_METHOD;
  764. } else if (!strcmp(enc, "deflate") || !strcmp(enc, "x-deflate")) {
  765. *compression = ZLIB_METHOD;
  766. } else if (!strcmp(enc, "gzip") || !strcmp(enc, "x-gzip")) {
  767. *compression = GZIP_METHOD;
  768. } else {
  769. log_info(LD_HTTP, "Unrecognized content encoding: %s. Trying to deal.",
  770. escaped(enc));
  771. *compression = UNKNOWN_METHOD;
  772. }
  773. }
  774. SMARTLIST_FOREACH(parsed_headers, char *, s, tor_free(s));
  775. smartlist_free(parsed_headers);
  776. return 0;
  777. }
  778. /** Return true iff <b>body</b> doesn't start with a plausible router or
  779. * running-list or directory opening. This is a sign of possible compression.
  780. **/
  781. static int
  782. body_is_plausible(const char *body, size_t len, int purpose)
  783. {
  784. int i;
  785. if (len == 0)
  786. return 1; /* empty bodies don't need decompression */
  787. if (len < 32)
  788. return 0;
  789. if (purpose != DIR_PURPOSE_FETCH_RENDDESC) {
  790. if (!strcmpstart(body,"router") ||
  791. !strcmpstart(body,"signed-directory") ||
  792. !strcmpstart(body,"network-status") ||
  793. !strcmpstart(body,"running-routers"))
  794. return 1;
  795. for (i=0;i<32;++i) {
  796. if (!TOR_ISPRINT(body[i]) && !TOR_ISSPACE(body[i]))
  797. return 0;
  798. }
  799. return 1;
  800. } else {
  801. return 1;
  802. }
  803. }
  804. /** We are a client, and we've finished reading the server's
  805. * response. Parse and it and act appropriately.
  806. *
  807. * If we're still happy with using this directory server in the future, return
  808. * 0. Otherwise return -1; and the caller should consider trying the request
  809. * again.
  810. *
  811. * The caller will take care of marking the connection for close.
  812. */
  813. static int
  814. connection_dir_client_reached_eof(dir_connection_t *conn)
  815. {
  816. char *body;
  817. char *headers;
  818. char *reason = NULL;
  819. size_t body_len=0, orig_len=0;
  820. int status_code;
  821. time_t date_header=0;
  822. int delta;
  823. compress_method_t compression;
  824. int plausible;
  825. int skewed=0;
  826. int allow_partial = conn->_base.purpose == DIR_PURPOSE_FETCH_SERVERDESC;
  827. int was_compressed=0;
  828. time_t now = time(NULL);
  829. switch (fetch_from_buf_http(conn->_base.inbuf,
  830. &headers, MAX_HEADERS_SIZE,
  831. &body, &body_len, MAX_DIR_DL_SIZE,
  832. allow_partial)) {
  833. case -1: /* overflow */
  834. log_warn(LD_PROTOCOL,
  835. "'fetch' response too large (server '%s:%d'). Closing.",
  836. conn->_base.address, conn->_base.port);
  837. return -1;
  838. case 0:
  839. log_info(LD_HTTP,
  840. "'fetch' response not all here, but we're at eof. Closing.");
  841. return -1;
  842. /* case 1, fall through */
  843. }
  844. orig_len = body_len;
  845. if (parse_http_response(headers, &status_code, &date_header,
  846. &compression, &reason) < 0) {
  847. log_warn(LD_HTTP,"Unparseable headers (server '%s:%d'). Closing.",
  848. conn->_base.address, conn->_base.port);
  849. tor_free(body); tor_free(headers);
  850. return -1;
  851. }
  852. if (!reason) reason = tor_strdup("[no reason given]");
  853. log_debug(LD_DIR,
  854. "Received response from directory server '%s:%d': %d %s",
  855. conn->_base.address, conn->_base.port, status_code,
  856. escaped(reason));
  857. /* now check if it's got any hints for us about our IP address. */
  858. if (conn->dirconn_direct) {
  859. char *guess = http_get_header(headers, X_ADDRESS_HEADER);
  860. if (guess) {
  861. router_new_address_suggestion(guess);
  862. tor_free(guess);
  863. }
  864. }
  865. if (date_header > 0) {
  866. /* The date header was written very soon after we sent our request,
  867. * so compute the skew as the difference between sending the request
  868. * and the date header. (We used to check now-date_header, but that's
  869. * inaccurate if we spend a lot of time downloading.)
  870. */
  871. delta = conn->_base.timestamp_lastwritten - date_header;
  872. if (abs(delta)>ALLOW_DIRECTORY_TIME_SKEW) {
  873. int trusted = router_digest_is_trusted_dir(conn->identity_digest);
  874. log_fn(trusted ? LOG_WARN : LOG_INFO,
  875. LD_HTTP,
  876. "Received directory with skewed time (server '%s:%d'): "
  877. "we are %d minutes %s, or the directory is %d minutes %s.",
  878. conn->_base.address, conn->_base.port,
  879. abs(delta)/60, delta>0 ? "ahead" : "behind",
  880. abs(delta)/60, delta>0 ? "behind" : "ahead");
  881. skewed = 1; /* don't check the recommended-versions line */
  882. control_event_general_status(trusted ? LOG_WARN : LOG_NOTICE,
  883. "CLOCK_SKEW SKEW=%d SOURCE=DIRSERV:%s:%d",
  884. delta, conn->_base.address, conn->_base.port);
  885. } else {
  886. log_debug(LD_HTTP, "Time on received directory is within tolerance; "
  887. "we are %d seconds skewed. (That's okay.)", delta);
  888. }
  889. }
  890. (void) skewed; /* skewed isn't used yet. */
  891. if (status_code == 503) {
  892. local_routerstatus_t *rs;
  893. trusted_dir_server_t *ds;
  894. log_info(LD_DIR,"Received http status code %d (%s) from server "
  895. "'%s:%d'. I'll try again soon.",
  896. status_code, escaped(reason), conn->_base.address,
  897. conn->_base.port);
  898. if ((rs = router_get_combined_status_by_digest(conn->identity_digest)))
  899. rs->last_dir_503_at = now;
  900. if ((ds = router_get_trusteddirserver_by_digest(conn->identity_digest)))
  901. ds->fake_status.last_dir_503_at = now;
  902. tor_free(body); tor_free(headers); tor_free(reason);
  903. return -1;
  904. }
  905. plausible = body_is_plausible(body, body_len, conn->_base.purpose);
  906. if (compression != NO_METHOD || !plausible) {
  907. char *new_body = NULL;
  908. size_t new_len = 0;
  909. compress_method_t guessed = detect_compression_method(body, body_len);
  910. if (compression == UNKNOWN_METHOD || guessed != compression) {
  911. /* Tell the user if we don't believe what we're told about compression.*/
  912. const char *description1, *description2;
  913. if (compression == ZLIB_METHOD)
  914. description1 = "as deflated";
  915. else if (compression == GZIP_METHOD)
  916. description1 = "as gzipped";
  917. else if (compression == NO_METHOD)
  918. description1 = "as uncompressed";
  919. else
  920. description1 = "with an unknown Content-Encoding";
  921. if (guessed == ZLIB_METHOD)
  922. description2 = "deflated";
  923. else if (guessed == GZIP_METHOD)
  924. description2 = "gzipped";
  925. else if (!plausible)
  926. description2 = "confusing binary junk";
  927. else
  928. description2 = "uncompressed";
  929. log_info(LD_HTTP, "HTTP body from server '%s:%d' was labeled %s, "
  930. "but it seems to be %s.%s",
  931. conn->_base.address, conn->_base.port, description1,
  932. description2,
  933. (compression>0 && guessed>0)?" Trying both.":"");
  934. }
  935. /* Try declared compression first if we can. */
  936. if (compression == GZIP_METHOD || compression == ZLIB_METHOD)
  937. tor_gzip_uncompress(&new_body, &new_len, body, body_len, compression,
  938. !allow_partial, LOG_PROTOCOL_WARN);
  939. /* Okay, if that didn't work, and we think that it was compressed
  940. * differently, try that. */
  941. if (!new_body &&
  942. (guessed == GZIP_METHOD || guessed == ZLIB_METHOD) &&
  943. compression != guessed)
  944. tor_gzip_uncompress(&new_body, &new_len, body, body_len, guessed,
  945. !allow_partial, LOG_PROTOCOL_WARN);
  946. /* If we're pretty sure that we have a compressed directory, and
  947. * we didn't manage to uncompress it, then warn and bail. */
  948. if (!plausible && !new_body) {
  949. log_fn(LOG_PROTOCOL_WARN, LD_HTTP,
  950. "Unable to decompress HTTP body (server '%s:%d').",
  951. conn->_base.address, conn->_base.port);
  952. tor_free(body); tor_free(headers); tor_free(reason);
  953. return -1;
  954. }
  955. if (new_body) {
  956. tor_free(body);
  957. body = new_body;
  958. body_len = new_len;
  959. was_compressed = 1;
  960. }
  961. }
  962. if (conn->_base.purpose == DIR_PURPOSE_FETCH_DIR) {
  963. /* fetch/process the directory to cache it. */
  964. log_info(LD_DIR,"Received directory (size %d) from server '%s:%d'",
  965. (int)body_len, conn->_base.address, conn->_base.port);
  966. if (status_code != 200) {
  967. log_warn(LD_DIR,"Received http status code %d (%s) from server "
  968. "'%s:%d' while fetching directory. I'll try again soon.",
  969. status_code, escaped(reason), conn->_base.address,
  970. conn->_base.port);
  971. tor_free(body); tor_free(headers); tor_free(reason);
  972. return -1;
  973. }
  974. if (router_parse_directory(body) < 0) {
  975. log_notice(LD_DIR,"I failed to parse the directory I fetched from "
  976. "'%s:%d'. Ignoring.", conn->_base.address, conn->_base.port);
  977. }
  978. note_request(was_compressed?"dl/dir.z":"dl/dir", orig_len);
  979. }
  980. if (conn->_base.purpose == DIR_PURPOSE_FETCH_RUNNING_LIST) {
  981. /* just update our list of running routers, if this list is new info */
  982. log_info(LD_DIR,"Received running-routers list (size %d)", (int)body_len);
  983. if (status_code != 200) {
  984. log_warn(LD_DIR,"Received http status code %d (%s) from server "
  985. "'%s:%d' while fetching running-routers. I'll try again soon.",
  986. status_code, escaped(reason), conn->_base.address,
  987. conn->_base.port);
  988. tor_free(body); tor_free(headers); tor_free(reason);
  989. return -1;
  990. }
  991. if (router_parse_runningrouters(body)<0) {
  992. log_warn(LD_DIR,
  993. "Bad running-routers from server '%s:%d'. I'll try again soon.",
  994. conn->_base.address, conn->_base.port);
  995. tor_free(body); tor_free(headers); tor_free(reason);
  996. return -1;
  997. }
  998. note_request(was_compressed?"dl/running-routers.z":
  999. "dl/running-routers", orig_len);
  1000. }
  1001. if (conn->_base.purpose == DIR_PURPOSE_FETCH_NETWORKSTATUS) {
  1002. smartlist_t *which = NULL;
  1003. networkstatus_source_t source;
  1004. char *cp;
  1005. log_info(LD_DIR,"Received networkstatus objects (size %d) from server "
  1006. "'%s:%d'",(int) body_len, conn->_base.address, conn->_base.port);
  1007. if (status_code != 200) {
  1008. /* XXXX This warning tends to freak out clients who get a 403. */
  1009. log_warn(LD_DIR,
  1010. "Received http status code %d (%s) from server "
  1011. "'%s:%d' while fetching \"/tor/status/%s\". I'll try again soon.",
  1012. status_code, escaped(reason), conn->_base.address,
  1013. conn->_base.port, conn->requested_resource);
  1014. tor_free(body); tor_free(headers); tor_free(reason);
  1015. connection_dir_download_networkstatus_failed(conn, status_code);
  1016. return -1;
  1017. }
  1018. note_request(was_compressed?"dl/status.z":"dl/status", orig_len);
  1019. if (conn->requested_resource &&
  1020. !strcmpstart(conn->requested_resource,"fp/")) {
  1021. source = NS_FROM_DIR_BY_FP;
  1022. which = smartlist_create();
  1023. dir_split_resource_into_fingerprints(conn->requested_resource+3,
  1024. which, NULL, 0, 0);
  1025. } else if (conn->requested_resource &&
  1026. !strcmpstart(conn->requested_resource, "all")) {
  1027. source = NS_FROM_DIR_ALL;
  1028. which = smartlist_create();
  1029. SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
  1030. trusted_dir_server_t *, ds,
  1031. {
  1032. char *cp = tor_malloc(HEX_DIGEST_LEN+1);
  1033. base16_encode(cp, HEX_DIGEST_LEN+1, ds->digest, DIGEST_LEN);
  1034. smartlist_add(which, cp);
  1035. });
  1036. } else {
  1037. /* Can we even end up here? -- weasel*/
  1038. source = NS_FROM_DIR_BY_FP;
  1039. log_warn(LD_BUG, "We received a networkstatus but we didn't ask "
  1040. "for it by fp, nor did we ask for all.");
  1041. }
  1042. cp = body;
  1043. while (*cp) {
  1044. char *next = strstr(cp, "\nnetwork-status-version");
  1045. if (next)
  1046. next[1] = '\0';
  1047. /* learn from it, and then remove it from 'which' */
  1048. if (router_set_networkstatus(cp, now, source, which)<0)
  1049. break;
  1050. if (next) {
  1051. next[1] = 'n';
  1052. cp = next+1;
  1053. } else
  1054. break;
  1055. }
  1056. routers_update_all_from_networkstatus(now); /*launches router downloads*/
  1057. directory_info_has_arrived(now, 0);
  1058. if (which) {
  1059. if (smartlist_len(which)) {
  1060. dir_networkstatus_download_failed(which, status_code);
  1061. }
  1062. SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
  1063. smartlist_free(which);
  1064. }
  1065. }
  1066. if (conn->_base.purpose == DIR_PURPOSE_FETCH_SERVERDESC) {
  1067. smartlist_t *which = NULL;
  1068. int n_asked_for = 0;
  1069. log_info(LD_DIR,"Received server info (size %d) from server '%s:%d'",
  1070. (int)body_len, conn->_base.address, conn->_base.port);
  1071. note_request(was_compressed?"dl/server.z":"dl/server", orig_len);
  1072. if (conn->requested_resource &&
  1073. !strcmpstart(conn->requested_resource,"d/")) {
  1074. which = smartlist_create();
  1075. dir_split_resource_into_fingerprints(conn->requested_resource+2,
  1076. which, NULL, 0, 0);
  1077. n_asked_for = smartlist_len(which);
  1078. }
  1079. if (status_code != 200) {
  1080. int dir_okay = status_code == 404 ||
  1081. (status_code == 400 && !strcmp(reason, "Servers unavailable."));
  1082. /* 404 means that it didn't have them; no big deal.
  1083. * Older (pre-0.1.1.8) servers said 400 Servers unavailable instead. */
  1084. /* XXXX This warning tends to freak out clients who get a 403. */
  1085. log_fn(dir_okay ? LOG_INFO : LOG_WARN, LD_DIR,
  1086. "Received http status code %d (%s) from server '%s:%d' "
  1087. "while fetching \"/tor/server/%s\". I'll try again soon.",
  1088. status_code, escaped(reason), conn->_base.address,
  1089. conn->_base.port, conn->requested_resource);
  1090. if (!which) {
  1091. connection_dir_download_routerdesc_failed(conn);
  1092. } else {
  1093. dir_routerdesc_download_failed(which, status_code);
  1094. SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
  1095. smartlist_free(which);
  1096. }
  1097. tor_free(body); tor_free(headers); tor_free(reason);
  1098. return dir_okay ? 0 : -1;
  1099. }
  1100. /* Learn the routers, assuming we requested by fingerprint or "all".
  1101. * Right now, we only use "authority" to fetch ourself, so we don't want
  1102. * to risk replacing ourself with a router running at the addr:port we
  1103. * think we have.
  1104. */
  1105. if (which || (conn->requested_resource &&
  1106. !strcmpstart(conn->requested_resource, "all"))) {
  1107. /* as we learn from them, we remove them from 'which' */
  1108. router_load_routers_from_string(body, SAVED_NOWHERE, which);
  1109. directory_info_has_arrived(now, 0);
  1110. }
  1111. if (which) { /* mark remaining ones as failed */
  1112. log_info(LD_DIR, "Received %d/%d routers requested from %s:%d",
  1113. n_asked_for-smartlist_len(which), n_asked_for,
  1114. conn->_base.address, (int)conn->_base.port);
  1115. if (smartlist_len(which)) {
  1116. dir_routerdesc_download_failed(which, status_code);
  1117. }
  1118. SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
  1119. smartlist_free(which);
  1120. }
  1121. if (directory_conn_is_self_reachability_test(conn))
  1122. router_dirport_found_reachable();
  1123. }
  1124. if (conn->_base.purpose == DIR_PURPOSE_UPLOAD_DIR) {
  1125. switch (status_code) {
  1126. case 200: {
  1127. int all_done = 1;
  1128. trusted_dir_server_t *ds =
  1129. router_get_trusteddirserver_by_digest(conn->identity_digest);
  1130. smartlist_t *servers;
  1131. log_info(LD_GENERAL,"eof (status 200) after uploading server "
  1132. "descriptor: finished.");
  1133. control_event_server_status(
  1134. LOG_NOTICE, "ACCEPTED_SERVER_DESCRIPTOR DIRAUTH=%s:%d",
  1135. conn->_base.address, conn->_base.port);
  1136. ds->has_accepted_serverdesc = 1;
  1137. servers = router_get_trusted_dir_servers();
  1138. SMARTLIST_FOREACH(servers, trusted_dir_server_t *, d, {
  1139. if ((d->is_v1_authority || d->is_v2_authority) &&
  1140. !d->has_accepted_serverdesc) {
  1141. all_done = 0;
  1142. break;
  1143. }
  1144. });
  1145. if (all_done)
  1146. control_event_server_status(LOG_NOTICE, "GOOD_SERVER_DESCRIPTOR");
  1147. }
  1148. break;
  1149. case 400:
  1150. log_warn(LD_GENERAL,"http status 400 (%s) response from "
  1151. "dirserver '%s:%d'. Please correct.",
  1152. escaped(reason), conn->_base.address, conn->_base.port);
  1153. control_event_server_status(LOG_WARN,
  1154. "BAD_SERVER_DESCRIPTOR DIRAUTH=%s:%d REASON=\"%s\"",
  1155. conn->_base.address, conn->_base.port, escaped(reason));
  1156. break;
  1157. case 403:
  1158. log_warn(LD_GENERAL,
  1159. "http status 403 (%s) response from dirserver "
  1160. "'%s:%d'. Is your clock skewed? Have you mailed us your key "
  1161. "fingerprint? Are you using the right key? Are you using a "
  1162. "private IP address? See http://tor.eff.org/doc/"
  1163. "tor-doc-server.html",escaped(reason), conn->_base.address,
  1164. conn->_base.port);
  1165. control_event_server_status(LOG_WARN,
  1166. "BAD_SERVER_DESCRIPTOR DIRAUTH=%s:%d REASON=\"%s\"",
  1167. conn->_base.address, conn->_base.port, escaped(reason));
  1168. break;
  1169. default:
  1170. log_warn(LD_GENERAL,
  1171. "http status %d (%s) reason unexpected while uploading "
  1172. "descriptor to server '%s:%d').",
  1173. status_code, escaped(reason), conn->_base.address,
  1174. conn->_base.port);
  1175. break;
  1176. }
  1177. /* return 0 in all cases, since we don't want to mark any
  1178. * dirservers down just because they don't like us. */
  1179. }
  1180. if (conn->_base.purpose == DIR_PURPOSE_FETCH_RENDDESC) {
  1181. log_info(LD_REND,"Received rendezvous descriptor (size %d, status %d "
  1182. "(%s))",
  1183. (int)body_len, status_code, escaped(reason));
  1184. switch (status_code) {
  1185. case 200:
  1186. if (rend_cache_store(body, body_len, 0) < 0) {
  1187. log_warn(LD_REND,"Failed to store rendezvous descriptor.");
  1188. /* alice's ap_stream will notice when connection_mark_for_close
  1189. * cleans it up */
  1190. } else {
  1191. /* success. notify pending connections about this. */
  1192. conn->_base.purpose = DIR_PURPOSE_HAS_FETCHED_RENDDESC;
  1193. rend_client_desc_here(conn->rend_query);
  1194. }
  1195. break;
  1196. case 404:
  1197. /* not there. pending connections will be notified when
  1198. * connection_mark_for_close cleans it up. */
  1199. break;
  1200. case 400:
  1201. log_warn(LD_REND,
  1202. "http status 400 (%s). Dirserver didn't like our "
  1203. "rendezvous query?", escaped(reason));
  1204. break;
  1205. default:
  1206. log_warn(LD_REND,"http status %d (%s) response unexpected while "
  1207. "fetching hidden service descriptor (server '%s:%d').",
  1208. status_code, escaped(reason), conn->_base.address,
  1209. conn->_base.port);
  1210. break;
  1211. }
  1212. }
  1213. if (conn->_base.purpose == DIR_PURPOSE_UPLOAD_RENDDESC) {
  1214. switch (status_code) {
  1215. case 200:
  1216. log_info(LD_REND,
  1217. "Uploading rendezvous descriptor: finished with status "
  1218. "200 (%s)", escaped(reason));
  1219. break;
  1220. case 400:
  1221. log_warn(LD_REND,"http status 400 (%s) response from dirserver "
  1222. "'%s:%d'. Malformed rendezvous descriptor?",
  1223. escaped(reason), conn->_base.address, conn->_base.port);
  1224. break;
  1225. default:
  1226. log_warn(LD_REND,"http status %d (%s) response unexpected (server "
  1227. "'%s:%d').",
  1228. status_code, escaped(reason), conn->_base.address,
  1229. conn->_base.port);
  1230. break;
  1231. }
  1232. }
  1233. tor_free(body); tor_free(headers); tor_free(reason);
  1234. return 0;
  1235. }
  1236. /** Called when a directory connection reaches EOF */
  1237. int
  1238. connection_dir_reached_eof(dir_connection_t *conn)
  1239. {
  1240. int retval;
  1241. if (conn->_base.state != DIR_CONN_STATE_CLIENT_READING) {
  1242. log_info(LD_HTTP,"conn reached eof, not reading. [state=%d] Closing.",
  1243. conn->_base.state);
  1244. connection_close_immediate(TO_CONN(conn)); /* error: give up on flushing */
  1245. connection_mark_for_close(TO_CONN(conn));
  1246. return -1;
  1247. }
  1248. retval = connection_dir_client_reached_eof(conn);
  1249. if (retval == 0) /* success */
  1250. conn->_base.state = DIR_CONN_STATE_CLIENT_FINISHED;
  1251. connection_mark_for_close(TO_CONN(conn));
  1252. return retval;
  1253. }
  1254. /** If any directory object is arriving, and it's over 10MB large, we're
  1255. * getting DoS'd. (As of 0.1.2.x, raw directories are about 1MB, and we never
  1256. * ask for more than 96 router descriptors at a time.)
  1257. */
  1258. #define MAX_DIRECTORY_OBJECT_SIZE (10*(1<<20))
  1259. /** Read handler for directory connections. (That's connections <em>to</em>
  1260. * directory servers and connections <em>at</em> directory servers.)
  1261. */
  1262. int
  1263. connection_dir_process_inbuf(dir_connection_t *conn)
  1264. {
  1265. tor_assert(conn);
  1266. tor_assert(conn->_base.type == CONN_TYPE_DIR);
  1267. /* Directory clients write, then read data until they receive EOF;
  1268. * directory servers read data until they get an HTTP command, then
  1269. * write their response (when it's finished flushing, they mark for
  1270. * close).
  1271. */
  1272. /* If we're on the dirserver side, look for a command. */
  1273. if (conn->_base.state == DIR_CONN_STATE_SERVER_COMMAND_WAIT) {
  1274. if (directory_handle_command(conn) < 0) {
  1275. connection_mark_for_close(TO_CONN(conn));
  1276. return -1;
  1277. }
  1278. return 0;
  1279. }
  1280. if (buf_datalen(conn->_base.inbuf) > MAX_DIRECTORY_OBJECT_SIZE) {
  1281. log_warn(LD_HTTP, "Too much data received from directory connection: "
  1282. "denial of service attempt, or you need to upgrade?");
  1283. connection_mark_for_close(TO_CONN(conn));
  1284. return -1;
  1285. }
  1286. if (!conn->_base.inbuf_reached_eof)
  1287. log_debug(LD_HTTP,"Got data, not eof. Leaving on inbuf.");
  1288. return 0;
  1289. }
  1290. /** Create an http response for the client <b>conn</b> out of
  1291. * <b>status</b> and <b>reason_phrase</b>. Write it to <b>conn</b>.
  1292. */
  1293. static void
  1294. write_http_status_line(dir_connection_t *conn, int status,
  1295. const char *reason_phrase)
  1296. {
  1297. char buf[256];
  1298. if (tor_snprintf(buf, sizeof(buf), "HTTP/1.0 %d %s\r\n\r\n",
  1299. status, reason_phrase) < 0) {
  1300. log_warn(LD_BUG,"status line too long.");
  1301. return;
  1302. }
  1303. connection_write_to_buf(buf, strlen(buf), TO_CONN(conn));
  1304. }
  1305. /** Write the header for an HTTP/1.0 response onto <b>conn</b>-\>outbuf,
  1306. * with <b>type</b> as the Content-Type.
  1307. *
  1308. * If <b>length</b> is nonnegative, it is the Content-Length.
  1309. * If <b>encoding</b> is provided, it is the Content-Encoding.
  1310. * If <b>cache_lifetime</b> is greater than 0, the content may be cached for
  1311. * up to cache_lifetime seconds. Otherwise, the content may not be cached. */
  1312. static void
  1313. write_http_response_header(dir_connection_t *conn, ssize_t length,
  1314. const char *type, const char *encoding,
  1315. int cache_lifetime)
  1316. {
  1317. char date[RFC1123_TIME_LEN+1];
  1318. char tmp[1024];
  1319. char *cp;
  1320. time_t now = time(NULL);
  1321. tor_assert(conn);
  1322. tor_assert(type);
  1323. format_rfc1123_time(date, now);
  1324. cp = tmp;
  1325. tor_snprintf(cp, sizeof(tmp),
  1326. "HTTP/1.0 200 OK\r\nDate: %s\r\nContent-Type: %s\r\n",
  1327. date, type);
  1328. cp += strlen(tmp);
  1329. if (!is_internal_IP(conn->_base.addr, 0)) {
  1330. /* Don't report the source address for a localhost/private connection. */
  1331. tor_snprintf(cp, sizeof(tmp)-(cp-tmp),
  1332. X_ADDRESS_HEADER "%s\r\n", conn->_base.address);
  1333. cp += strlen(cp);
  1334. }
  1335. if (encoding) {
  1336. tor_snprintf(cp, sizeof(tmp)-(cp-tmp),
  1337. "Content-Encoding: %s\r\n", encoding);
  1338. cp += strlen(cp);
  1339. }
  1340. if (length >= 0) {
  1341. tor_snprintf(cp, sizeof(tmp)-(cp-tmp),
  1342. "Content-Length: %ld\r\n", (long)length);
  1343. cp += strlen(cp);
  1344. }
  1345. if (cache_lifetime > 0) {
  1346. char expbuf[RFC1123_TIME_LEN+1];
  1347. format_rfc1123_time(expbuf, now + cache_lifetime);
  1348. /* We could say 'Cache-control: max-age=%d' here if we start doing
  1349. * http/1.1 */
  1350. tor_snprintf(cp, sizeof(tmp)-(cp-tmp),
  1351. "Expires: %s\r\n", expbuf);
  1352. cp += strlen(cp);
  1353. } else {
  1354. /* We could say 'Cache-control: no-cache' here if we start doing
  1355. * http/1.1 */
  1356. strlcpy(cp, "Pragma: no-cache\r\n", sizeof(tmp)-(cp-tmp));
  1357. cp += strlen(cp);
  1358. }
  1359. if (sizeof(tmp)-(cp-tmp) > 3)
  1360. memcpy(cp, "\r\n", 3);
  1361. else
  1362. tor_assert(0);
  1363. connection_write_to_buf(tmp, strlen(tmp), TO_CONN(conn));
  1364. }
  1365. /** Helper function: return 1 if there are any dir conns of purpose
  1366. * <b>purpose</b> that are going elsewhere than our own ORPort/Dirport.
  1367. * Else return 0.
  1368. */
  1369. static int
  1370. already_fetching_directory(int purpose)
  1371. {
  1372. int i, n;
  1373. connection_t *conn;
  1374. connection_t **carray;
  1375. get_connection_array(&carray,&n);
  1376. for (i=0;i<n;i++) {
  1377. conn = carray[i];
  1378. if (conn->type == CONN_TYPE_DIR &&
  1379. conn->purpose == purpose &&
  1380. !conn->marked_for_close &&
  1381. !router_digest_is_me(TO_DIR_CONN(conn)->identity_digest))
  1382. return 1;
  1383. }
  1384. return 0;
  1385. }
  1386. #undef INSTRUMENT_DOWNLOADS
  1387. #ifdef INSTRUMENT_DOWNLOADS
  1388. /** Map used to keep track of how much data we've up/downloaded in what kind
  1389. * of request. Maps from request type to pointer to uint64_t. */
  1390. static strmap_t *request_bytes_map = NULL;
  1391. /** Called when we just transmitted or received <b>bytes</b> worth of data
  1392. * because of a request of type <b>key</b> (an arbitrary identifier): adds
  1393. * <b>bytes</b> to the total associated with key. */
  1394. static void
  1395. note_request(const char *key, size_t bytes)
  1396. {
  1397. uint64_t *n;
  1398. if (!request_bytes_map)
  1399. request_bytes_map = strmap_new();
  1400. n = strmap_get(request_bytes_map, key);
  1401. if (!n) {
  1402. n = tor_malloc_zero(sizeof(uint64_t));
  1403. strmap_set(request_bytes_map, key, n);
  1404. }
  1405. *n += bytes;
  1406. }
  1407. /** Return a newly allocated string holding a summary of bytes used per
  1408. * request type. */
  1409. char *
  1410. directory_dump_request_log(void)
  1411. {
  1412. smartlist_t *lines;
  1413. char tmp[256];
  1414. char *result;
  1415. strmap_iter_t *iter;
  1416. if (!request_bytes_map)
  1417. request_bytes_map = strmap_new();
  1418. lines = smartlist_create();
  1419. for (iter = strmap_iter_init(request_bytes_map);
  1420. !strmap_iter_done(iter);
  1421. iter = strmap_iter_next(request_bytes_map, iter)) {
  1422. const char *key;
  1423. void *val;
  1424. uint64_t *n;
  1425. strmap_iter_get(iter, &key, &val);
  1426. n = val;
  1427. tor_snprintf(tmp, sizeof(tmp), "%s "U64_FORMAT"\n",
  1428. key, U64_PRINTF_ARG(*n));
  1429. smartlist_add(lines, tor_strdup(tmp));
  1430. }
  1431. smartlist_sort_strings(lines);
  1432. result = smartlist_join_strings(lines, "", 0, NULL);
  1433. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  1434. smartlist_free(lines);
  1435. return result;
  1436. }
  1437. #else
  1438. static void
  1439. note_request(const char *key, size_t bytes)
  1440. {
  1441. (void)key;
  1442. (void)bytes;
  1443. }
  1444. char *
  1445. directory_dump_request_log(void)
  1446. {
  1447. return tor_strdup("Not supported.");
  1448. }
  1449. #endif
  1450. /** Helper function: called when a dirserver gets a complete HTTP GET
  1451. * request. Look for a request for a directory or for a rendezvous
  1452. * service descriptor. On finding one, write a response into
  1453. * conn-\>outbuf. If the request is unrecognized, send a 400.
  1454. * Always return 0. */
  1455. static int
  1456. directory_handle_command_get(dir_connection_t *conn, const char *headers,
  1457. const char *body, size_t body_len)
  1458. {
  1459. size_t dlen;
  1460. const char *cp;
  1461. char *url = NULL;
  1462. or_options_t *options = get_options();
  1463. /* We ignore the body of a GET request. */
  1464. (void)body;
  1465. (void)body_len;
  1466. log_debug(LD_DIRSERV,"Received GET command.");
  1467. conn->_base.state = DIR_CONN_STATE_SERVER_WRITING;
  1468. if (parse_http_url(headers, &url) < 0) {
  1469. write_http_status_line(conn, 400, "Bad request");
  1470. return 0;
  1471. }
  1472. log_debug(LD_DIRSERV,"rewritten url as '%s'.", url);
  1473. if (!strcmp(url,"/tor/") || !strcmp(url,"/tor/dir.z")) { /* dir fetch */
  1474. int deflated = !strcmp(url,"/tor/dir.z");
  1475. cached_dir_t *d = dirserv_get_directory();
  1476. if (!d) {
  1477. log_notice(LD_DIRSERV,"Client asked for the mirrored directory, but we "
  1478. "don't have a good one yet. Sending 503 Dir not available.");
  1479. write_http_status_line(conn, 503, "Directory unavailable");
  1480. /* try to get a new one now */
  1481. if (!already_fetching_directory(DIR_PURPOSE_FETCH_DIR))
  1482. directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL, 1);
  1483. tor_free(url);
  1484. return 0;
  1485. }
  1486. dlen = deflated ? d->dir_z_len : d->dir_len;
  1487. if (global_write_bucket_low(TO_CONN(conn), dlen, 1)) {
  1488. log_info(LD_DIRSERV,
  1489. "Client asked for the mirrored directory, but we've been "
  1490. "writing too many bytes lately. Sending 503 Dir busy.");
  1491. write_http_status_line(conn, 503, "Directory busy, try again later");
  1492. tor_free(url);
  1493. return 0;
  1494. }
  1495. note_request(url, dlen);
  1496. tor_free(url);
  1497. log_debug(LD_DIRSERV,"Dumping %sdirectory to client.",
  1498. deflated?"deflated ":"");
  1499. write_http_response_header(conn, dlen,
  1500. deflated?"application/octet-stream":"text/plain",
  1501. deflated?"deflate":"identity",
  1502. FULL_DIR_CACHE_LIFETIME);
  1503. conn->cached_dir = d;
  1504. conn->cached_dir_offset = 0;
  1505. if (! deflated)
  1506. conn->zlib_state = tor_zlib_new(0, ZLIB_METHOD);
  1507. ++d->refcnt;
  1508. /* Prime the connection with some data. */
  1509. conn->dir_spool_src = DIR_SPOOL_CACHED_DIR;
  1510. connection_dirserv_flushed_some(conn);
  1511. return 0;
  1512. }
  1513. if (!strcmp(url,"/tor/running-routers") ||
  1514. !strcmp(url,"/tor/running-routers.z")) { /* running-routers fetch */
  1515. int deflated = !strcmp(url,"/tor/running-routers.z");
  1516. dlen = dirserv_get_runningrouters(&cp, deflated);
  1517. if (!dlen) { /* we failed to create/cache cp */
  1518. write_http_status_line(conn, 503, "Directory unavailable");
  1519. /* try to get a new one now */
  1520. if (!already_fetching_directory(DIR_PURPOSE_FETCH_RUNNING_LIST))
  1521. directory_get_from_dirserver(DIR_PURPOSE_FETCH_RUNNING_LIST, NULL, 1);
  1522. tor_free(url);
  1523. return 0;
  1524. }
  1525. if (global_write_bucket_low(TO_CONN(conn), dlen, 1)) {
  1526. log_info(LD_DIRSERV,
  1527. "Client asked for running-routers, but we've been "
  1528. "writing too many bytes lately. Sending 503 Dir busy.");
  1529. write_http_status_line(conn, 503, "Directory busy, try again later");
  1530. tor_free(url);
  1531. return 0;
  1532. }
  1533. note_request(url, dlen);
  1534. tor_free(url);
  1535. write_http_response_header(conn, dlen,
  1536. deflated?"application/octet-stream":"text/plain",
  1537. deflated?"deflate":"identity",
  1538. RUNNINGROUTERS_CACHE_LIFETIME);
  1539. connection_write_to_buf(cp, strlen(cp), TO_CONN(conn));
  1540. return 0;
  1541. }
  1542. if (!strcmpstart(url,"/tor/status/")) {
  1543. /* v2 network status fetch. */
  1544. size_t url_len = strlen(url);
  1545. int deflated = !strcmp(url+url_len-2, ".z");
  1546. smartlist_t *dir_fps = smartlist_create();
  1547. const char *request_type = NULL;
  1548. const char *key = url + strlen("/tor/status/");
  1549. if (deflated)
  1550. url[url_len-2] = '\0';
  1551. dirserv_get_networkstatus_v2_fingerprints(dir_fps, key);
  1552. if (!strcmpstart(key, "fp/"))
  1553. request_type = deflated?"/tor/status/fp.z":"/tor/status/fp";
  1554. else if (!strcmpstart(key, "authority"))
  1555. request_type = deflated?"/tor/status/authority.z":
  1556. "/tor/status/authority";
  1557. else if (!strcmpstart(key, "all"))
  1558. request_type = deflated?"/tor/status/all.z":"/tor/status/all";
  1559. else
  1560. request_type = "/tor/status/?";
  1561. tor_free(url);
  1562. if (!smartlist_len(dir_fps)) { /* we failed to create/cache cp */
  1563. write_http_status_line(conn, 503, "Network status object unavailable");
  1564. smartlist_free(dir_fps);
  1565. return 0;
  1566. }
  1567. dlen = dirserv_estimate_data_size(dir_fps, 0, deflated);
  1568. if (global_write_bucket_low(TO_CONN(conn), dlen, 2)) {
  1569. log_info(LD_DIRSERV,
  1570. "Client asked for network status lists, but we've been "
  1571. "writing too many bytes lately. Sending 503 Dir busy.");
  1572. write_http_status_line(conn, 503, "Directory busy, try again later");
  1573. SMARTLIST_FOREACH(dir_fps, char *, cp, tor_free(cp));
  1574. smartlist_free(dir_fps);
  1575. return 0;
  1576. }
  1577. // note_request(request_type,dlen);
  1578. (void) request_type;
  1579. write_http_response_header(conn, -1,
  1580. deflated?"application/octet_stream":"text/plain",
  1581. deflated?"deflate":NULL,
  1582. smartlist_len(dir_fps) == 1 ? NETWORKSTATUS_CACHE_LIFETIME:0);
  1583. conn->fingerprint_stack = dir_fps;
  1584. if (! deflated)
  1585. conn->zlib_state = tor_zlib_new(0, ZLIB_METHOD);
  1586. /* Prime the connection with some data. */
  1587. conn->dir_spool_src = DIR_SPOOL_NETWORKSTATUS;
  1588. connection_dirserv_flushed_some(conn);
  1589. return 0;
  1590. }
  1591. if (!strcmpstart(url,"/tor/server/") ||
  1592. !strcmpstart(url,"/tor/extra/")) {
  1593. char *url_mem = url;
  1594. size_t url_len = strlen(url);
  1595. int deflated = !strcmp(url+url_len-2, ".z");
  1596. int res;
  1597. const char *msg;
  1598. const char *request_type = NULL;
  1599. int cache_lifetime = 0;
  1600. int is_extra = !strcmpstart(url,"/tor/extra/");
  1601. if (deflated)
  1602. url[url_len-2] = '\0';
  1603. url += is_extra ? strlen("/tor/extra/") : strlen("/tor/server/");
  1604. conn->fingerprint_stack = smartlist_create();
  1605. res = dirserv_get_routerdesc_fingerprints(conn->fingerprint_stack, url,
  1606. &msg);
  1607. if (!strcmpstart(url, "fp/")) {
  1608. request_type = deflated?"/tor/server/fp.z":"/tor/server/fp";
  1609. if (smartlist_len(conn->fingerprint_stack) == 1)
  1610. cache_lifetime = ROUTERDESC_CACHE_LIFETIME;
  1611. } else if (!strcmpstart(url, "authority")) {
  1612. request_type = deflated?"/tor/server/authority.z":
  1613. "/tor/server/authority";
  1614. cache_lifetime = ROUTERDESC_CACHE_LIFETIME;
  1615. } else if (!strcmpstart(url, "all")) {
  1616. request_type = deflated?"/tor/server/all.z":"/tor/server/all";
  1617. cache_lifetime = FULL_DIR_CACHE_LIFETIME;
  1618. } else if (!strcmpstart(url, "d/")) {
  1619. request_type = deflated?"/tor/server/d.z":"/tor/server/d";
  1620. if (smartlist_len(conn->fingerprint_stack) == 1)
  1621. cache_lifetime = ROUTERDESC_BY_DIGEST_CACHE_LIFETIME;
  1622. } else {
  1623. request_type = "/tor/server/?";
  1624. }
  1625. (void) request_type; /* usable for note_request. */
  1626. if (!strcmpstart(url, "d/"))
  1627. conn->dir_spool_src =
  1628. is_extra ? DIR_SPOOL_EXTRA_BY_DIGEST : DIR_SPOOL_SERVER_BY_DIGEST;
  1629. else
  1630. conn->dir_spool_src =
  1631. is_extra ? DIR_SPOOL_EXTRA_BY_FP : DIR_SPOOL_SERVER_BY_FP;
  1632. tor_free(url_mem);
  1633. if (res < 0)
  1634. write_http_status_line(conn, 404, msg);
  1635. else {
  1636. dlen = dirserv_estimate_data_size(conn->fingerprint_stack,
  1637. 1, deflated);
  1638. if (global_write_bucket_low(TO_CONN(conn), dlen, 2)) {
  1639. log_info(LD_DIRSERV,
  1640. "Client asked for server descriptors, but we've been "
  1641. "writing too many bytes lately. Sending 503 Dir busy.");
  1642. write_http_status_line(conn, 503, "Directory busy, try again later");
  1643. return 0;
  1644. }
  1645. write_http_response_header(conn, -1,
  1646. deflated?"application/octet_stream":"text/plain",
  1647. deflated?"deflate":NULL, cache_lifetime);
  1648. if (deflated)
  1649. conn->zlib_state = tor_zlib_new(1, ZLIB_METHOD);
  1650. /* Prime the connection with some data. */
  1651. connection_dirserv_flushed_some(conn);
  1652. }
  1653. return 0;
  1654. }
  1655. if (options->HSAuthoritativeDir &&
  1656. (!strcmpstart(url,"/tor/rendezvous/") ||
  1657. !strcmpstart(url,"/tor/rendezvous1/"))) {
  1658. /* rendezvous descriptor fetch */
  1659. const char *descp;
  1660. size_t desc_len;
  1661. int versioned = !strcmpstart(url,"/tor/rendezvous1/");
  1662. const char *query = url+strlen("/tor/rendezvous/")+(versioned?1:0);
  1663. switch (rend_cache_lookup_desc(query, versioned?-1:0, &descp, &desc_len)) {
  1664. case 1: /* valid */
  1665. write_http_response_header(conn, desc_len, "application/octet-stream",
  1666. NULL, 0);
  1667. note_request("/tor/rendezvous?/", desc_len);
  1668. /* need to send descp separately, because it may include nuls */
  1669. connection_write_to_buf(descp, desc_len, TO_CONN(conn));
  1670. /* report successful fetch to statistic */
  1671. if (options->HSAuthorityRecordStats) {
  1672. hs_usage_note_fetch_total(query, time(NULL));
  1673. hs_usage_note_fetch_successful(query, time(NULL));
  1674. }
  1675. break;
  1676. case 0: /* well-formed but not present */
  1677. write_http_status_line(conn, 404, "Not found");
  1678. /* report (unsuccessful) fetch to statistic */
  1679. if (options->HSAuthorityRecordStats) {
  1680. hs_usage_note_fetch_total(query, time(NULL));
  1681. }
  1682. break;
  1683. case -1: /* not well-formed */
  1684. write_http_status_line(conn, 400, "Bad request");
  1685. break;
  1686. }
  1687. tor_free(url);
  1688. return 0;
  1689. }
  1690. if (!strcmpstart(url,"/tor/bytes.txt")) {
  1691. char *bytes = directory_dump_request_log();
  1692. size_t len = strlen(bytes);
  1693. write_http_response_header(conn, len, "text/plain", NULL, 0);
  1694. connection_write_to_buf(bytes, len, TO_CONN(conn));
  1695. tor_free(bytes);
  1696. tor_free(url);
  1697. return 0;
  1698. }
  1699. if (!strcmp(url,"/tor/robots.txt")) { /* /robots.txt will have been
  1700. rewritten to /tor/robots.txt */
  1701. char robots[] = "User-agent: *\r\nDisallow: /\r\n";
  1702. size_t len = strlen(robots);
  1703. write_http_response_header(conn, len, "text/plain", NULL,
  1704. ROBOTS_CACHE_LIFETIME);
  1705. connection_write_to_buf(robots, len, TO_CONN(conn));
  1706. tor_free(url);
  1707. return 0;
  1708. }
  1709. if (!strcmp(url,"/tor/dir-all-weaselhack") &&
  1710. (conn->_base.addr == 0x7f000001ul) &&
  1711. authdir_mode_v2(options) &&
  1712. !authdir_mode_bridge(options)) {
  1713. /* until weasel rewrites his scripts at noreply */
  1714. char *new_directory=NULL;
  1715. if (dirserv_dump_directory_to_string(&new_directory,
  1716. get_identity_key(), 1)) {
  1717. log_warn(LD_BUG, "Error creating full v1 directory.");
  1718. tor_free(new_directory);
  1719. write_http_status_line(conn, 503, "Directory unavailable");
  1720. return 0;
  1721. }
  1722. dlen = strlen(new_directory);
  1723. write_http_response_header(conn, dlen, "text/plain", "identity", 0);
  1724. connection_write_to_buf(new_directory, dlen, TO_CONN(conn));
  1725. tor_free(new_directory);
  1726. tor_free(url);
  1727. return 0;
  1728. }
  1729. /* we didn't recognize the url */
  1730. write_http_status_line(conn, 404, "Not found");
  1731. tor_free(url);
  1732. return 0;
  1733. }
  1734. /** Helper function: called when a dirserver gets a complete HTTP POST
  1735. * request. Look for an uploaded server descriptor or rendezvous
  1736. * service descriptor. On finding one, process it and write a
  1737. * response into conn-\>outbuf. If the request is unrecognized, send a
  1738. * 400. Always return 0. */
  1739. static int
  1740. directory_handle_command_post(dir_connection_t *conn, const char *headers,
  1741. const char *body, size_t body_len)
  1742. {
  1743. char *url = NULL;
  1744. or_options_t *options = get_options();
  1745. log_debug(LD_DIRSERV,"Received POST command.");
  1746. conn->_base.state = DIR_CONN_STATE_SERVER_WRITING;
  1747. if (!authdir_mode(options)) {
  1748. /* we just provide cached directories; we don't want to
  1749. * receive anything. */
  1750. write_http_status_line(conn, 400, "Nonauthoritative directory does not "
  1751. "accept posted server descriptors");
  1752. return 0;
  1753. }
  1754. if (parse_http_url(headers, &url) < 0) {
  1755. write_http_status_line(conn, 400, "Bad request");
  1756. return 0;
  1757. }
  1758. log_debug(LD_DIRSERV,"rewritten url as '%s'.", url);
  1759. if (authdir_mode_handles_descs(options) &&
  1760. !strcmp(url,"/tor/")) { /* server descriptor post */
  1761. const char *msg;
  1762. int r = dirserv_add_multiple_descriptors(body, &msg);
  1763. tor_assert(msg);
  1764. if (r > 0)
  1765. dirserv_get_directory(); /* rebuild and write to disk */
  1766. switch (r) {
  1767. case -2:
  1768. case -1:
  1769. case 1:
  1770. log_notice(LD_DIRSERV,"Rejected router descriptor from %s.",
  1771. conn->_base.address);
  1772. /* malformed descriptor, or something wrong */
  1773. write_http_status_line(conn, 400, msg);
  1774. break;
  1775. case 0: /* accepted but discarded */
  1776. case 2: /* accepted */
  1777. write_http_status_line(conn, 200, msg);
  1778. break;
  1779. }
  1780. goto done;
  1781. }
  1782. if (options->HSAuthoritativeDir &&
  1783. !strcmpstart(url,"/tor/rendezvous/publish")) {
  1784. /* rendezvous descriptor post */
  1785. if (rend_cache_store(body, body_len, 1) < 0) {
  1786. // char tmp[1024*2+1];
  1787. log_fn(LOG_PROTOCOL_WARN, LD_DIRSERV,
  1788. "Rejected rend descriptor (length %d) from %s.",
  1789. (int)body_len, conn->_base.address);
  1790. write_http_status_line(conn, 400, "Invalid service descriptor rejected");
  1791. } else {
  1792. write_http_status_line(conn, 200, "Service descriptor stored");
  1793. }
  1794. goto done;
  1795. }
  1796. /* we didn't recognize the url */
  1797. write_http_status_line(conn, 404, "Not found");
  1798. done:
  1799. tor_free(url);
  1800. return 0;
  1801. }
  1802. /** Called when a dirserver receives data on a directory connection;
  1803. * looks for an HTTP request. If the request is complete, remove it
  1804. * from the inbuf, try to process it; otherwise, leave it on the
  1805. * buffer. Return a 0 on success, or -1 on error.
  1806. */
  1807. static int
  1808. directory_handle_command(dir_connection_t *conn)
  1809. {
  1810. char *headers=NULL, *body=NULL;
  1811. size_t body_len=0;
  1812. int r;
  1813. tor_assert(conn);
  1814. tor_assert(conn->_base.type == CONN_TYPE_DIR);
  1815. switch (fetch_from_buf_http(conn->_base.inbuf,
  1816. &headers, MAX_HEADERS_SIZE,
  1817. &body, &body_len, MAX_DIR_UL_SIZE, 0)) {
  1818. case -1: /* overflow */
  1819. log_warn(LD_DIRSERV,
  1820. "Invalid input from address '%s'. Closing.",
  1821. conn->_base.address);
  1822. return -1;
  1823. case 0:
  1824. log_debug(LD_DIRSERV,"command not all here yet.");
  1825. return 0;
  1826. /* case 1, fall through */
  1827. }
  1828. http_set_address_origin(headers, TO_CONN(conn));
  1829. //log_debug(LD_DIRSERV,"headers %s, body %s.", headers, body);
  1830. if (!strncasecmp(headers,"GET",3))
  1831. r = directory_handle_command_get(conn, headers, body, body_len);
  1832. else if (!strncasecmp(headers,"POST",4))
  1833. r = directory_handle_command_post(conn, headers, body, body_len);
  1834. else {
  1835. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1836. "Got headers %s with unknown command. Closing.",
  1837. escaped(headers));
  1838. r = -1;
  1839. }
  1840. tor_free(headers); tor_free(body);
  1841. return r;
  1842. }
  1843. /** Write handler for directory connections; called when all data has
  1844. * been flushed. Close the connection or wait for a response as
  1845. * appropriate.
  1846. */
  1847. int
  1848. connection_dir_finished_flushing(dir_connection_t *conn)
  1849. {
  1850. tor_assert(conn);
  1851. tor_assert(conn->_base.type == CONN_TYPE_DIR);
  1852. switch (conn->_base.state) {
  1853. case DIR_CONN_STATE_CLIENT_SENDING:
  1854. log_debug(LD_DIR,"client finished sending command.");
  1855. conn->_base.state = DIR_CONN_STATE_CLIENT_READING;
  1856. connection_stop_writing(TO_CONN(conn));
  1857. return 0;
  1858. case DIR_CONN_STATE_SERVER_WRITING:
  1859. log_debug(LD_DIRSERV,"Finished writing server response. Closing.");
  1860. connection_mark_for_close(TO_CONN(conn));
  1861. return 0;
  1862. default:
  1863. log_warn(LD_BUG,"called in unexpected state %d.",
  1864. conn->_base.state);
  1865. tor_fragile_assert();
  1866. return -1;
  1867. }
  1868. return 0;
  1869. }
  1870. /** Connected handler for directory connections: begin sending data to the
  1871. * server */
  1872. int
  1873. connection_dir_finished_connecting(dir_connection_t *conn)
  1874. {
  1875. tor_assert(conn);
  1876. tor_assert(conn->_base.type == CONN_TYPE_DIR);
  1877. tor_assert(conn->_base.state == DIR_CONN_STATE_CONNECTING);
  1878. log_debug(LD_HTTP,"Dir connection to router %s:%u established.",
  1879. conn->_base.address,conn->_base.port);
  1880. conn->_base.state = DIR_CONN_STATE_CLIENT_SENDING; /* start flushing conn */
  1881. return 0;
  1882. }
  1883. /** Called when one or more networkstatus fetches have failed (with uppercase
  1884. * fingerprints listed in <b>failed</b>). Mark those fingerprints as having
  1885. * failed once, unless they failed with status code 503. */
  1886. static void
  1887. dir_networkstatus_download_failed(smartlist_t *failed, int status_code)
  1888. {
  1889. if (status_code == 503)
  1890. return;
  1891. SMARTLIST_FOREACH(failed, const char *, fp,
  1892. {
  1893. char digest[DIGEST_LEN];
  1894. trusted_dir_server_t *dir;
  1895. base16_decode(digest, DIGEST_LEN, fp, strlen(fp));
  1896. dir = router_get_trusteddirserver_by_digest(digest);
  1897. if (dir)
  1898. ++dir->n_networkstatus_failures;
  1899. });
  1900. }
  1901. /** Called when one or more routerdesc fetches have failed (with uppercase
  1902. * fingerprints listed in <b>failed</b>). */
  1903. static void
  1904. dir_routerdesc_download_failed(smartlist_t *failed, int status_code)
  1905. {
  1906. char digest[DIGEST_LEN];
  1907. local_routerstatus_t *rs;
  1908. time_t now = time(NULL);
  1909. int server = server_mode(get_options()) && get_options()->DirPort;
  1910. SMARTLIST_FOREACH(failed, const char *, cp,
  1911. {
  1912. base16_decode(digest, DIGEST_LEN, cp, strlen(cp));
  1913. rs = router_get_combined_status_by_digest(digest);
  1914. if (!rs || rs->n_download_failures >= MAX_ROUTERDESC_DOWNLOAD_FAILURES)
  1915. continue;
  1916. if (status_code != 503 || server)
  1917. ++rs->n_download_failures;
  1918. if (server) {
  1919. switch (rs->n_download_failures) {
  1920. case 0: rs->next_attempt_at = 0; break;
  1921. case 1: rs->next_attempt_at = 0; break;
  1922. case 2: rs->next_attempt_at = 0; break;
  1923. case 3: rs->next_attempt_at = now+60; break;
  1924. case 4: rs->next_attempt_at = now+60; break;
  1925. case 5: rs->next_attempt_at = now+60*2; break;
  1926. case 6: rs->next_attempt_at = now+60*5; break;
  1927. case 7: rs->next_attempt_at = now+60*15; break;
  1928. default: rs->next_attempt_at = TIME_MAX; break;
  1929. }
  1930. } else {
  1931. switch (rs->n_download_failures) {
  1932. case 0: rs->next_attempt_at = 0; break;
  1933. case 1: rs->next_attempt_at = 0; break;
  1934. case 2: rs->next_attempt_at = now+60; break;
  1935. case 3: rs->next_attempt_at = now+60*5; break;
  1936. case 4: rs->next_attempt_at = now+60*10; break;
  1937. default: rs->next_attempt_at = TIME_MAX; break;
  1938. }
  1939. }
  1940. if (rs->next_attempt_at == 0)
  1941. log_debug(LD_DIR, "%s failed %d time(s); I'll try again immediately.",
  1942. cp, (int)rs->n_download_failures);
  1943. else if (rs->next_attempt_at < TIME_MAX)
  1944. log_debug(LD_DIR, "%s failed %d time(s); I'll try again in %d seconds.",
  1945. cp, (int)rs->n_download_failures,
  1946. (int)(rs->next_attempt_at-now));
  1947. else
  1948. log_debug(LD_DIR, "%s failed %d time(s); Giving up for a while.",
  1949. cp, (int)rs->n_download_failures);
  1950. });
  1951. /* No need to relaunch descriptor downloads here: we already do it
  1952. * every 10 seconds (DESCRIPTOR_RETRY_INTERVAL) in main.c. */
  1953. }
  1954. /** Given a directory <b>resource</b> request, containing zero
  1955. * or more strings separated by plus signs, followed optionally by ".z", store
  1956. * the strings, in order, into <b>fp_out</b>. If <b>compressed_out</b> is
  1957. * non-NULL, set it to 1 if the resource ends in ".z", else set it to 0. If
  1958. * decode_hex is true, then delete all elements that aren't hex digests, and
  1959. * decode the rest. If sort_uniq is true, then sort the list and remove
  1960. * all duplicates.
  1961. */
  1962. int
  1963. dir_split_resource_into_fingerprints(const char *resource,
  1964. smartlist_t *fp_out, int *compressed_out,
  1965. int decode_hex, int sort_uniq)
  1966. {
  1967. smartlist_t *fp_tmp = smartlist_create();
  1968. tor_assert(fp_out);
  1969. smartlist_split_string(fp_tmp, resource, "+", 0, 0);
  1970. if (compressed_out)
  1971. *compressed_out = 0;
  1972. if (smartlist_len(fp_tmp)) {
  1973. char *last = smartlist_get(fp_tmp,smartlist_len(fp_tmp)-1);
  1974. size_t last_len = strlen(last);
  1975. if (last_len > 2 && !strcmp(last+last_len-2, ".z")) {
  1976. last[last_len-2] = '\0';
  1977. if (compressed_out)
  1978. *compressed_out = 1;
  1979. }
  1980. }
  1981. if (decode_hex) {
  1982. int i;
  1983. char *cp, *d = NULL;
  1984. for (i = 0; i < smartlist_len(fp_tmp); ++i) {
  1985. cp = smartlist_get(fp_tmp, i);
  1986. if (strlen(cp) != HEX_DIGEST_LEN) {
  1987. log_info(LD_DIR,
  1988. "Skipping digest %s with non-standard length.", escaped(cp));
  1989. smartlist_del_keeporder(fp_tmp, i--);
  1990. goto again;
  1991. }
  1992. d = tor_malloc_zero(DIGEST_LEN);
  1993. if (base16_decode(d, DIGEST_LEN, cp, HEX_DIGEST_LEN)<0) {
  1994. log_info(LD_DIR, "Skipping non-decodable digest %s", escaped(cp));
  1995. smartlist_del_keeporder(fp_tmp, i--);
  1996. goto again;
  1997. }
  1998. smartlist_set(fp_tmp, i, d);
  1999. d = NULL;
  2000. again:
  2001. tor_free(cp);
  2002. tor_free(d);
  2003. }
  2004. }
  2005. if (sort_uniq) {
  2006. smartlist_t *fp_tmp2 = smartlist_create();
  2007. int i;
  2008. if (decode_hex)
  2009. smartlist_sort_digests(fp_tmp);
  2010. else
  2011. smartlist_sort_strings(fp_tmp);
  2012. if (smartlist_len(fp_tmp))
  2013. smartlist_add(fp_tmp2, smartlist_get(fp_tmp, 0));
  2014. for (i = 1; i < smartlist_len(fp_tmp); ++i) {
  2015. char *cp = smartlist_get(fp_tmp, i);
  2016. char *last = smartlist_get(fp_tmp2, smartlist_len(fp_tmp2)-1);
  2017. if ((decode_hex && memcmp(cp, last, DIGEST_LEN))
  2018. || (!decode_hex && strcasecmp(cp, last)))
  2019. smartlist_add(fp_tmp2, cp);
  2020. else
  2021. tor_free(cp);
  2022. }
  2023. smartlist_free(fp_tmp);
  2024. fp_tmp = fp_tmp2;
  2025. }
  2026. smartlist_add_all(fp_out, fp_tmp);
  2027. smartlist_free(fp_tmp);
  2028. return 0;
  2029. }