directory.c 74 KB

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