directory.c 117 KB

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