directory.c 76 KB

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