directory.c 116 KB

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