directory.c 66 KB

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