directory.c 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142
  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. /* There's no need to call this here: we already call it every 10 seconds *
  334. * (DESCRIPTOR_RETRY_INTERVAL) in main.c -NM */
  335. /* update_router_descriptor_downloads(time(NULL)); */
  336. (void) conn;
  337. }
  338. /** Helper for directory_initiate_command_(router|trusted_dir): send the
  339. * command to a server whose address is <b>address</b>, whose IP is
  340. * <b>addr</b>, whose directory port is <b>dir_port</b>, whose tor version
  341. * <b>supports_begindir</b>, and whose identity key digest is
  342. * <b>digest</b>. */
  343. void
  344. directory_initiate_command(const char *address, uint32_t addr,
  345. uint16_t dir_port, int supports_begindir,
  346. const char *digest, uint8_t purpose,
  347. int private_connection, const char *resource,
  348. const char *payload, size_t payload_len)
  349. {
  350. dir_connection_t *conn;
  351. or_options_t *options = get_options();
  352. int want_to_tunnel = options->TunnelDirConns && supports_begindir;
  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'", fwd);
  662. tor_free(fwd);
  663. return;
  664. }
  665. tor_free(conn->address);
  666. conn->address = tor_strdup(fwd);
  667. tor_free(fwd);
  668. }
  669. }
  670. /** Parse an HTTP response string <b>headers</b> of the form
  671. * \verbatim
  672. * "HTTP/1.\%d \%d\%s\r\n...".
  673. * \endverbatim
  674. *
  675. * If it's well-formed, assign the status code to *<b>code</b> and
  676. * return 0. Otherwise, return -1.
  677. *
  678. * On success: If <b>date</b> is provided, set *date to the Date
  679. * header in the http headers, or 0 if no such header is found. If
  680. * <b>compression</b> is provided, set *<b>compression</b> to the
  681. * compression method given in the Content-Encoding header, or 0 if no
  682. * such header is found, or -1 if the value of the header is not
  683. * recognized. If <b>reason</b> is provided, strdup the reason string
  684. * into it.
  685. */
  686. int
  687. parse_http_response(const char *headers, int *code, time_t *date,
  688. compress_method_t *compression, char **reason)
  689. {
  690. int n1, n2;
  691. char datestr[RFC1123_TIME_LEN+1];
  692. smartlist_t *parsed_headers;
  693. tor_assert(headers);
  694. tor_assert(code);
  695. while (TOR_ISSPACE(*headers)) headers++; /* tolerate leading whitespace */
  696. if (sscanf(headers, "HTTP/1.%d %d", &n1, &n2) < 2 ||
  697. (n1 != 0 && n1 != 1) ||
  698. (n2 < 100 || n2 >= 600)) {
  699. log_warn(LD_HTTP,"Failed to parse header %s",escaped(headers));
  700. return -1;
  701. }
  702. *code = n2;
  703. parsed_headers = smartlist_create();
  704. smartlist_split_string(parsed_headers, headers, "\n",
  705. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  706. if (reason) {
  707. smartlist_t *status_line_elements = smartlist_create();
  708. tor_assert(smartlist_len(parsed_headers));
  709. smartlist_split_string(status_line_elements,
  710. smartlist_get(parsed_headers, 0),
  711. " ", SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 3);
  712. tor_assert(smartlist_len(status_line_elements) <= 3);
  713. if (smartlist_len(status_line_elements) == 3) {
  714. *reason = smartlist_get(status_line_elements, 2);
  715. smartlist_set(status_line_elements, 2, NULL); /* Prevent free */
  716. }
  717. SMARTLIST_FOREACH(status_line_elements, char *, cp, tor_free(cp));
  718. smartlist_free(status_line_elements);
  719. }
  720. if (date) {
  721. *date = 0;
  722. SMARTLIST_FOREACH(parsed_headers, const char *, s,
  723. if (!strcmpstart(s, "Date: ")) {
  724. strlcpy(datestr, s+6, sizeof(datestr));
  725. /* This will do nothing on failure, so we don't need to check
  726. the result. We shouldn't warn, since there are many other valid
  727. date formats besides the one we use. */
  728. parse_rfc1123_time(datestr, date);
  729. break;
  730. });
  731. }
  732. if (compression) {
  733. const char *enc = NULL;
  734. SMARTLIST_FOREACH(parsed_headers, const char *, s,
  735. if (!strcmpstart(s, "Content-Encoding: ")) {
  736. enc = s+18; break;
  737. });
  738. if (!enc || !strcmp(enc, "identity")) {
  739. *compression = NO_METHOD;
  740. } else if (!strcmp(enc, "deflate") || !strcmp(enc, "x-deflate")) {
  741. *compression = ZLIB_METHOD;
  742. } else if (!strcmp(enc, "gzip") || !strcmp(enc, "x-gzip")) {
  743. *compression = GZIP_METHOD;
  744. } else {
  745. log_info(LD_HTTP, "Unrecognized content encoding: %s. Trying to deal.",
  746. escaped(enc));
  747. *compression = UNKNOWN_METHOD;
  748. }
  749. }
  750. SMARTLIST_FOREACH(parsed_headers, char *, s, tor_free(s));
  751. smartlist_free(parsed_headers);
  752. return 0;
  753. }
  754. /** Return true iff <b>body</b> doesn't start with a plausible router or
  755. * running-list or directory opening. This is a sign of possible compression.
  756. **/
  757. static int
  758. body_is_plausible(const char *body, size_t len, int purpose)
  759. {
  760. int i;
  761. if (len == 0)
  762. return 1; /* empty bodies don't need decompression */
  763. if (len < 32)
  764. return 0;
  765. if (purpose != DIR_PURPOSE_FETCH_RENDDESC) {
  766. if (!strcmpstart(body,"router") ||
  767. !strcmpstart(body,"signed-directory") ||
  768. !strcmpstart(body,"network-status") ||
  769. !strcmpstart(body,"running-routers"))
  770. return 1;
  771. for (i=0;i<32;++i) {
  772. if (!TOR_ISPRINT(body[i]) && !TOR_ISSPACE(body[i]))
  773. return 0;
  774. }
  775. return 1;
  776. } else {
  777. return 1;
  778. }
  779. }
  780. /** We are a client, and we've finished reading the server's
  781. * response. Parse and it and act appropriately.
  782. *
  783. * If we're still happy with using this directory server in the future, return
  784. * 0. Otherwise return -1; and the caller should consider trying the request
  785. * again.
  786. *
  787. * The caller will take care of marking the connection for close.
  788. */
  789. static int
  790. connection_dir_client_reached_eof(dir_connection_t *conn)
  791. {
  792. char *body;
  793. char *headers;
  794. char *reason = NULL;
  795. size_t body_len=0, orig_len=0;
  796. int status_code;
  797. time_t date_header=0;
  798. int delta;
  799. compress_method_t compression;
  800. int plausible;
  801. int skewed=0;
  802. int allow_partial = conn->_base.purpose == DIR_PURPOSE_FETCH_SERVERDESC;
  803. int was_compressed=0;
  804. switch (fetch_from_buf_http(conn->_base.inbuf,
  805. &headers, MAX_HEADERS_SIZE,
  806. &body, &body_len, MAX_DIR_SIZE,
  807. allow_partial)) {
  808. case -1: /* overflow */
  809. log_warn(LD_PROTOCOL,
  810. "'fetch' response too large (server '%s:%d'). Closing.",
  811. conn->_base.address, conn->_base.port);
  812. return -1;
  813. case 0:
  814. log_info(LD_HTTP,
  815. "'fetch' response not all here, but we're at eof. Closing.");
  816. return -1;
  817. /* case 1, fall through */
  818. }
  819. orig_len = body_len;
  820. if (parse_http_response(headers, &status_code, &date_header,
  821. &compression, &reason) < 0) {
  822. log_warn(LD_HTTP,"Unparseable headers (server '%s:%d'). Closing.",
  823. conn->_base.address, conn->_base.port);
  824. tor_free(body); tor_free(headers);
  825. return -1;
  826. }
  827. if (!reason) reason = tor_strdup("[no reason given]");
  828. log_debug(LD_DIR,
  829. "Received response from directory server '%s:%d': %d %s",
  830. conn->_base.address, conn->_base.port, status_code,
  831. escaped(reason));
  832. /* now check if it's got any hints for us about our IP address. */
  833. if (conn->dirconn_direct) {
  834. char *guess = http_get_header(headers, X_ADDRESS_HEADER);
  835. if (guess) {
  836. router_new_address_suggestion(guess);
  837. tor_free(guess);
  838. }
  839. }
  840. if (date_header > 0) {
  841. /* The date header was written very soon after we sent our request,
  842. * so compute the skew as the difference between sending the request
  843. * and the date header. (We used to check now-date_header, but that's
  844. * inaccurate if we spend a lot of time downloading.)
  845. */
  846. delta = conn->_base.timestamp_lastwritten - date_header;
  847. if (abs(delta)>ALLOW_DIRECTORY_TIME_SKEW) {
  848. int trusted = router_digest_is_trusted_dir(conn->identity_digest);
  849. log_fn(trusted ? LOG_WARN : LOG_INFO,
  850. LD_HTTP,
  851. "Received directory with skewed time (server '%s:%d'): "
  852. "we are %d minutes %s, or the directory is %d minutes %s.",
  853. conn->_base.address, conn->_base.port,
  854. abs(delta)/60, delta>0 ? "ahead" : "behind",
  855. abs(delta)/60, delta>0 ? "behind" : "ahead");
  856. skewed = 1; /* don't check the recommended-versions line */
  857. control_event_general_status(trusted ? LOG_WARN : LOG_NOTICE,
  858. "CLOCK_SKEW SKEW=%d SOURCE=DIRSERV:%s:%d",
  859. delta, conn->_base.address, conn->_base.port);
  860. } else {
  861. log_debug(LD_HTTP, "Time on received directory is within tolerance; "
  862. "we are %d seconds skewed. (That's okay.)", delta);
  863. }
  864. }
  865. (void) skewed; /* skewed isn't used yet. */
  866. if (status_code == 503) {
  867. local_routerstatus_t *rs;
  868. trusted_dir_server_t *ds;
  869. time_t now = time(NULL);
  870. log_info(LD_DIR,"Received http status code %d (%s) from server "
  871. "'%s:%d'. I'll try again soon.",
  872. status_code, escaped(reason), conn->_base.address,
  873. conn->_base.port);
  874. if ((rs = router_get_combined_status_by_digest(conn->identity_digest)))
  875. rs->last_dir_503_at = now;
  876. if ((ds = router_get_trusteddirserver_by_digest(conn->identity_digest)))
  877. ds->fake_status.last_dir_503_at = now;
  878. tor_free(body); tor_free(headers); tor_free(reason);
  879. return -1;
  880. }
  881. plausible = body_is_plausible(body, body_len, conn->_base.purpose);
  882. if (compression != NO_METHOD || !plausible) {
  883. char *new_body = NULL;
  884. size_t new_len = 0;
  885. compress_method_t guessed = detect_compression_method(body, body_len);
  886. if (compression == UNKNOWN_METHOD || guessed != compression) {
  887. /* Tell the user if we don't believe what we're told about compression.*/
  888. const char *description1, *description2;
  889. if (compression == ZLIB_METHOD)
  890. description1 = "as deflated";
  891. else if (compression == GZIP_METHOD)
  892. description1 = "as gzipped";
  893. else if (compression == NO_METHOD)
  894. description1 = "as uncompressed";
  895. else
  896. description1 = "with an unknown Content-Encoding";
  897. if (guessed == ZLIB_METHOD)
  898. description2 = "deflated";
  899. else if (guessed == GZIP_METHOD)
  900. description2 = "gzipped";
  901. else if (!plausible)
  902. description2 = "confusing binary junk";
  903. else
  904. description2 = "uncompressed";
  905. log_info(LD_HTTP, "HTTP body from server '%s:%d' was labeled %s, "
  906. "but it seems to be %s.%s",
  907. conn->_base.address, conn->_base.port, description1,
  908. description2,
  909. (compression>0 && guessed>0)?" Trying both.":"");
  910. }
  911. /* Try declared compression first if we can. */
  912. if (compression == GZIP_METHOD || compression == ZLIB_METHOD)
  913. tor_gzip_uncompress(&new_body, &new_len, body, body_len, compression,
  914. !allow_partial, LOG_PROTOCOL_WARN);
  915. /* Okay, if that didn't work, and we think that it was compressed
  916. * differently, try that. */
  917. if (!new_body &&
  918. (guessed == GZIP_METHOD || guessed == ZLIB_METHOD) &&
  919. compression != guessed)
  920. tor_gzip_uncompress(&new_body, &new_len, body, body_len, guessed,
  921. !allow_partial, LOG_PROTOCOL_WARN);
  922. /* If we're pretty sure that we have a compressed directory, and
  923. * we didn't manage to uncompress it, then warn and bail. */
  924. if (!plausible && !new_body) {
  925. log_fn(LOG_PROTOCOL_WARN, LD_HTTP,
  926. "Unable to decompress HTTP body (server '%s:%d').",
  927. conn->_base.address, conn->_base.port);
  928. tor_free(body); tor_free(headers); tor_free(reason);
  929. return -1;
  930. }
  931. if (new_body) {
  932. tor_free(body);
  933. body = new_body;
  934. body_len = new_len;
  935. was_compressed = 1;
  936. }
  937. }
  938. if (conn->_base.purpose == DIR_PURPOSE_FETCH_DIR) {
  939. /* fetch/process the directory to cache it. */
  940. log_info(LD_DIR,"Received directory (size %d) from server '%s:%d'",
  941. (int)body_len, conn->_base.address, conn->_base.port);
  942. if (status_code != 200) {
  943. log_warn(LD_DIR,"Received http status code %d (%s) from server "
  944. "'%s:%d' while fetching directory. I'll try again soon.",
  945. status_code, escaped(reason), conn->_base.address,
  946. conn->_base.port);
  947. tor_free(body); tor_free(headers); tor_free(reason);
  948. return -1;
  949. }
  950. if (router_parse_directory(body) < 0) {
  951. log_notice(LD_DIR,"I failed to parse the directory I fetched from "
  952. "'%s:%d'. Ignoring.", conn->_base.address, conn->_base.port);
  953. }
  954. note_request(was_compressed?"dl/dir.z":"dl/dir", orig_len);
  955. }
  956. if (conn->_base.purpose == DIR_PURPOSE_FETCH_RUNNING_LIST) {
  957. /* just update our list of running routers, if this list is new info */
  958. log_info(LD_DIR,"Received running-routers list (size %d)", (int)body_len);
  959. if (status_code != 200) {
  960. log_warn(LD_DIR,"Received http status code %d (%s) from server "
  961. "'%s:%d' while fetching running-routers. I'll try again soon.",
  962. status_code, escaped(reason), conn->_base.address,
  963. conn->_base.port);
  964. tor_free(body); tor_free(headers); tor_free(reason);
  965. return -1;
  966. }
  967. if (router_parse_runningrouters(body)<0) {
  968. log_warn(LD_DIR,
  969. "Bad running-routers from server '%s:%d'. I'll try again soon.",
  970. conn->_base.address, conn->_base.port);
  971. tor_free(body); tor_free(headers); tor_free(reason);
  972. return -1;
  973. }
  974. note_request(was_compressed?"dl/running-routers.z":
  975. "dl/running-routers", orig_len);
  976. }
  977. if (conn->_base.purpose == DIR_PURPOSE_FETCH_NETWORKSTATUS) {
  978. smartlist_t *which = NULL;
  979. networkstatus_source_t source;
  980. char *cp;
  981. log_info(LD_DIR,"Received networkstatus objects (size %d) from server "
  982. "'%s:%d'",(int) body_len, conn->_base.address, conn->_base.port);
  983. if (status_code != 200) {
  984. log_warn(LD_DIR,
  985. "Received http status code %d (%s) from server "
  986. "'%s:%d' while fetching \"/tor/status/%s\". I'll try again soon.",
  987. status_code, escaped(reason), conn->_base.address,
  988. conn->_base.port, conn->requested_resource);
  989. tor_free(body); tor_free(headers); tor_free(reason);
  990. connection_dir_download_networkstatus_failed(conn, status_code);
  991. return -1;
  992. }
  993. note_request(was_compressed?"dl/status.z":"dl/status", orig_len);
  994. if (conn->requested_resource &&
  995. !strcmpstart(conn->requested_resource,"fp/")) {
  996. source = NS_FROM_DIR_BY_FP;
  997. which = smartlist_create();
  998. dir_split_resource_into_fingerprints(conn->requested_resource+3,
  999. which, NULL, 0, 0);
  1000. } else if (conn->requested_resource &&
  1001. !strcmpstart(conn->requested_resource, "all")) {
  1002. source = NS_FROM_DIR_ALL;
  1003. which = smartlist_create();
  1004. SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
  1005. trusted_dir_server_t *, ds,
  1006. {
  1007. char *cp = tor_malloc(HEX_DIGEST_LEN+1);
  1008. base16_encode(cp, HEX_DIGEST_LEN+1, ds->digest, DIGEST_LEN);
  1009. smartlist_add(which, cp);
  1010. });
  1011. } else {
  1012. /* Can we even end up here? -- weasel*/
  1013. source = NS_FROM_DIR_BY_FP;
  1014. log_warn(LD_BUG, "We received a networkstatus but we didn't ask "
  1015. "for it by fp, nor did we ask for all.");
  1016. }
  1017. cp = body;
  1018. while (*cp) {
  1019. char *next = strstr(cp, "\nnetwork-status-version");
  1020. if (next)
  1021. next[1] = '\0';
  1022. /* learn from it, and then remove it from 'which' */
  1023. if (router_set_networkstatus(cp, time(NULL), source, which)<0)
  1024. break;
  1025. if (next) {
  1026. next[1] = 'n';
  1027. cp = next+1;
  1028. }
  1029. else
  1030. break;
  1031. }
  1032. routers_update_all_from_networkstatus(); /*launches router downloads*/
  1033. directory_info_has_arrived(time(NULL), 0);
  1034. if (which) {
  1035. if (smartlist_len(which)) {
  1036. dir_networkstatus_download_failed(which, status_code);
  1037. }
  1038. SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
  1039. smartlist_free(which);
  1040. }
  1041. }
  1042. if (conn->_base.purpose == DIR_PURPOSE_FETCH_SERVERDESC) {
  1043. smartlist_t *which = NULL;
  1044. int n_asked_for = 0;
  1045. log_info(LD_DIR,"Received server info (size %d) from server '%s:%d'",
  1046. (int)body_len, conn->_base.address, conn->_base.port);
  1047. note_request(was_compressed?"dl/server.z":"dl/server", orig_len);
  1048. if (conn->requested_resource &&
  1049. !strcmpstart(conn->requested_resource,"d/")) {
  1050. which = smartlist_create();
  1051. dir_split_resource_into_fingerprints(conn->requested_resource+2,
  1052. which, NULL, 0, 0);
  1053. n_asked_for = smartlist_len(which);
  1054. }
  1055. if (status_code != 200) {
  1056. int dir_okay = status_code == 404 ||
  1057. (status_code == 400 && !strcmp(reason, "Servers unavailable."));
  1058. /* 404 means that it didn't have them; no big deal.
  1059. * Older (pre-0.1.1.8) servers said 400 Servers unavailable instead. */
  1060. log_fn(dir_okay ? LOG_INFO : LOG_WARN, LD_DIR,
  1061. "Received http status code %d (%s) from server '%s:%d' "
  1062. "while fetching \"/tor/server/%s\". I'll try again soon.",
  1063. status_code, escaped(reason), conn->_base.address,
  1064. conn->_base.port, conn->requested_resource);
  1065. if (!which) {
  1066. connection_dir_download_routerdesc_failed(conn);
  1067. } else {
  1068. dir_routerdesc_download_failed(which, status_code);
  1069. SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
  1070. smartlist_free(which);
  1071. }
  1072. tor_free(body); tor_free(headers); tor_free(reason);
  1073. return dir_okay ? 0 : -1;
  1074. }
  1075. /* Learn the routers, assuming we requested by fingerprint or "all".
  1076. * Right now, we only use "authority" to fetch ourself, so we don't want
  1077. * to risk replacing ourself with a router running at the addr:port we
  1078. * think we have.
  1079. */
  1080. if (which || (conn->requested_resource &&
  1081. !strcmpstart(conn->requested_resource, "all"))) {
  1082. /* as we learn from them, we remove them from 'which' */
  1083. router_load_routers_from_string(body, SAVED_NOWHERE, which);
  1084. directory_info_has_arrived(time(NULL), 0);
  1085. }
  1086. if (which) { /* mark remaining ones as failed */
  1087. log_info(LD_DIR, "Received %d/%d routers requested from %s:%d",
  1088. n_asked_for-smartlist_len(which), n_asked_for,
  1089. conn->_base.address, (int)conn->_base.port);
  1090. if (smartlist_len(which)) {
  1091. dir_routerdesc_download_failed(which, status_code);
  1092. }
  1093. SMARTLIST_FOREACH(which, char *, cp, tor_free(cp));
  1094. smartlist_free(which);
  1095. }
  1096. if (directory_conn_is_self_reachability_test(conn))
  1097. router_dirport_found_reachable();
  1098. }
  1099. if (conn->_base.purpose == DIR_PURPOSE_UPLOAD_DIR) {
  1100. switch (status_code) {
  1101. case 200: {
  1102. int all_done = 1;
  1103. trusted_dir_server_t *ds =
  1104. router_get_trusteddirserver_by_digest(conn->identity_digest);
  1105. smartlist_t *servers;
  1106. log_info(LD_GENERAL,"eof (status 200) after uploading server "
  1107. "descriptor: finished.");
  1108. control_event_server_status(
  1109. LOG_NOTICE, "ACCEPTED_SERVER_DESCRIPTOR DIRAUTH=%s:%d",
  1110. conn->_base.address, conn->_base.port);
  1111. ds->has_accepted_serverdesc = 1;
  1112. servers = router_get_trusted_dir_servers();
  1113. SMARTLIST_FOREACH(servers, trusted_dir_server_t *, d, {
  1114. if ((d->is_v1_authority || d->is_v2_authority) &&
  1115. !d->has_accepted_serverdesc) {
  1116. all_done = 0;
  1117. break;
  1118. }
  1119. });
  1120. if (all_done)
  1121. control_event_server_status(LOG_NOTICE, "GOOD_SERVER_DESCRIPTOR");
  1122. }
  1123. break;
  1124. case 400:
  1125. log_warn(LD_GENERAL,"http status 400 (%s) response from "
  1126. "dirserver '%s:%d'. Please correct.",
  1127. escaped(reason), conn->_base.address, conn->_base.port);
  1128. control_event_server_status(LOG_WARN,
  1129. "BAD_SERVER_DESCRIPTOR DIRAUTH=%s:%d REASON=\"%s\"",
  1130. conn->_base.address, conn->_base.port, escaped(reason));
  1131. break;
  1132. case 403:
  1133. log_warn(LD_GENERAL,
  1134. "http status 403 (%s) response from dirserver "
  1135. "'%s:%d'. Is your clock skewed? Have you mailed us your key "
  1136. "fingerprint? Are you using the right key? Are you using a "
  1137. "private IP address? See http://tor.eff.org/doc/"
  1138. "tor-doc-server.html",escaped(reason), conn->_base.address,
  1139. conn->_base.port);
  1140. control_event_server_status(LOG_WARN,
  1141. "BAD_SERVER_DESCRIPTOR DIRAUTH=%s:%d REASON=\"%s\"",
  1142. conn->_base.address, conn->_base.port, escaped(reason));
  1143. break;
  1144. default:
  1145. log_warn(LD_GENERAL,
  1146. "http status %d (%s) reason unexpected while uploading "
  1147. "descriptor to server '%s:%d').",
  1148. status_code, escaped(reason), conn->_base.address,
  1149. conn->_base.port);
  1150. break;
  1151. }
  1152. /* return 0 in all cases, since we don't want to mark any
  1153. * dirservers down just because they don't like us. */
  1154. }
  1155. if (conn->_base.purpose == DIR_PURPOSE_FETCH_RENDDESC) {
  1156. log_info(LD_REND,"Received rendezvous descriptor (size %d, status %d "
  1157. "(%s))",
  1158. (int)body_len, status_code, escaped(reason));
  1159. switch (status_code) {
  1160. case 200:
  1161. if (rend_cache_store(body, body_len) < 0) {
  1162. log_warn(LD_REND,"Failed to store rendezvous descriptor.");
  1163. /* alice's ap_stream will notice when connection_mark_for_close
  1164. * cleans it up */
  1165. } else {
  1166. /* success. notify pending connections about this. */
  1167. conn->_base.purpose = DIR_PURPOSE_HAS_FETCHED_RENDDESC;
  1168. rend_client_desc_here(conn->rend_query);
  1169. }
  1170. break;
  1171. case 404:
  1172. /* not there. pending connections will be notified when
  1173. * connection_mark_for_close cleans it up. */
  1174. break;
  1175. case 400:
  1176. log_warn(LD_REND,
  1177. "http status 400 (%s). Dirserver didn't like our "
  1178. "rendezvous query?", escaped(reason));
  1179. break;
  1180. default:
  1181. log_warn(LD_REND,"http status %d (%s) response unexpected while "
  1182. "fetching hidden service descriptor (server '%s:%d').",
  1183. status_code, escaped(reason), conn->_base.address,
  1184. conn->_base.port);
  1185. break;
  1186. }
  1187. }
  1188. if (conn->_base.purpose == DIR_PURPOSE_UPLOAD_RENDDESC) {
  1189. switch (status_code) {
  1190. case 200:
  1191. log_info(LD_REND,
  1192. "Uploading rendezvous descriptor: finished with status "
  1193. "200 (%s)", escaped(reason));
  1194. break;
  1195. case 400:
  1196. log_warn(LD_REND,"http status 400 (%s) response from dirserver "
  1197. "'%s:%d'. Malformed rendezvous descriptor?",
  1198. escaped(reason), conn->_base.address, conn->_base.port);
  1199. break;
  1200. default:
  1201. log_warn(LD_REND,"http status %d (%s) response unexpected (server "
  1202. "'%s:%d').",
  1203. status_code, escaped(reason), conn->_base.address,
  1204. conn->_base.port);
  1205. break;
  1206. }
  1207. }
  1208. tor_free(body); tor_free(headers); tor_free(reason);
  1209. return 0;
  1210. }
  1211. /** Called when a directory connection reaches EOF */
  1212. int
  1213. connection_dir_reached_eof(dir_connection_t *conn)
  1214. {
  1215. int retval;
  1216. if (conn->_base.state != DIR_CONN_STATE_CLIENT_READING) {
  1217. log_info(LD_HTTP,"conn reached eof, not reading. Closing.");
  1218. connection_close_immediate(TO_CONN(conn)); /* error: give up on flushing */
  1219. connection_mark_for_close(TO_CONN(conn));
  1220. return -1;
  1221. }
  1222. retval = connection_dir_client_reached_eof(conn);
  1223. if (retval == 0) /* success */
  1224. conn->_base.state = DIR_CONN_STATE_CLIENT_FINISHED;
  1225. connection_mark_for_close(TO_CONN(conn));
  1226. return retval;
  1227. }
  1228. /** If any directory object is arriving, and it's over 10MB large, we're
  1229. * getting DoS'd. (As of 0.1.2.x, raw directories are about 1MB, and we never
  1230. * ask for more than 96 router descriptors at a time.)
  1231. */
  1232. #define MAX_DIRECTORY_OBJECT_SIZE (10*(1<<20))
  1233. /** Read handler for directory connections. (That's connections <em>to</em>
  1234. * directory servers and connections <em>at</em> directory servers.)
  1235. */
  1236. int
  1237. connection_dir_process_inbuf(dir_connection_t *conn)
  1238. {
  1239. tor_assert(conn);
  1240. tor_assert(conn->_base.type == CONN_TYPE_DIR);
  1241. /* Directory clients write, then read data until they receive EOF;
  1242. * directory servers read data until they get an HTTP command, then
  1243. * write their response (when it's finished flushing, they mark for
  1244. * close).
  1245. */
  1246. /* If we're on the dirserver side, look for a command. */
  1247. if (conn->_base.state == DIR_CONN_STATE_SERVER_COMMAND_WAIT) {
  1248. if (directory_handle_command(conn) < 0) {
  1249. connection_mark_for_close(TO_CONN(conn));
  1250. return -1;
  1251. }
  1252. return 0;
  1253. }
  1254. if (buf_datalen(conn->_base.inbuf) > MAX_DIRECTORY_OBJECT_SIZE) {
  1255. log_warn(LD_HTTP, "Too much data received from directory connection: "
  1256. "denial of service attempt, or you need to upgrade?");
  1257. connection_mark_for_close(TO_CONN(conn));
  1258. return -1;
  1259. }
  1260. if (!conn->_base.inbuf_reached_eof)
  1261. log_debug(LD_HTTP,"Got data, not eof. Leaving on inbuf.");
  1262. return 0;
  1263. }
  1264. /** Create an http response for the client <b>conn</b> out of
  1265. * <b>status</b> and <b>reason_phrase</b>. Write it to <b>conn</b>.
  1266. */
  1267. static void
  1268. write_http_status_line(dir_connection_t *conn, int status,
  1269. const char *reason_phrase)
  1270. {
  1271. char buf[256];
  1272. if (tor_snprintf(buf, sizeof(buf), "HTTP/1.0 %d %s\r\n\r\n",
  1273. status, reason_phrase) < 0) {
  1274. log_warn(LD_BUG,"Bug: status line too long.");
  1275. return;
  1276. }
  1277. connection_write_to_buf(buf, strlen(buf), TO_CONN(conn));
  1278. }
  1279. /** Write the header for an HTTP/1.0 response onto <b>conn</b>-\>outbuf,
  1280. * with <b>type</b> as the Content-Type.
  1281. *
  1282. * If <b>length</b> is nonnegative, it is the Content-Length.
  1283. * If <b>encoding</b> is provided, it is the Content-Encoding.
  1284. * If <b>cache_lifetime</b> is greater than 0, the content may be cached for
  1285. * up to cache_lifetime seconds. Otherwise, the content may not be cached. */
  1286. static void
  1287. write_http_response_header(dir_connection_t *conn, ssize_t length,
  1288. const char *type, const char *encoding,
  1289. int cache_lifetime)
  1290. {
  1291. char date[RFC1123_TIME_LEN+1];
  1292. char tmp[1024];
  1293. char *cp;
  1294. time_t now = time(NULL);
  1295. tor_assert(conn);
  1296. tor_assert(type);
  1297. format_rfc1123_time(date, now);
  1298. cp = tmp;
  1299. tor_snprintf(cp, sizeof(tmp),
  1300. "HTTP/1.0 200 OK\r\nDate: %s\r\nContent-Type: %s\r\n",
  1301. date, type);
  1302. cp += strlen(tmp);
  1303. if (!is_internal_IP(conn->_base.addr, 0)) {
  1304. /* Don't report the source address for a localhost/private connection. */
  1305. tor_snprintf(cp, sizeof(tmp)-(cp-tmp),
  1306. X_ADDRESS_HEADER "%s\r\n", conn->_base.address);
  1307. cp += strlen(cp);
  1308. }
  1309. if (encoding) {
  1310. tor_snprintf(cp, sizeof(tmp)-(cp-tmp),
  1311. "Content-Encoding: %s\r\n", encoding);
  1312. cp += strlen(cp);
  1313. }
  1314. if (length >= 0) {
  1315. tor_snprintf(cp, sizeof(tmp)-(cp-tmp),
  1316. "Content-Length: %ld\r\n", (long)length);
  1317. cp += strlen(cp);
  1318. }
  1319. if (cache_lifetime > 0) {
  1320. char expbuf[RFC1123_TIME_LEN+1];
  1321. format_rfc1123_time(expbuf, now + cache_lifetime);
  1322. /* We could say 'Cache-control: max-age=%d' here if we start doing
  1323. * http/1.1 */
  1324. tor_snprintf(cp, sizeof(tmp)-(cp-tmp),
  1325. "Expires: %s\r\n", expbuf);
  1326. cp += strlen(cp);
  1327. } else {
  1328. /* We could say 'Cache-control: no-cache' here if we start doing
  1329. * http/1.1 */
  1330. strlcpy(cp, "Pragma: no-cache\r\n", sizeof(tmp)-(cp-tmp));
  1331. cp += strlen(cp);
  1332. }
  1333. if (sizeof(tmp)-(cp-tmp) > 3)
  1334. memcpy(cp, "\r\n", 3);
  1335. else
  1336. tor_assert(0);
  1337. connection_write_to_buf(tmp, strlen(tmp), TO_CONN(conn));
  1338. }
  1339. /** Helper function: return 1 if there are any dir conns of purpose
  1340. * <b>purpose</b> that are going elsewhere than our own ORPort/Dirport.
  1341. * Else return 0.
  1342. */
  1343. static int
  1344. already_fetching_directory(int purpose)
  1345. {
  1346. int i, n;
  1347. connection_t *conn;
  1348. connection_t **carray;
  1349. get_connection_array(&carray,&n);
  1350. for (i=0;i<n;i++) {
  1351. conn = carray[i];
  1352. if (conn->type == CONN_TYPE_DIR &&
  1353. conn->purpose == purpose &&
  1354. !conn->marked_for_close &&
  1355. !router_digest_is_me(TO_DIR_CONN(conn)->identity_digest))
  1356. return 1;
  1357. }
  1358. return 0;
  1359. }
  1360. #undef INSTRUMENT_DOWNLOADS
  1361. #ifdef INSTRUMENT_DOWNLOADS
  1362. /** Map used to keep track of how much data we've up/downloaded in what kind
  1363. * of request. Maps from request type to pointer to uint64_t. */
  1364. static strmap_t *request_bytes_map = NULL;
  1365. /** Called when we just transmitted or received <b>bytes</b> worth of data
  1366. * because of a request of type <b>key</b> (an arbitrary identifier): adds
  1367. * <b>bytes</b> to the total associated with key. */
  1368. static void
  1369. note_request(const char *key, size_t bytes)
  1370. {
  1371. uint64_t *n;
  1372. if (!request_bytes_map)
  1373. request_bytes_map = strmap_new();
  1374. n = strmap_get(request_bytes_map, key);
  1375. if (!n) {
  1376. n = tor_malloc_zero(sizeof(uint64_t));
  1377. strmap_set(request_bytes_map, key, n);
  1378. }
  1379. *n += bytes;
  1380. }
  1381. /** Return a newly allocated string holding a summary of bytes used per
  1382. * request type. */
  1383. char *
  1384. directory_dump_request_log(void)
  1385. {
  1386. smartlist_t *lines;
  1387. char tmp[256];
  1388. char *result;
  1389. strmap_iter_t *iter;
  1390. if (!request_bytes_map)
  1391. request_bytes_map = strmap_new();
  1392. lines = smartlist_create();
  1393. for (iter = strmap_iter_init(request_bytes_map);
  1394. !strmap_iter_done(iter);
  1395. iter = strmap_iter_next(request_bytes_map, iter)) {
  1396. const char *key;
  1397. void *val;
  1398. uint64_t *n;
  1399. strmap_iter_get(iter, &key, &val);
  1400. n = val;
  1401. tor_snprintf(tmp, sizeof(tmp), "%s "U64_FORMAT"\n",
  1402. key, U64_PRINTF_ARG(*n));
  1403. smartlist_add(lines, tor_strdup(tmp));
  1404. }
  1405. smartlist_sort_strings(lines);
  1406. result = smartlist_join_strings(lines, "", 0, NULL);
  1407. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  1408. smartlist_free(lines);
  1409. return result;
  1410. }
  1411. #else
  1412. static void
  1413. note_request(const char *key, size_t bytes)
  1414. {
  1415. (void)key;
  1416. (void)bytes;
  1417. }
  1418. char *
  1419. directory_dump_request_log(void)
  1420. {
  1421. return tor_strdup("Not supported.");
  1422. }
  1423. #endif
  1424. /** Helper function: called when a dirserver gets a complete HTTP GET
  1425. * request. Look for a request for a directory or for a rendezvous
  1426. * service descriptor. On finding one, write a response into
  1427. * conn-\>outbuf. If the request is unrecognized, send a 400.
  1428. * Always return 0. */
  1429. static int
  1430. directory_handle_command_get(dir_connection_t *conn, const char *headers,
  1431. const char *body, size_t body_len)
  1432. {
  1433. size_t dlen;
  1434. const char *cp;
  1435. char *url = NULL;
  1436. or_options_t *options = get_options();
  1437. /* We ignore the body of a GET request. */
  1438. (void)body;
  1439. (void)body_len;
  1440. log_debug(LD_DIRSERV,"Received GET command.");
  1441. conn->_base.state = DIR_CONN_STATE_SERVER_WRITING;
  1442. if (parse_http_url(headers, &url) < 0) {
  1443. write_http_status_line(conn, 400, "Bad request");
  1444. return 0;
  1445. }
  1446. log_debug(LD_DIRSERV,"rewritten url as '%s'.", url);
  1447. if (!strcmp(url,"/tor/") || !strcmp(url,"/tor/dir.z")) { /* dir fetch */
  1448. int deflated = !strcmp(url,"/tor/dir.z");
  1449. cached_dir_t *d = dirserv_get_directory();
  1450. if (!d) {
  1451. log_notice(LD_DIRSERV,"Client asked for the mirrored directory, but we "
  1452. "don't have a good one yet. Sending 503 Dir not available.");
  1453. write_http_status_line(conn, 503, "Directory unavailable");
  1454. /* try to get a new one now */
  1455. if (!already_fetching_directory(DIR_PURPOSE_FETCH_DIR))
  1456. directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL, 1);
  1457. tor_free(url);
  1458. return 0;
  1459. }
  1460. dlen = deflated ? d->dir_z_len : d->dir_len;
  1461. if (global_write_bucket_low(TO_CONN(conn), dlen, 1)) {
  1462. log_info(LD_DIRSERV,
  1463. "Client asked for the mirrored directory, but we've been "
  1464. "writing too many bytes lately. Sending 503 Dir busy.");
  1465. write_http_status_line(conn, 503, "Directory busy, try again later");
  1466. tor_free(url);
  1467. return 0;
  1468. }
  1469. note_request(url, dlen);
  1470. tor_free(url);
  1471. log_debug(LD_DIRSERV,"Dumping %sdirectory to client.",
  1472. deflated?"deflated ":"");
  1473. write_http_response_header(conn, dlen,
  1474. deflated?"application/octet-stream":"text/plain",
  1475. deflated?"deflate":"identity",
  1476. FULL_DIR_CACHE_LIFETIME);
  1477. conn->cached_dir = d;
  1478. conn->cached_dir_offset = 0;
  1479. if (! deflated)
  1480. conn->zlib_state = tor_zlib_new(0, ZLIB_METHOD);
  1481. ++d->refcnt;
  1482. /* Prime the connection with some data. */
  1483. conn->dir_spool_src = DIR_SPOOL_CACHED_DIR;
  1484. connection_dirserv_flushed_some(conn);
  1485. return 0;
  1486. }
  1487. if (!strcmp(url,"/tor/running-routers") ||
  1488. !strcmp(url,"/tor/running-routers.z")) { /* running-routers fetch */
  1489. int deflated = !strcmp(url,"/tor/running-routers.z");
  1490. dlen = dirserv_get_runningrouters(&cp, deflated);
  1491. if (!dlen) { /* we failed to create/cache cp */
  1492. write_http_status_line(conn, 503, "Directory unavailable");
  1493. /* try to get a new one now */
  1494. if (!already_fetching_directory(DIR_PURPOSE_FETCH_RUNNING_LIST))
  1495. directory_get_from_dirserver(DIR_PURPOSE_FETCH_RUNNING_LIST, NULL, 1);
  1496. tor_free(url);
  1497. return 0;
  1498. }
  1499. if (global_write_bucket_low(TO_CONN(conn), dlen, 1)) {
  1500. log_info(LD_DIRSERV,
  1501. "Client asked for running-routers, but we've been "
  1502. "writing too many bytes lately. Sending 503 Dir busy.");
  1503. write_http_status_line(conn, 503, "Directory busy, try again later");
  1504. tor_free(url);
  1505. return 0;
  1506. }
  1507. note_request(url, dlen);
  1508. tor_free(url);
  1509. write_http_response_header(conn, dlen,
  1510. deflated?"application/octet-stream":"text/plain",
  1511. deflated?"deflate":"identity",
  1512. RUNNINGROUTERS_CACHE_LIFETIME);
  1513. connection_write_to_buf(cp, strlen(cp), TO_CONN(conn));
  1514. return 0;
  1515. }
  1516. if (!strcmpstart(url,"/tor/status/")) {
  1517. /* v2 network status fetch. */
  1518. size_t url_len = strlen(url);
  1519. int deflated = !strcmp(url+url_len-2, ".z");
  1520. smartlist_t *dir_fps = smartlist_create();
  1521. const char *request_type = NULL;
  1522. const char *key = url + strlen("/tor/status/");
  1523. if (deflated)
  1524. url[url_len-2] = '\0';
  1525. dirserv_get_networkstatus_v2_fingerprints(dir_fps, key);
  1526. if (!strcmpstart(key, "fp/"))
  1527. request_type = deflated?"/tor/status/fp.z":"/tor/status/fp";
  1528. else if (!strcmpstart(key, "authority"))
  1529. request_type = deflated?"/tor/status/authority.z":
  1530. "/tor/status/authority";
  1531. else if (!strcmpstart(key, "all"))
  1532. request_type = deflated?"/tor/status/all.z":"/tor/status/all";
  1533. else
  1534. request_type = "/tor/status/?";
  1535. tor_free(url);
  1536. if (!smartlist_len(dir_fps)) { /* we failed to create/cache cp */
  1537. write_http_status_line(conn, 503, "Network status object unavailable");
  1538. smartlist_free(dir_fps);
  1539. return 0;
  1540. }
  1541. dlen = dirserv_estimate_data_size(dir_fps, 0, deflated);
  1542. if (global_write_bucket_low(TO_CONN(conn), dlen, 2)) {
  1543. log_info(LD_DIRSERV,
  1544. "Client asked for network status lists, but we've been "
  1545. "writing too many bytes lately. Sending 503 Dir busy.");
  1546. write_http_status_line(conn, 503, "Directory busy, try again later");
  1547. SMARTLIST_FOREACH(dir_fps, char *, cp, tor_free(cp));
  1548. smartlist_free(dir_fps);
  1549. return 0;
  1550. }
  1551. // note_request(request_type,dlen);
  1552. (void) request_type;
  1553. write_http_response_header(conn, -1,
  1554. deflated?"application/octet_stream":"text/plain",
  1555. deflated?"deflate":NULL,
  1556. smartlist_len(dir_fps) == 1 ? NETWORKSTATUS_CACHE_LIFETIME:0);
  1557. conn->fingerprint_stack = dir_fps;
  1558. if (! deflated)
  1559. conn->zlib_state = tor_zlib_new(0, ZLIB_METHOD);
  1560. /* Prime the connection with some data. */
  1561. conn->dir_spool_src = DIR_SPOOL_NETWORKSTATUS;
  1562. connection_dirserv_flushed_some(conn);
  1563. return 0;
  1564. }
  1565. if (!strcmpstart(url,"/tor/server/")) {
  1566. size_t url_len = strlen(url);
  1567. int deflated = !strcmp(url+url_len-2, ".z");
  1568. int res;
  1569. const char *msg;
  1570. const char *request_type = NULL;
  1571. int cache_lifetime = 0;
  1572. if (deflated)
  1573. url[url_len-2] = '\0';
  1574. conn->fingerprint_stack = smartlist_create();
  1575. res = dirserv_get_routerdesc_fingerprints(conn->fingerprint_stack, url,
  1576. &msg);
  1577. if (!strcmpstart(url, "/tor/server/fp/")) {
  1578. request_type = deflated?"/tor/server/fp.z":"/tor/server/fp";
  1579. if (smartlist_len(conn->fingerprint_stack) == 1)
  1580. cache_lifetime = ROUTERDESC_CACHE_LIFETIME;
  1581. } else if (!strcmpstart(url, "/tor/server/authority")) {
  1582. request_type = deflated?"/tor/server/authority.z":
  1583. "/tor/server/authority";
  1584. cache_lifetime = ROUTERDESC_CACHE_LIFETIME;
  1585. } else if (!strcmpstart(url, "/tor/server/all")) {
  1586. request_type = deflated?"/tor/server/all.z":"/tor/server/all";
  1587. cache_lifetime = FULL_DIR_CACHE_LIFETIME;
  1588. } else if (!strcmpstart(url, "/tor/server/d/")) {
  1589. request_type = deflated?"/tor/server/d.z":"/tor/server/d";
  1590. if (smartlist_len(conn->fingerprint_stack) == 1)
  1591. cache_lifetime = ROUTERDESC_BY_DIGEST_CACHE_LIFETIME;
  1592. } else {
  1593. request_type = "/tor/server/?";
  1594. }
  1595. (void) request_type; /* usable for note_request. */
  1596. if (!strcmpstart(url, "/tor/server/d/"))
  1597. conn->dir_spool_src = DIR_SPOOL_SERVER_BY_DIGEST;
  1598. else
  1599. conn->dir_spool_src = DIR_SPOOL_SERVER_BY_FP;
  1600. tor_free(url);
  1601. if (res < 0)
  1602. write_http_status_line(conn, 404, msg);
  1603. else {
  1604. dlen = dirserv_estimate_data_size(conn->fingerprint_stack,
  1605. 1, deflated);
  1606. if (global_write_bucket_low(TO_CONN(conn), dlen, 2)) {
  1607. log_info(LD_DIRSERV,
  1608. "Client asked for server descriptors, but we've been "
  1609. "writing too many bytes lately. Sending 503 Dir busy.");
  1610. write_http_status_line(conn, 503, "Directory busy, try again later");
  1611. return 0;
  1612. }
  1613. write_http_response_header(conn, -1,
  1614. deflated?"application/octet_stream":"text/plain",
  1615. deflated?"deflate":NULL, cache_lifetime);
  1616. if (deflated)
  1617. conn->zlib_state = tor_zlib_new(1, ZLIB_METHOD);
  1618. /* Prime the connection with some data. */
  1619. connection_dirserv_flushed_some(conn);
  1620. }
  1621. return 0;
  1622. }
  1623. if (options->HSAuthoritativeDir &&
  1624. (!strcmpstart(url,"/tor/rendezvous/") ||
  1625. !strcmpstart(url,"/tor/rendezvous1/"))) {
  1626. /* rendezvous descriptor fetch */
  1627. const char *descp;
  1628. size_t desc_len;
  1629. int versioned = !strcmpstart(url,"/tor/rendezvous1/");
  1630. const char *query = url+strlen("/tor/rendezvous/")+(versioned?1:0);
  1631. switch (rend_cache_lookup_desc(query, versioned?-1:0, &descp, &desc_len)) {
  1632. case 1: /* valid */
  1633. write_http_response_header(conn, desc_len, "application/octet-stream",
  1634. NULL, 0);
  1635. note_request("/tor/rendezvous?/", desc_len);
  1636. /* need to send descp separately, because it may include nuls */
  1637. connection_write_to_buf(descp, desc_len, TO_CONN(conn));
  1638. break;
  1639. case 0: /* well-formed but not present */
  1640. write_http_status_line(conn, 404, "Not found");
  1641. break;
  1642. case -1: /* not well-formed */
  1643. write_http_status_line(conn, 400, "Bad request");
  1644. break;
  1645. }
  1646. tor_free(url);
  1647. return 0;
  1648. }
  1649. if (!strcmpstart(url,"/tor/bytes.txt")) {
  1650. char *bytes = directory_dump_request_log();
  1651. size_t len = strlen(bytes);
  1652. write_http_response_header(conn, len, "text/plain", NULL, 0);
  1653. connection_write_to_buf(bytes, len, TO_CONN(conn));
  1654. tor_free(bytes);
  1655. tor_free(url);
  1656. return 0;
  1657. }
  1658. if (!strcmp(url,"/tor/robots.txt")) { /* /robots.txt will have been
  1659. rewritten to /tor/robots.txt */
  1660. char robots[] = "User-agent: *\r\nDisallow: /\r\n";
  1661. size_t len = strlen(robots);
  1662. write_http_response_header(conn, len, "text/plain", NULL,
  1663. ROBOTS_CACHE_LIFETIME);
  1664. connection_write_to_buf(robots, len, TO_CONN(conn));
  1665. tor_free(url);
  1666. return 0;
  1667. }
  1668. if (!strcmp(url,"/tor/dir-all-weaselhack") &&
  1669. (conn->_base.addr == 0x7f000001ul) &&
  1670. authdir_mode(options)) {
  1671. /* until weasel rewrites his scripts at noreply */
  1672. char *new_directory=NULL;
  1673. if (dirserv_dump_directory_to_string(&new_directory,
  1674. get_identity_key(), 1)) {
  1675. log_warn(LD_BUG, "Error creating full v1 directory.");
  1676. tor_free(new_directory);
  1677. write_http_status_line(conn, 503, "Directory unavailable");
  1678. return 0;
  1679. }
  1680. dlen = strlen(new_directory);
  1681. write_http_response_header(conn, dlen, "text/plain", "identity", 0);
  1682. connection_write_to_buf(new_directory, dlen, TO_CONN(conn));
  1683. tor_free(new_directory);
  1684. tor_free(url);
  1685. return 0;
  1686. }
  1687. /* we didn't recognize the url */
  1688. write_http_status_line(conn, 404, "Not found");
  1689. tor_free(url);
  1690. return 0;
  1691. }
  1692. /** Helper function: called when a dirserver gets a complete HTTP POST
  1693. * request. Look for an uploaded server descriptor or rendezvous
  1694. * service descriptor. On finding one, process it and write a
  1695. * response into conn-\>outbuf. If the request is unrecognized, send a
  1696. * 400. Always return 0. */
  1697. static int
  1698. directory_handle_command_post(dir_connection_t *conn, const char *headers,
  1699. const char *body, size_t body_len)
  1700. {
  1701. char *url = NULL;
  1702. or_options_t *options = get_options();
  1703. log_debug(LD_DIRSERV,"Received POST command.");
  1704. conn->_base.state = DIR_CONN_STATE_SERVER_WRITING;
  1705. if (!authdir_mode(options)) {
  1706. /* we just provide cached directories; we don't want to
  1707. * receive anything. */
  1708. write_http_status_line(conn, 400, "Nonauthoritative directory does not "
  1709. "accept posted server descriptors");
  1710. return 0;
  1711. }
  1712. if (parse_http_url(headers, &url) < 0) {
  1713. write_http_status_line(conn, 400, "Bad request");
  1714. return 0;
  1715. }
  1716. log_debug(LD_DIRSERV,"rewritten url as '%s'.", url);
  1717. if (!strcmp(url,"/tor/")) { /* server descriptor post */
  1718. const char *msg;
  1719. int r = dirserv_add_descriptor(body, &msg);
  1720. tor_assert(msg);
  1721. if (r > 0)
  1722. dirserv_get_directory(); /* rebuild and write to disk */
  1723. switch (r) {
  1724. case -2:
  1725. case -1:
  1726. case 1:
  1727. log_notice(LD_DIRSERV,"Rejected router descriptor from %s.",
  1728. conn->_base.address);
  1729. /* malformed descriptor, or something wrong */
  1730. write_http_status_line(conn, 400, msg);
  1731. break;
  1732. case 0: /* accepted but discarded */
  1733. case 2: /* accepted */
  1734. write_http_status_line(conn, 200, msg);
  1735. break;
  1736. }
  1737. goto done;
  1738. }
  1739. if (options->HSAuthoritativeDir &&
  1740. !strcmpstart(url,"/tor/rendezvous/publish")) {
  1741. /* rendezvous descriptor post */
  1742. if (rend_cache_store(body, body_len) < 0) {
  1743. // char tmp[1024*2+1];
  1744. log_fn(LOG_PROTOCOL_WARN, LD_DIRSERV,
  1745. "Rejected rend descriptor (length %d) from %s.",
  1746. (int)body_len, conn->_base.address);
  1747. write_http_status_line(conn, 400, "Invalid service descriptor rejected");
  1748. } else {
  1749. write_http_status_line(conn, 200, "Service descriptor stored");
  1750. }
  1751. goto done;
  1752. }
  1753. /* we didn't recognize the url */
  1754. write_http_status_line(conn, 404, "Not found");
  1755. done:
  1756. tor_free(url);
  1757. return 0;
  1758. }
  1759. /** Called when a dirserver receives data on a directory connection;
  1760. * looks for an HTTP request. If the request is complete, remove it
  1761. * from the inbuf, try to process it; otherwise, leave it on the
  1762. * buffer. Return a 0 on success, or -1 on error.
  1763. */
  1764. static int
  1765. directory_handle_command(dir_connection_t *conn)
  1766. {
  1767. char *headers=NULL, *body=NULL;
  1768. size_t body_len=0;
  1769. int r;
  1770. tor_assert(conn);
  1771. tor_assert(conn->_base.type == CONN_TYPE_DIR);
  1772. switch (fetch_from_buf_http(conn->_base.inbuf,
  1773. &headers, MAX_HEADERS_SIZE,
  1774. &body, &body_len, MAX_BODY_SIZE, 0)) {
  1775. case -1: /* overflow */
  1776. log_warn(LD_DIRSERV,
  1777. "Invalid input from address '%s'. Closing.",
  1778. conn->_base.address);
  1779. return -1;
  1780. case 0:
  1781. log_debug(LD_DIRSERV,"command not all here yet.");
  1782. return 0;
  1783. /* case 1, fall through */
  1784. }
  1785. http_set_address_origin(headers, TO_CONN(conn));
  1786. //log_debug(LD_DIRSERV,"headers %s, body %s.", headers, body);
  1787. if (!strncasecmp(headers,"GET",3))
  1788. r = directory_handle_command_get(conn, headers, body, body_len);
  1789. else if (!strncasecmp(headers,"POST",4))
  1790. r = directory_handle_command_post(conn, headers, body, body_len);
  1791. else {
  1792. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1793. "Got headers %s with unknown command. Closing.",
  1794. escaped(headers));
  1795. r = -1;
  1796. }
  1797. tor_free(headers); tor_free(body);
  1798. return r;
  1799. }
  1800. /** Write handler for directory connections; called when all data has
  1801. * been flushed. Close the connection or wait for a response as
  1802. * appropriate.
  1803. */
  1804. int
  1805. connection_dir_finished_flushing(dir_connection_t *conn)
  1806. {
  1807. tor_assert(conn);
  1808. tor_assert(conn->_base.type == CONN_TYPE_DIR);
  1809. switch (conn->_base.state) {
  1810. case DIR_CONN_STATE_CLIENT_SENDING:
  1811. log_debug(LD_DIR,"client finished sending command.");
  1812. conn->_base.state = DIR_CONN_STATE_CLIENT_READING;
  1813. connection_stop_writing(TO_CONN(conn));
  1814. return 0;
  1815. case DIR_CONN_STATE_SERVER_WRITING:
  1816. log_debug(LD_DIRSERV,"Finished writing server response. Closing.");
  1817. connection_mark_for_close(TO_CONN(conn));
  1818. return 0;
  1819. default:
  1820. log_warn(LD_BUG,"Bug: called in unexpected state %d.",
  1821. conn->_base.state);
  1822. tor_fragile_assert();
  1823. return -1;
  1824. }
  1825. return 0;
  1826. }
  1827. /** Connected handler for directory connections: begin sending data to the
  1828. * server */
  1829. int
  1830. connection_dir_finished_connecting(dir_connection_t *conn)
  1831. {
  1832. tor_assert(conn);
  1833. tor_assert(conn->_base.type == CONN_TYPE_DIR);
  1834. tor_assert(conn->_base.state == DIR_CONN_STATE_CONNECTING);
  1835. log_debug(LD_HTTP,"Dir connection to router %s:%u established.",
  1836. conn->_base.address,conn->_base.port);
  1837. conn->_base.state = DIR_CONN_STATE_CLIENT_SENDING; /* start flushing conn */
  1838. return 0;
  1839. }
  1840. /** Called when one or more networkstatus fetches have failed (with uppercase
  1841. * fingerprints listed in <b>failed</b>). Mark those fingerprints as having
  1842. * failed once, unless they failed with status code 503. */
  1843. static void
  1844. dir_networkstatus_download_failed(smartlist_t *failed, int status_code)
  1845. {
  1846. if (status_code == 503)
  1847. return;
  1848. SMARTLIST_FOREACH(failed, const char *, fp,
  1849. {
  1850. char digest[DIGEST_LEN];
  1851. trusted_dir_server_t *dir;
  1852. base16_decode(digest, DIGEST_LEN, fp, strlen(fp));
  1853. dir = router_get_trusteddirserver_by_digest(digest);
  1854. if (dir)
  1855. ++dir->n_networkstatus_failures;
  1856. });
  1857. }
  1858. /** Called when one or more routerdesc fetches have failed (with uppercase
  1859. * fingerprints listed in <b>failed</b>). */
  1860. static void
  1861. dir_routerdesc_download_failed(smartlist_t *failed, int status_code)
  1862. {
  1863. char digest[DIGEST_LEN];
  1864. local_routerstatus_t *rs;
  1865. time_t now = time(NULL);
  1866. int server = server_mode(get_options()) && get_options()->DirPort;
  1867. SMARTLIST_FOREACH(failed, const char *, cp,
  1868. {
  1869. base16_decode(digest, DIGEST_LEN, cp, strlen(cp));
  1870. rs = router_get_combined_status_by_digest(digest);
  1871. if (!rs || rs->n_download_failures >= MAX_ROUTERDESC_DOWNLOAD_FAILURES)
  1872. continue;
  1873. if (status_code != 503 || server)
  1874. ++rs->n_download_failures;
  1875. if (server) {
  1876. switch (rs->n_download_failures) {
  1877. case 0: rs->next_attempt_at = 0; break;
  1878. case 1: rs->next_attempt_at = 0; break;
  1879. case 2: rs->next_attempt_at = 0; break;
  1880. case 3: rs->next_attempt_at = now+60; break;
  1881. case 4: rs->next_attempt_at = now+60; break;
  1882. case 5: rs->next_attempt_at = now+60*2; break;
  1883. case 6: rs->next_attempt_at = now+60*5; break;
  1884. case 7: rs->next_attempt_at = now+60*15; break;
  1885. default: rs->next_attempt_at = TIME_MAX; break;
  1886. }
  1887. } else {
  1888. switch (rs->n_download_failures) {
  1889. case 0: rs->next_attempt_at = 0; break;
  1890. case 1: rs->next_attempt_at = 0; break;
  1891. case 2: rs->next_attempt_at = now+60; break;
  1892. case 3: rs->next_attempt_at = now+60*5; break;
  1893. case 4: rs->next_attempt_at = now+60*10; break;
  1894. default: rs->next_attempt_at = TIME_MAX; break;
  1895. }
  1896. }
  1897. if (rs->next_attempt_at == 0)
  1898. log_debug(LD_DIR, "%s failed %d time(s); I'll try again immediately.",
  1899. cp, (int)rs->n_download_failures);
  1900. else if (rs->next_attempt_at < TIME_MAX)
  1901. log_debug(LD_DIR, "%s failed %d time(s); I'll try again in %d seconds.",
  1902. cp, (int)rs->n_download_failures,
  1903. (int)(rs->next_attempt_at-now));
  1904. else
  1905. log_debug(LD_DIR, "%s failed %d time(s); Giving up for a while.",
  1906. cp, (int)rs->n_download_failures);
  1907. });
  1908. /* There's no need to call this here: we already call it every 10 seconds *
  1909. * (DESCRIPTOR_RETRY_INTERVAL) in main.c -NM */
  1910. /* update_router_descriptor_downloads(time(NULL)); */
  1911. }
  1912. /** Given a directory <b>resource</b> request, containing zero
  1913. * or more strings separated by plus signs, followed optionally by ".z", store
  1914. * the strings, in order, into <b>fp_out</b>. If <b>compressed_out</b> is
  1915. * non-NULL, set it to 1 if the resource ends in ".z", else set it to 0. If
  1916. * decode_hex is true, then delete all elements that aren't hex digests, and
  1917. * decode the rest. If sort_uniq is true, then sort the list and remove
  1918. * all duplicates.
  1919. */
  1920. int
  1921. dir_split_resource_into_fingerprints(const char *resource,
  1922. smartlist_t *fp_out, int *compressed_out,
  1923. int decode_hex, int sort_uniq)
  1924. {
  1925. smartlist_t *fp_tmp = smartlist_create();
  1926. tor_assert(fp_out);
  1927. smartlist_split_string(fp_tmp, resource, "+", 0, 0);
  1928. if (compressed_out)
  1929. *compressed_out = 0;
  1930. if (smartlist_len(fp_tmp)) {
  1931. char *last = smartlist_get(fp_tmp,smartlist_len(fp_tmp)-1);
  1932. size_t last_len = strlen(last);
  1933. if (last_len > 2 && !strcmp(last+last_len-2, ".z")) {
  1934. last[last_len-2] = '\0';
  1935. if (compressed_out)
  1936. *compressed_out = 1;
  1937. }
  1938. }
  1939. if (decode_hex) {
  1940. int i;
  1941. char *cp, *d = NULL;
  1942. for (i = 0; i < smartlist_len(fp_tmp); ++i) {
  1943. cp = smartlist_get(fp_tmp, i);
  1944. if (strlen(cp) != HEX_DIGEST_LEN) {
  1945. log_info(LD_DIR,
  1946. "Skipping digest %s with non-standard length.", escaped(cp));
  1947. smartlist_del_keeporder(fp_tmp, i--);
  1948. goto again;
  1949. }
  1950. d = tor_malloc_zero(DIGEST_LEN);
  1951. if (base16_decode(d, DIGEST_LEN, cp, HEX_DIGEST_LEN)<0) {
  1952. log_info(LD_DIR, "Skipping non-decodable digest %s", escaped(cp));
  1953. smartlist_del_keeporder(fp_tmp, i--);
  1954. goto again;
  1955. }
  1956. smartlist_set(fp_tmp, i, d);
  1957. d = NULL;
  1958. again:
  1959. tor_free(cp);
  1960. tor_free(d);
  1961. }
  1962. }
  1963. if (sort_uniq) {
  1964. smartlist_t *fp_tmp2 = smartlist_create();
  1965. int i;
  1966. if (decode_hex)
  1967. smartlist_sort_digests(fp_tmp);
  1968. else
  1969. smartlist_sort_strings(fp_tmp);
  1970. if (smartlist_len(fp_tmp))
  1971. smartlist_add(fp_tmp2, smartlist_get(fp_tmp, 0));
  1972. for (i = 1; i < smartlist_len(fp_tmp); ++i) {
  1973. char *cp = smartlist_get(fp_tmp, i);
  1974. char *last = smartlist_get(fp_tmp2, smartlist_len(fp_tmp2)-1);
  1975. if ((decode_hex && memcmp(cp, last, DIGEST_LEN))
  1976. || (!decode_hex && strcasecmp(cp, last)))
  1977. smartlist_add(fp_tmp2, cp);
  1978. else
  1979. tor_free(cp);
  1980. }
  1981. smartlist_free(fp_tmp);
  1982. fp_tmp = fp_tmp2;
  1983. }
  1984. smartlist_add_all(fp_out, fp_tmp);
  1985. smartlist_free(fp_tmp);
  1986. return 0;
  1987. }