directory.c 67 KB

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