directory.c 82 KB

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