directory.c 75 KB

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