directory.c 81 KB

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