directory.c 83 KB

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