directory.c 101 KB

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