directory.c 97 KB

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