circuitbuild.c 105 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /* $Id$ */
  7. const char circuitbuild_c_id[] =
  8. "$Id$";
  9. /**
  10. * \file circuitbuild.c
  11. * \brief The actual details of building circuits.
  12. **/
  13. #include "or.h"
  14. /********* START VARIABLES **********/
  15. /** A global list of all circuits at this hop. */
  16. extern circuit_t *global_circuitlist;
  17. /** An entry_guard_t represents our information about a chosen long-term
  18. * first hop, known as a "helper" node in the literature. We can't just
  19. * use a routerinfo_t, since we want to remember these even when we
  20. * don't have a directory. */
  21. typedef struct {
  22. char nickname[MAX_NICKNAME_LEN+1];
  23. char identity[DIGEST_LEN];
  24. time_t chosen_on_date; /**< Approximately when was this guard added?
  25. * "0" if we don't know. */
  26. char *chosen_by_version; /**< What tor version added this guard? NULL
  27. * if we don't know. */
  28. unsigned int made_contact : 1; /**< 0 if we have never connected to this
  29. * router, 1 if we have. */
  30. unsigned int can_retry : 1; /**< Should we retry connecting to this entry,
  31. * in spite of having it marked as unreachable?*/
  32. time_t bad_since; /**< 0 if this guard is currently usable, or the time at
  33. * which it was observed to become (according to the
  34. * directory or the user configuration) unusable. */
  35. time_t unreachable_since; /**< 0 if we can connect to this guard, or the
  36. * time at which we first noticed we couldn't
  37. * connect to it. */
  38. time_t last_attempted; /**< 0 if we can connect to this guard, or the time
  39. * at which we last failed to connect to it. */
  40. } entry_guard_t;
  41. /** A list of our chosen entry guards. */
  42. static smartlist_t *entry_guards = NULL;
  43. /** A value of 1 means that the entry_guards list has changed
  44. * and those changes need to be flushed to disk. */
  45. static int entry_guards_dirty = 0;
  46. /********* END VARIABLES ************/
  47. static int circuit_deliver_create_cell(circuit_t *circ,
  48. uint8_t cell_type, const char *payload);
  49. static int onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit);
  50. static crypt_path_t *onion_next_hop_in_cpath(crypt_path_t *cpath);
  51. static int onion_extend_cpath(origin_circuit_t *circ);
  52. static int count_acceptable_routers(smartlist_t *routers);
  53. static int onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice);
  54. static void entry_guards_changed(void);
  55. static time_t start_of_month(time_t when);
  56. /** Iterate over values of circ_id, starting from conn-\>next_circ_id,
  57. * and with the high bit specified by conn-\>circ_id_type, until we get
  58. * a circ_id that is not in use by any other circuit on that conn.
  59. *
  60. * Return it, or 0 if can't get a unique circ_id.
  61. */
  62. static uint16_t
  63. get_unique_circ_id_by_conn(or_connection_t *conn)
  64. {
  65. uint16_t test_circ_id;
  66. uint16_t attempts=0;
  67. uint16_t high_bit;
  68. tor_assert(conn);
  69. if (conn->circ_id_type == CIRC_ID_TYPE_NEITHER) {
  70. log_warn(LD_BUG, "Trying to pick a circuit ID for a connection from "
  71. "a client with no identity.");
  72. return 0;
  73. }
  74. high_bit = (conn->circ_id_type == CIRC_ID_TYPE_HIGHER) ? 1<<15 : 0;
  75. do {
  76. /* Sequentially iterate over test_circ_id=1...1<<15-1 until we find a
  77. * circID such that (high_bit|test_circ_id) is not already used. */
  78. test_circ_id = conn->next_circ_id++;
  79. if (test_circ_id == 0 || test_circ_id >= 1<<15) {
  80. test_circ_id = 1;
  81. conn->next_circ_id = 2;
  82. }
  83. if (++attempts > 1<<15) {
  84. /* Make sure we don't loop forever if all circ_id's are used. This
  85. * matters because it's an external DoS opportunity.
  86. */
  87. log_warn(LD_CIRC,"No unused circ IDs. Failing.");
  88. return 0;
  89. }
  90. test_circ_id |= high_bit;
  91. } while (circuit_get_by_circid_orconn(test_circ_id, conn));
  92. return test_circ_id;
  93. }
  94. /** If <b>verbose</b> is false, allocate and return a comma-separated list of
  95. * the currently built elements of circuit_t. If <b>verbose</b> is true, also
  96. * list information about link status in a more verbose format using spaces.
  97. * If <b>verbose_names</b> is false, give nicknames for Named routers and hex
  98. * digests for others; if <b>verbose_names</b> is true, use $DIGEST=Name style
  99. * names.
  100. */
  101. static char *
  102. circuit_list_path_impl(origin_circuit_t *circ, int verbose, int verbose_names)
  103. {
  104. crypt_path_t *hop;
  105. smartlist_t *elements;
  106. const char *states[] = {"closed", "waiting for keys", "open"};
  107. char buf[128];
  108. char *s;
  109. elements = smartlist_create();
  110. if (verbose) {
  111. const char *nickname = build_state_get_exit_nickname(circ->build_state);
  112. tor_snprintf(buf, sizeof(buf), "%s%s circ (length %d%s%s):",
  113. circ->build_state->is_internal ? "internal" : "exit",
  114. circ->build_state->need_uptime ? " (high-uptime)" : "",
  115. circ->build_state->desired_path_len,
  116. circ->_base.state == CIRCUIT_STATE_OPEN ? "" : ", exit ",
  117. circ->_base.state == CIRCUIT_STATE_OPEN ? "" :
  118. (nickname?nickname:"*unnamed*"));
  119. smartlist_add(elements, tor_strdup(buf));
  120. }
  121. hop = circ->cpath;
  122. do {
  123. routerinfo_t *ri;
  124. char *elt;
  125. if (!hop)
  126. break;
  127. if (!verbose && hop->state != CPATH_STATE_OPEN)
  128. break;
  129. if (!hop->extend_info)
  130. break;
  131. if (verbose_names) {
  132. elt = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
  133. if ((ri = router_get_by_digest(hop->extend_info->identity_digest))) {
  134. router_get_verbose_nickname(elt, ri);
  135. } else if (hop->extend_info->nickname &&
  136. is_legal_nickname(hop->extend_info->nickname)) {
  137. elt[0] = '$';
  138. base16_encode(elt+1, HEX_DIGEST_LEN+1,
  139. hop->extend_info->identity_digest, DIGEST_LEN);
  140. elt[HEX_DIGEST_LEN+1]= '~';
  141. strlcpy(elt+HEX_DIGEST_LEN+2,
  142. hop->extend_info->nickname, MAX_NICKNAME_LEN+1);
  143. } else {
  144. elt[0] = '$';
  145. base16_encode(elt+1, HEX_DIGEST_LEN+1,
  146. hop->extend_info->identity_digest, DIGEST_LEN);
  147. }
  148. } else { /* ! verbose_names */
  149. if ((ri = router_get_by_digest(hop->extend_info->identity_digest)) &&
  150. ri->is_named) {
  151. elt = tor_strdup(hop->extend_info->nickname);
  152. } else {
  153. elt = tor_malloc(HEX_DIGEST_LEN+2);
  154. elt[0] = '$';
  155. base16_encode(elt+1, HEX_DIGEST_LEN+1,
  156. hop->extend_info->identity_digest, DIGEST_LEN);
  157. }
  158. }
  159. tor_assert(elt);
  160. if (verbose) {
  161. size_t len = strlen(elt)+2+strlen(states[hop->state])+1;
  162. char *v = tor_malloc(len);
  163. tor_assert(hop->state <= 2);
  164. tor_snprintf(v,len,"%s(%s)",elt,states[hop->state]);
  165. smartlist_add(elements, v);
  166. tor_free(elt);
  167. } else {
  168. smartlist_add(elements, elt);
  169. }
  170. hop = hop->next;
  171. } while (hop != circ->cpath);
  172. s = smartlist_join_strings(elements, verbose?" ":",", 0, NULL);
  173. SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
  174. smartlist_free(elements);
  175. return s;
  176. }
  177. /** If <b>verbose</b> is false, allocate and return a comma-separated
  178. * list of the currently built elements of circuit_t. If
  179. * <b>verbose</b> is true, also list information about link status in
  180. * a more verbose format using spaces.
  181. */
  182. char *
  183. circuit_list_path(origin_circuit_t *circ, int verbose)
  184. {
  185. return circuit_list_path_impl(circ, verbose, 0);
  186. }
  187. /** Allocate and return a comma-separated list of the currently built elements
  188. * of circuit_t, giving each as a verbose nickname.
  189. */
  190. char *
  191. circuit_list_path_for_controller(origin_circuit_t *circ)
  192. {
  193. return circuit_list_path_impl(circ, 0, 1);
  194. }
  195. /** Log, at severity <b>severity</b>, the nicknames of each router in
  196. * circ's cpath. Also log the length of the cpath, and the intended
  197. * exit point.
  198. */
  199. void
  200. circuit_log_path(int severity, unsigned int domain, origin_circuit_t *circ)
  201. {
  202. char *s = circuit_list_path(circ,1);
  203. log(severity,domain,"%s",s);
  204. tor_free(s);
  205. }
  206. /** Tell the rep(utation)hist(ory) module about the status of the links
  207. * in circ. Hops that have become OPEN are marked as successfully
  208. * extended; the _first_ hop that isn't open (if any) is marked as
  209. * unable to extend.
  210. */
  211. /* XXXX Someday we should learn from OR circuits too. */
  212. void
  213. circuit_rep_hist_note_result(origin_circuit_t *circ)
  214. {
  215. crypt_path_t *hop;
  216. char *prev_digest = NULL;
  217. routerinfo_t *router;
  218. hop = circ->cpath;
  219. if (!hop) /* circuit hasn't started building yet. */
  220. return;
  221. if (server_mode(get_options())) {
  222. routerinfo_t *me = router_get_my_routerinfo();
  223. if (!me)
  224. return;
  225. prev_digest = me->cache_info.identity_digest;
  226. }
  227. do {
  228. router = router_get_by_digest(hop->extend_info->identity_digest);
  229. if (router) {
  230. if (prev_digest) {
  231. if (hop->state == CPATH_STATE_OPEN)
  232. rep_hist_note_extend_succeeded(prev_digest,
  233. router->cache_info.identity_digest);
  234. else {
  235. rep_hist_note_extend_failed(prev_digest,
  236. router->cache_info.identity_digest);
  237. break;
  238. }
  239. }
  240. prev_digest = router->cache_info.identity_digest;
  241. } else {
  242. prev_digest = NULL;
  243. }
  244. hop=hop->next;
  245. } while (hop!=circ->cpath);
  246. }
  247. /** Pick all the entries in our cpath. Stop and return 0 when we're
  248. * happy, or return -1 if an error occurs. */
  249. static int
  250. onion_populate_cpath(origin_circuit_t *circ)
  251. {
  252. int r;
  253. again:
  254. r = onion_extend_cpath(circ);
  255. if (r < 0) {
  256. log_info(LD_CIRC,"Generating cpath hop failed.");
  257. return -1;
  258. }
  259. if (r == 0)
  260. goto again;
  261. return 0; /* if r == 1 */
  262. }
  263. /** Create and return a new origin circuit. Initialize its purpose and
  264. * build-state based on our arguments. The <b>flags</b> argument is a
  265. * bitfield of CIRCLAUNCH_* flags. */
  266. origin_circuit_t *
  267. origin_circuit_init(uint8_t purpose, int flags)
  268. {
  269. /* sets circ->p_circ_id and circ->p_conn */
  270. origin_circuit_t *circ = origin_circuit_new();
  271. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OR_WAIT);
  272. circ->build_state = tor_malloc_zero(sizeof(cpath_build_state_t));
  273. circ->build_state->onehop_tunnel =
  274. ((flags & CIRCLAUNCH_ONEHOP_TUNNEL) ? 1 : 0);
  275. circ->build_state->need_uptime =
  276. ((flags & CIRCLAUNCH_NEED_UPTIME) ? 1 : 0);
  277. circ->build_state->need_capacity =
  278. ((flags & CIRCLAUNCH_NEED_CAPACITY) ? 1 : 0);
  279. circ->build_state->is_internal =
  280. ((flags & CIRCLAUNCH_IS_INTERNAL) ? 1 : 0);
  281. circ->_base.purpose = purpose;
  282. return circ;
  283. }
  284. /** Build a new circuit for <b>purpose</b>. If <b>exit</b>
  285. * is defined, then use that as your exit router, else choose a suitable
  286. * exit node.
  287. *
  288. * Also launch a connection to the first OR in the chosen path, if
  289. * it's not open already.
  290. */
  291. origin_circuit_t *
  292. circuit_establish_circuit(uint8_t purpose, extend_info_t *exit, int flags)
  293. {
  294. origin_circuit_t *circ;
  295. int err_reason = 0;
  296. circ = origin_circuit_init(purpose, flags);
  297. if (onion_pick_cpath_exit(circ, exit) < 0 ||
  298. onion_populate_cpath(circ) < 0) {
  299. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_NOPATH);
  300. return NULL;
  301. }
  302. control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED, 0);
  303. if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
  304. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  305. return NULL;
  306. }
  307. return circ;
  308. }
  309. /** Start establishing the first hop of our circuit. Figure out what
  310. * OR we should connect to, and if necessary start the connection to
  311. * it. If we're already connected, then send the 'create' cell.
  312. * Return 0 for ok, -reason if circ should be marked-for-close. */
  313. int
  314. circuit_handle_first_hop(origin_circuit_t *circ)
  315. {
  316. crypt_path_t *firsthop;
  317. or_connection_t *n_conn;
  318. char tmpbuf[INET_NTOA_BUF_LEN];
  319. struct in_addr in;
  320. int err_reason = 0;
  321. firsthop = onion_next_hop_in_cpath(circ->cpath);
  322. tor_assert(firsthop);
  323. tor_assert(firsthop->extend_info);
  324. /* now see if we're already connected to the first OR in 'route' */
  325. in.s_addr = htonl(firsthop->extend_info->addr);
  326. tor_inet_ntoa(&in, tmpbuf, sizeof(tmpbuf));
  327. log_debug(LD_CIRC,"Looking for firsthop '%s:%u'",tmpbuf,
  328. firsthop->extend_info->port);
  329. /* imprint the circuit with its future n_conn->id */
  330. memcpy(circ->_base.n_conn_id_digest, firsthop->extend_info->identity_digest,
  331. DIGEST_LEN);
  332. n_conn = connection_or_get_by_identity_digest(
  333. firsthop->extend_info->identity_digest);
  334. /* If we don't have an open conn, or the conn we have is obsolete
  335. * (i.e. old or broken) and the other side will let us make a second
  336. * connection without dropping it immediately... */
  337. if (!n_conn || n_conn->_base.state != OR_CONN_STATE_OPEN ||
  338. (n_conn->_base.or_is_obsolete &&
  339. router_digest_version_as_new_as(firsthop->extend_info->identity_digest,
  340. "0.1.1.9-alpha-cvs"))) {
  341. /* not currently connected */
  342. circ->_base.n_addr = firsthop->extend_info->addr;
  343. circ->_base.n_port = firsthop->extend_info->port;
  344. if (!n_conn || n_conn->_base.or_is_obsolete) { /* launch the connection */
  345. n_conn = connection_or_connect(firsthop->extend_info->addr,
  346. firsthop->extend_info->port,
  347. firsthop->extend_info->identity_digest);
  348. if (!n_conn) { /* connect failed, forget the whole thing */
  349. log_info(LD_CIRC,"connect to firsthop failed. Closing.");
  350. return -END_CIRC_REASON_CONNECTFAILED;
  351. }
  352. }
  353. log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
  354. /* return success. The onion/circuit/etc will be taken care of
  355. * automatically (may already have been) whenever n_conn reaches
  356. * OR_CONN_STATE_OPEN.
  357. */
  358. return 0;
  359. } else { /* it's already open. use it. */
  360. circ->_base.n_addr = n_conn->_base.addr;
  361. circ->_base.n_port = n_conn->_base.port;
  362. circ->_base.n_conn = n_conn;
  363. log_debug(LD_CIRC,"Conn open. Delivering first onion skin.");
  364. if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
  365. log_info(LD_CIRC,"circuit_send_next_onion_skin failed.");
  366. return err_reason;
  367. }
  368. }
  369. return 0;
  370. }
  371. /** Find any circuits that are waiting on <b>or_conn</b> to become
  372. * open and get them to send their create cells forward.
  373. *
  374. * Status is 1 if connect succeeded, or 0 if connect failed.
  375. */
  376. void
  377. circuit_n_conn_done(or_connection_t *or_conn, int status)
  378. {
  379. smartlist_t *pending_circs;
  380. int err_reason = 0;
  381. log_debug(LD_CIRC,"or_conn to %s, status=%d",
  382. or_conn->nickname ? or_conn->nickname : "NULL", status);
  383. pending_circs = smartlist_create();
  384. circuit_get_all_pending_on_or_conn(pending_circs, or_conn);
  385. SMARTLIST_FOREACH(pending_circs, circuit_t *, circ,
  386. {
  387. /* These checks are redundant wrt get_all_pending_on_or_conn, but I'm
  388. * leaving them in in case it's possible for the status of a circuit to
  389. * change as we're going down the list. */
  390. if (circ->marked_for_close || circ->n_conn ||
  391. circ->state != CIRCUIT_STATE_OR_WAIT)
  392. continue;
  393. if (tor_digest_is_zero(circ->n_conn_id_digest)) {
  394. /* Look at addr/port. This is an unkeyed connection. */
  395. if (circ->n_addr != or_conn->_base.addr ||
  396. circ->n_port != or_conn->_base.port)
  397. continue;
  398. /* now teach circ the right identity_digest */
  399. memcpy(circ->n_conn_id_digest, or_conn->identity_digest, DIGEST_LEN);
  400. } else {
  401. /* We expected a key. See if it's the right one. */
  402. if (memcmp(or_conn->identity_digest,
  403. circ->n_conn_id_digest, DIGEST_LEN))
  404. continue;
  405. }
  406. if (!status) { /* or_conn failed; close circ */
  407. log_info(LD_CIRC,"or_conn failed. Closing circ.");
  408. circuit_mark_for_close(circ, END_CIRC_REASON_OR_CONN_CLOSED);
  409. continue;
  410. }
  411. log_debug(LD_CIRC, "Found circ, sending create cell.");
  412. /* circuit_deliver_create_cell will set n_circ_id and add us to
  413. * orconn_circuid_circuit_map, so we don't need to call
  414. * set_circid_orconn here. */
  415. circ->n_conn = or_conn;
  416. if (CIRCUIT_IS_ORIGIN(circ)) {
  417. if ((err_reason =
  418. circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ))) < 0) {
  419. log_info(LD_CIRC,
  420. "send_next_onion_skin failed; circuit marked for closing.");
  421. circuit_mark_for_close(circ, -err_reason);
  422. continue;
  423. /* XXX could this be bad, eg if next_onion_skin failed because conn
  424. * died? */
  425. }
  426. } else {
  427. /* pull the create cell out of circ->onionskin, and send it */
  428. tor_assert(circ->onionskin);
  429. if (circuit_deliver_create_cell(circ,CELL_CREATE,circ->onionskin)<0) {
  430. circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
  431. continue;
  432. }
  433. tor_free(circ->onionskin);
  434. circuit_set_state(circ, CIRCUIT_STATE_OPEN);
  435. }
  436. });
  437. smartlist_free(pending_circs);
  438. }
  439. /** Find a new circid that isn't currently in use on the circ->n_conn
  440. * for the outgoing
  441. * circuit <b>circ</b>, and deliver a cell of type <b>cell_type</b>
  442. * (either CELL_CREATE or CELL_CREATE_FAST) with payload <b>payload</b>
  443. * to this circuit.
  444. * Return -1 if we failed to find a suitable circid, else return 0.
  445. */
  446. static int
  447. circuit_deliver_create_cell(circuit_t *circ, uint8_t cell_type,
  448. const char *payload)
  449. {
  450. cell_t cell;
  451. uint16_t id;
  452. tor_assert(circ);
  453. tor_assert(circ->n_conn);
  454. tor_assert(payload);
  455. tor_assert(cell_type == CELL_CREATE || cell_type == CELL_CREATE_FAST);
  456. id = get_unique_circ_id_by_conn(circ->n_conn);
  457. if (!id) {
  458. log_warn(LD_CIRC,"failed to get unique circID.");
  459. return -1;
  460. }
  461. log_debug(LD_CIRC,"Chosen circID %u.", id);
  462. circuit_set_n_circid_orconn(circ, id, circ->n_conn);
  463. memset(&cell, 0, sizeof(cell_t));
  464. cell.command = cell_type;
  465. cell.circ_id = circ->n_circ_id;
  466. memcpy(cell.payload, payload, ONIONSKIN_CHALLENGE_LEN);
  467. append_cell_to_circuit_queue(circ, circ->n_conn, &cell, CELL_DIRECTION_OUT);
  468. if (CIRCUIT_IS_ORIGIN(circ)) {
  469. /* mark it so it gets better rate limiting treatment. */
  470. circ->n_conn->client_used = time(NULL);
  471. }
  472. return 0;
  473. }
  474. /** We've decided to start our reachability testing. If all
  475. * is set, log this to the user. Return 1 if we did, or 0 if
  476. * we chose not to log anything. */
  477. int
  478. inform_testing_reachability(void)
  479. {
  480. char dirbuf[128];
  481. routerinfo_t *me = router_get_my_routerinfo();
  482. if (!me)
  483. return 0;
  484. if (me->dir_port)
  485. tor_snprintf(dirbuf, sizeof(dirbuf), " and DirPort %s:%d",
  486. me->address, me->dir_port);
  487. log(LOG_NOTICE, LD_OR, "Now checking whether ORPort %s:%d%s %s reachable... "
  488. "(this may take up to %d minutes -- look for log "
  489. "messages indicating success)",
  490. me->address, me->or_port,
  491. me->dir_port ? dirbuf : "",
  492. me->dir_port ? "are" : "is",
  493. TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT/60);
  494. return 1;
  495. }
  496. /** Return true iff we should send a create_fast cell to build a circuit
  497. * starting at <b>router</b>. (If <b>router</b> is NULL, we don't have
  498. * information on the router, so assume true.) */
  499. static INLINE int
  500. should_use_create_fast_for_router(routerinfo_t *router,
  501. origin_circuit_t *circ)
  502. {
  503. or_options_t *options = get_options();
  504. if (!options->FastFirstHopPK) /* create_fast is disabled */
  505. return 0;
  506. if (router && router->platform &&
  507. !tor_version_as_new_as(router->platform, "0.1.0.6-rc")) {
  508. /* known not to work */
  509. return 0;
  510. }
  511. if (server_mode(options) && circ->cpath->extend_info->onion_key) {
  512. /* We're a server, and we know an onion key. We can choose.
  513. * Prefer to blend in. */
  514. return 0;
  515. }
  516. return 1;
  517. }
  518. /** This is the backbone function for building circuits.
  519. *
  520. * If circ's first hop is closed, then we need to build a create
  521. * cell and send it forward.
  522. *
  523. * Otherwise, we need to build a relay extend cell and send it
  524. * forward.
  525. *
  526. * Return -reason if we want to tear down circ, else return 0.
  527. */
  528. int
  529. circuit_send_next_onion_skin(origin_circuit_t *circ)
  530. {
  531. crypt_path_t *hop;
  532. routerinfo_t *router;
  533. char payload[2+4+DIGEST_LEN+ONIONSKIN_CHALLENGE_LEN];
  534. char *onionskin;
  535. size_t payload_len;
  536. tor_assert(circ);
  537. if (circ->cpath->state == CPATH_STATE_CLOSED) {
  538. int fast;
  539. uint8_t cell_type;
  540. log_debug(LD_CIRC,"First skin; sending create cell.");
  541. router = router_get_by_digest(circ->_base.n_conn->identity_digest);
  542. fast = should_use_create_fast_for_router(router, circ);
  543. if (!fast && !circ->cpath->extend_info->onion_key) {
  544. log_warn(LD_CIRC,
  545. "Can't send create_fast, but have no onion key. Failing.");
  546. return - END_CIRC_REASON_INTERNAL;
  547. }
  548. if (!fast) {
  549. /* We are an OR, or we are connecting to an old Tor: we should
  550. * send an old slow create cell.
  551. */
  552. cell_type = CELL_CREATE;
  553. if (onion_skin_create(circ->cpath->extend_info->onion_key,
  554. &(circ->cpath->dh_handshake_state),
  555. payload) < 0) {
  556. log_warn(LD_CIRC,"onion_skin_create (first hop) failed.");
  557. return - END_CIRC_REASON_INTERNAL;
  558. }
  559. } else {
  560. /* We are not an OR, and we're building the first hop of a circuit to a
  561. * new OR: we can be speedy and use CREATE_FAST to save an RSA operation
  562. * and a DH operation. */
  563. cell_type = CELL_CREATE_FAST;
  564. memset(payload, 0, sizeof(payload));
  565. crypto_rand(circ->cpath->fast_handshake_state,
  566. sizeof(circ->cpath->fast_handshake_state));
  567. memcpy(payload, circ->cpath->fast_handshake_state,
  568. sizeof(circ->cpath->fast_handshake_state));
  569. }
  570. if (circuit_deliver_create_cell(TO_CIRCUIT(circ), cell_type, payload) < 0)
  571. return - END_CIRC_REASON_RESOURCELIMIT;
  572. circ->cpath->state = CPATH_STATE_AWAITING_KEYS;
  573. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  574. log_info(LD_CIRC,"First hop: finished sending %s cell to '%s'",
  575. fast ? "CREATE_FAST" : "CREATE",
  576. router ? router->nickname : "<unnamed>");
  577. } else {
  578. tor_assert(circ->cpath->state == CPATH_STATE_OPEN);
  579. tor_assert(circ->_base.state == CIRCUIT_STATE_BUILDING);
  580. log_debug(LD_CIRC,"starting to send subsequent skin.");
  581. hop = onion_next_hop_in_cpath(circ->cpath);
  582. if (!hop) {
  583. /* done building the circuit. whew. */
  584. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
  585. log_info(LD_CIRC,"circuit built!");
  586. circuit_reset_failure_count(0);
  587. if (!has_completed_circuit && !circ->build_state->onehop_tunnel) {
  588. or_options_t *options = get_options();
  589. has_completed_circuit=1;
  590. /* FFFF Log a count of known routers here */
  591. log(LOG_NOTICE, LD_GENERAL,
  592. "Tor has successfully opened a circuit. "
  593. "Looks like client functionality is working.");
  594. control_event_client_status(LOG_NOTICE, "CIRCUIT_ESTABLISHED");
  595. if (server_mode(options) && !check_whether_orport_reachable()) {
  596. inform_testing_reachability();
  597. consider_testing_reachability(1, 1);
  598. }
  599. }
  600. circuit_rep_hist_note_result(circ);
  601. circuit_has_opened(circ); /* do other actions as necessary */
  602. return 0;
  603. }
  604. set_uint32(payload, htonl(hop->extend_info->addr));
  605. set_uint16(payload+4, htons(hop->extend_info->port));
  606. onionskin = payload+2+4;
  607. memcpy(payload+2+4+ONIONSKIN_CHALLENGE_LEN,
  608. hop->extend_info->identity_digest, DIGEST_LEN);
  609. payload_len = 2+4+ONIONSKIN_CHALLENGE_LEN+DIGEST_LEN;
  610. if (onion_skin_create(hop->extend_info->onion_key,
  611. &(hop->dh_handshake_state), onionskin) < 0) {
  612. log_warn(LD_CIRC,"onion_skin_create failed.");
  613. return - END_CIRC_REASON_INTERNAL;
  614. }
  615. log_info(LD_CIRC,"Sending extend relay cell.");
  616. /* send it to hop->prev, because it will transfer
  617. * it to a create cell and then send to hop */
  618. if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
  619. RELAY_COMMAND_EXTEND,
  620. payload, payload_len, hop->prev) < 0)
  621. return 0; /* circuit is closed */
  622. hop->state = CPATH_STATE_AWAITING_KEYS;
  623. }
  624. return 0;
  625. }
  626. /** Our clock just jumped by <b>seconds_elapsed</b>. Assume
  627. * something has also gone wrong with our network: notify the user,
  628. * and abandon all not-yet-used circuits. */
  629. void
  630. circuit_note_clock_jumped(int seconds_elapsed)
  631. {
  632. int severity = server_mode(get_options()) ? LOG_WARN : LOG_NOTICE;
  633. log(severity, LD_GENERAL, "Your system clock just jumped %d seconds %s; "
  634. "assuming established circuits no longer work.",
  635. seconds_elapsed >=0 ? seconds_elapsed : -seconds_elapsed,
  636. seconds_elapsed >=0 ? "forward" : "backward");
  637. control_event_general_status(LOG_WARN, "CLOCK_JUMPED TIME=%d",
  638. seconds_elapsed);
  639. has_completed_circuit=0; /* so it'll log when it works again */
  640. control_event_client_status(severity, "CIRCUIT_NOT_ESTABLISHED REASON=%s",
  641. "CLOCK_JUMPED");
  642. circuit_mark_all_unused_circs();
  643. circuit_expire_all_dirty_circs();
  644. }
  645. /** Take the 'extend' cell, pull out addr/port plus the onion skin. Make
  646. * sure we're connected to the next hop, and pass it the onion skin using
  647. * a create cell. Return -1 if we want to warn and tear down the circuit,
  648. * else return 0.
  649. */
  650. int
  651. circuit_extend(cell_t *cell, circuit_t *circ)
  652. {
  653. or_connection_t *n_conn;
  654. relay_header_t rh;
  655. char *onionskin;
  656. char *id_digest=NULL;
  657. if (circ->n_conn) {
  658. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  659. "n_conn already set. Bug/attack. Closing.");
  660. return -1;
  661. }
  662. if (!server_mode(get_options())) {
  663. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  664. "Got an extend cell, but running as a client. Closing.");
  665. return -1;
  666. }
  667. relay_header_unpack(&rh, cell->payload);
  668. if (rh.length < 4+2+ONIONSKIN_CHALLENGE_LEN+DIGEST_LEN) {
  669. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  670. "Wrong length %d on extend cell. Closing circuit.",
  671. rh.length);
  672. return -1;
  673. }
  674. circ->n_addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE));
  675. circ->n_port = ntohs(get_uint16(cell->payload+RELAY_HEADER_SIZE+4));
  676. onionskin = cell->payload+RELAY_HEADER_SIZE+4+2;
  677. id_digest = cell->payload+RELAY_HEADER_SIZE+4+2+ONIONSKIN_CHALLENGE_LEN;
  678. n_conn = connection_or_get_by_identity_digest(id_digest);
  679. /* If we don't have an open conn, or the conn we have is obsolete
  680. * (i.e. old or broken) and the other side will let us make a second
  681. * connection without dropping it immediately... */
  682. if (!n_conn || n_conn->_base.state != OR_CONN_STATE_OPEN ||
  683. (n_conn->_base.or_is_obsolete &&
  684. router_digest_version_as_new_as(id_digest,"0.1.1.9-alpha-cvs"))) {
  685. struct in_addr in;
  686. char tmpbuf[INET_NTOA_BUF_LEN];
  687. in.s_addr = htonl(circ->n_addr);
  688. tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
  689. log_info(LD_CIRC|LD_OR,"Next router (%s:%d) not connected. Connecting.",
  690. tmpbuf, circ->n_port);
  691. circ->onionskin = tor_malloc(ONIONSKIN_CHALLENGE_LEN);
  692. memcpy(circ->onionskin, onionskin, ONIONSKIN_CHALLENGE_LEN);
  693. circuit_set_state(circ, CIRCUIT_STATE_OR_WAIT);
  694. /* imprint the circuit with its future n_conn->id */
  695. memcpy(circ->n_conn_id_digest, id_digest, DIGEST_LEN);
  696. if (n_conn && !n_conn->_base.or_is_obsolete) {
  697. circ->n_addr = n_conn->_base.addr;
  698. circ->n_port = n_conn->_base.port;
  699. } else {
  700. /* we should try to open a connection */
  701. n_conn = connection_or_connect(circ->n_addr, circ->n_port, id_digest);
  702. if (!n_conn) {
  703. log_info(LD_CIRC,"Launching n_conn failed. Closing circuit.");
  704. circuit_mark_for_close(circ, END_CIRC_REASON_CONNECTFAILED);
  705. return 0;
  706. }
  707. log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
  708. }
  709. /* return success. The onion/circuit/etc will be taken care of
  710. * automatically (may already have been) whenever n_conn reaches
  711. * OR_CONN_STATE_OPEN.
  712. */
  713. return 0;
  714. }
  715. /* these may be different if the router connected to us from elsewhere */
  716. circ->n_addr = n_conn->_base.addr;
  717. circ->n_port = n_conn->_base.port;
  718. circ->n_conn = n_conn;
  719. memcpy(circ->n_conn_id_digest, n_conn->identity_digest, DIGEST_LEN);
  720. log_debug(LD_CIRC,"n_conn is %s:%u",
  721. n_conn->_base.address,n_conn->_base.port);
  722. if (circuit_deliver_create_cell(circ, CELL_CREATE, onionskin) < 0)
  723. return -1;
  724. return 0;
  725. }
  726. /** Initialize cpath-\>{f|b}_{crypto|digest} from the key material in
  727. * key_data. key_data must contain CPATH_KEY_MATERIAL bytes, which are
  728. * used as follows:
  729. * - 20 to initialize f_digest
  730. * - 20 to initialize b_digest
  731. * - 16 to key f_crypto
  732. * - 16 to key b_crypto
  733. *
  734. * (If 'reverse' is true, then f_XX and b_XX are swapped.)
  735. */
  736. int
  737. circuit_init_cpath_crypto(crypt_path_t *cpath, const char *key_data,
  738. int reverse)
  739. {
  740. crypto_digest_env_t *tmp_digest;
  741. crypto_cipher_env_t *tmp_crypto;
  742. tor_assert(cpath);
  743. tor_assert(key_data);
  744. tor_assert(!(cpath->f_crypto || cpath->b_crypto ||
  745. cpath->f_digest || cpath->b_digest));
  746. cpath->f_digest = crypto_new_digest_env();
  747. crypto_digest_add_bytes(cpath->f_digest, key_data, DIGEST_LEN);
  748. cpath->b_digest = crypto_new_digest_env();
  749. crypto_digest_add_bytes(cpath->b_digest, key_data+DIGEST_LEN, DIGEST_LEN);
  750. if (!(cpath->f_crypto =
  751. crypto_create_init_cipher(key_data+(2*DIGEST_LEN),1))) {
  752. log_warn(LD_BUG,"Forward cipher initialization failed.");
  753. return -1;
  754. }
  755. if (!(cpath->b_crypto =
  756. crypto_create_init_cipher(key_data+(2*DIGEST_LEN)+CIPHER_KEY_LEN,0))) {
  757. log_warn(LD_BUG,"Backward cipher initialization failed.");
  758. return -1;
  759. }
  760. if (reverse) {
  761. tmp_digest = cpath->f_digest;
  762. cpath->f_digest = cpath->b_digest;
  763. cpath->b_digest = tmp_digest;
  764. tmp_crypto = cpath->f_crypto;
  765. cpath->f_crypto = cpath->b_crypto;
  766. cpath->b_crypto = tmp_crypto;
  767. }
  768. return 0;
  769. }
  770. /** A created or extended cell came back to us on the circuit, and it included
  771. * <b>reply</b> as its body. (If <b>reply_type</b> is CELL_CREATED, the body
  772. * contains (the second DH key, plus KH). If <b>reply_type</b> is
  773. * CELL_CREATED_FAST, the body contains a secret y and a hash H(x|y).)
  774. *
  775. * Calculate the appropriate keys and digests, make sure KH is
  776. * correct, and initialize this hop of the cpath.
  777. *
  778. * Return - reason if we want to mark circ for close, else return 0.
  779. */
  780. int
  781. circuit_finish_handshake(origin_circuit_t *circ, uint8_t reply_type,
  782. const char *reply)
  783. {
  784. char keys[CPATH_KEY_MATERIAL_LEN];
  785. crypt_path_t *hop;
  786. if (circ->cpath->state == CPATH_STATE_AWAITING_KEYS)
  787. hop = circ->cpath;
  788. else {
  789. hop = onion_next_hop_in_cpath(circ->cpath);
  790. if (!hop) { /* got an extended when we're all done? */
  791. log_warn(LD_PROTOCOL,"got extended when circ already built? Closing.");
  792. return - END_CIRC_REASON_TORPROTOCOL;
  793. }
  794. }
  795. tor_assert(hop->state == CPATH_STATE_AWAITING_KEYS);
  796. if (reply_type == CELL_CREATED && hop->dh_handshake_state) {
  797. if (onion_skin_client_handshake(hop->dh_handshake_state, reply, keys,
  798. DIGEST_LEN*2+CIPHER_KEY_LEN*2) < 0) {
  799. log_warn(LD_CIRC,"onion_skin_client_handshake failed.");
  800. return -END_CIRC_REASON_TORPROTOCOL;
  801. }
  802. /* Remember hash of g^xy */
  803. memcpy(hop->handshake_digest, reply+DH_KEY_LEN, DIGEST_LEN);
  804. } else if (reply_type == CELL_CREATED_FAST && !hop->dh_handshake_state) {
  805. if (fast_client_handshake(hop->fast_handshake_state, reply, keys,
  806. DIGEST_LEN*2+CIPHER_KEY_LEN*2) < 0) {
  807. log_warn(LD_CIRC,"fast_client_handshake failed.");
  808. return -END_CIRC_REASON_TORPROTOCOL;
  809. }
  810. memcpy(hop->handshake_digest, reply+DIGEST_LEN, DIGEST_LEN);
  811. } else {
  812. log_warn(LD_PROTOCOL,"CREATED cell type did not match CREATE cell type.");
  813. return -END_CIRC_REASON_TORPROTOCOL;
  814. }
  815. if (hop->dh_handshake_state) {
  816. crypto_dh_free(hop->dh_handshake_state); /* don't need it anymore */
  817. hop->dh_handshake_state = NULL;
  818. }
  819. memset(hop->fast_handshake_state, 0, sizeof(hop->fast_handshake_state));
  820. if (circuit_init_cpath_crypto(hop, keys, 0)<0) {
  821. return -END_CIRC_REASON_TORPROTOCOL;
  822. }
  823. hop->state = CPATH_STATE_OPEN;
  824. log_info(LD_CIRC,"Finished building %scircuit hop:",
  825. (reply_type == CELL_CREATED_FAST) ? "fast " : "");
  826. circuit_log_path(LOG_INFO,LD_CIRC,circ);
  827. control_event_circuit_status(circ, CIRC_EVENT_EXTENDED, 0);
  828. return 0;
  829. }
  830. /** We received a relay truncated cell on circ.
  831. *
  832. * Since we don't ask for truncates currently, getting a truncated
  833. * means that a connection broke or an extend failed. For now,
  834. * just give up: for circ to close, and return 0.
  835. */
  836. int
  837. circuit_truncated(origin_circuit_t *circ, crypt_path_t *layer)
  838. {
  839. // crypt_path_t *victim;
  840. // connection_t *stream;
  841. tor_assert(circ);
  842. tor_assert(layer);
  843. /* XXX Since we don't ask for truncates currently, getting a truncated
  844. * means that a connection broke or an extend failed. For now,
  845. * just give up.
  846. */
  847. circuit_mark_for_close(TO_CIRCUIT(circ),
  848. END_CIRC_REASON_FLAG_REMOTE|END_CIRC_REASON_OR_CONN_CLOSED);
  849. return 0;
  850. #if 0
  851. while (layer->next != circ->cpath) {
  852. /* we need to clear out layer->next */
  853. victim = layer->next;
  854. log_debug(LD_CIRC, "Killing a layer of the cpath.");
  855. for (stream = circ->p_streams; stream; stream=stream->next_stream) {
  856. if (stream->cpath_layer == victim) {
  857. log_info(LD_APP, "Marking stream %d for close because of truncate.",
  858. stream->stream_id);
  859. /* no need to send 'end' relay cells,
  860. * because the other side's already dead
  861. */
  862. connection_mark_unattached_ap(stream, END_STREAM_REASON_DESTROY);
  863. }
  864. }
  865. layer->next = victim->next;
  866. circuit_free_cpath_node(victim);
  867. }
  868. log_info(LD_CIRC, "finished");
  869. return 0;
  870. #endif
  871. }
  872. /** Given a response payload and keys, initialize, then send a created
  873. * cell back.
  874. */
  875. int
  876. onionskin_answer(or_circuit_t *circ, uint8_t cell_type, const char *payload,
  877. const char *keys)
  878. {
  879. cell_t cell;
  880. crypt_path_t *tmp_cpath;
  881. tmp_cpath = tor_malloc_zero(sizeof(crypt_path_t));
  882. tmp_cpath->magic = CRYPT_PATH_MAGIC;
  883. memset(&cell, 0, sizeof(cell_t));
  884. cell.command = cell_type;
  885. cell.circ_id = circ->p_circ_id;
  886. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
  887. memcpy(cell.payload, payload,
  888. cell_type == CELL_CREATED ? ONIONSKIN_REPLY_LEN : DIGEST_LEN*2);
  889. log_debug(LD_CIRC,"init digest forward 0x%.8x, backward 0x%.8x.",
  890. (unsigned int)*(uint32_t*)(keys),
  891. (unsigned int)*(uint32_t*)(keys+20));
  892. if (circuit_init_cpath_crypto(tmp_cpath, keys, 0)<0) {
  893. log_warn(LD_BUG,"Circuit initialization failed");
  894. tor_free(tmp_cpath);
  895. return -1;
  896. }
  897. circ->n_digest = tmp_cpath->f_digest;
  898. circ->n_crypto = tmp_cpath->f_crypto;
  899. circ->p_digest = tmp_cpath->b_digest;
  900. circ->p_crypto = tmp_cpath->b_crypto;
  901. tmp_cpath->magic = 0;
  902. tor_free(tmp_cpath);
  903. if (cell_type == CELL_CREATED)
  904. memcpy(circ->handshake_digest, cell.payload+DH_KEY_LEN, DIGEST_LEN);
  905. else
  906. memcpy(circ->handshake_digest, cell.payload+DIGEST_LEN, DIGEST_LEN);
  907. circ->is_first_hop = (cell_type == CELL_CREATED_FAST);
  908. append_cell_to_circuit_queue(TO_CIRCUIT(circ),
  909. circ->p_conn, &cell, CELL_DIRECTION_IN);
  910. log_debug(LD_CIRC,"Finished sending 'created' cell.");
  911. if (!is_local_IP(circ->p_conn->_base.addr) &&
  912. !connection_or_nonopen_was_started_here(circ->p_conn)) {
  913. /* record that we could process create cells from a non-local conn
  914. * that we didn't initiate; presumably this means that create cells
  915. * can reach us too. */
  916. router_orport_found_reachable();
  917. }
  918. return 0;
  919. }
  920. /** Choose a length for a circuit of purpose <b>purpose</b>.
  921. * Default length is 3 + the number of endpoints that would give something
  922. * away. If the routerlist <b>routers</b> doesn't have enough routers
  923. * to handle the desired path length, return as large a path length as
  924. * is feasible, except if it's less than 2, in which case return -1.
  925. */
  926. static int
  927. new_route_len(uint8_t purpose, extend_info_t *exit,
  928. smartlist_t *routers)
  929. {
  930. int num_acceptable_routers;
  931. int routelen;
  932. tor_assert(routers);
  933. #ifdef TOR_PERF
  934. routelen = 2;
  935. #else
  936. routelen = 3;
  937. if (exit &&
  938. purpose != CIRCUIT_PURPOSE_TESTING &&
  939. purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
  940. routelen++;
  941. #endif
  942. log_debug(LD_CIRC,"Chosen route length %d (%d routers available).",
  943. routelen, smartlist_len(routers));
  944. num_acceptable_routers = count_acceptable_routers(routers);
  945. if (num_acceptable_routers < 2) {
  946. log_info(LD_CIRC,
  947. "Not enough acceptable routers (%d). Discarding this circuit.",
  948. num_acceptable_routers);
  949. return -1;
  950. }
  951. if (num_acceptable_routers < routelen) {
  952. log_info(LD_CIRC,"Not enough routers: cutting routelen from %d to %d.",
  953. routelen, num_acceptable_routers);
  954. routelen = num_acceptable_routers;
  955. }
  956. return routelen;
  957. }
  958. /** Fetch the list of predicted ports, dup it into a smartlist of
  959. * uint16_t's, remove the ones that are already handled by an
  960. * existing circuit, and return it.
  961. */
  962. static smartlist_t *
  963. circuit_get_unhandled_ports(time_t now)
  964. {
  965. smartlist_t *source = rep_hist_get_predicted_ports(now);
  966. smartlist_t *dest = smartlist_create();
  967. uint16_t *tmp;
  968. int i;
  969. for (i = 0; i < smartlist_len(source); ++i) {
  970. tmp = tor_malloc(sizeof(uint16_t));
  971. memcpy(tmp, smartlist_get(source, i), sizeof(uint16_t));
  972. smartlist_add(dest, tmp);
  973. }
  974. circuit_remove_handled_ports(dest);
  975. return dest;
  976. }
  977. /** Return 1 if we already have circuits present or on the way for
  978. * all anticipated ports. Return 0 if we should make more.
  979. *
  980. * If we're returning 0, set need_uptime and need_capacity to
  981. * indicate any requirements that the unhandled ports have.
  982. */
  983. int
  984. circuit_all_predicted_ports_handled(time_t now, int *need_uptime,
  985. int *need_capacity)
  986. {
  987. int i, enough;
  988. uint16_t *port;
  989. smartlist_t *sl = circuit_get_unhandled_ports(now);
  990. smartlist_t *LongLivedServices = get_options()->LongLivedPorts;
  991. tor_assert(need_uptime);
  992. tor_assert(need_capacity);
  993. enough = (smartlist_len(sl) == 0);
  994. for (i = 0; i < smartlist_len(sl); ++i) {
  995. port = smartlist_get(sl, i);
  996. if (smartlist_string_num_isin(LongLivedServices, *port))
  997. *need_uptime = 1;
  998. tor_free(port);
  999. }
  1000. smartlist_free(sl);
  1001. return enough;
  1002. }
  1003. /** Return 1 if <b>router</b> can handle one or more of the ports in
  1004. * <b>needed_ports</b>, else return 0.
  1005. */
  1006. static int
  1007. router_handles_some_port(routerinfo_t *router, smartlist_t *needed_ports)
  1008. {
  1009. int i;
  1010. uint16_t port;
  1011. for (i = 0; i < smartlist_len(needed_ports); ++i) {
  1012. addr_policy_result_t r;
  1013. port = *(uint16_t *)smartlist_get(needed_ports, i);
  1014. tor_assert(port);
  1015. r = compare_addr_to_addr_policy(0, port, router->exit_policy);
  1016. if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
  1017. return 1;
  1018. }
  1019. return 0;
  1020. }
  1021. /** Return true iff <b>conn</b> needs another general circuit to be
  1022. * built. */
  1023. static int
  1024. ap_stream_wants_exit_attention(connection_t *conn)
  1025. {
  1026. if (conn->type == CONN_TYPE_AP &&
  1027. conn->state == AP_CONN_STATE_CIRCUIT_WAIT &&
  1028. !conn->marked_for_close &&
  1029. !connection_edge_is_rendezvous_stream(TO_EDGE_CONN(conn)) &&
  1030. !circuit_stream_is_being_handled(TO_EDGE_CONN(conn), 0,
  1031. MIN_CIRCUITS_HANDLING_STREAM))
  1032. return 1;
  1033. return 0;
  1034. }
  1035. /** Return a pointer to a suitable router to be the exit node for the
  1036. * general-purpose circuit we're about to build.
  1037. *
  1038. * Look through the connection array, and choose a router that maximizes
  1039. * the number of pending streams that can exit from this router.
  1040. *
  1041. * Return NULL if we can't find any suitable routers.
  1042. */
  1043. static routerinfo_t *
  1044. choose_good_exit_server_general(routerlist_t *dir, int need_uptime,
  1045. int need_capacity)
  1046. {
  1047. int *n_supported;
  1048. int i;
  1049. int n_pending_connections = 0;
  1050. smartlist_t *connections;
  1051. int best_support = -1;
  1052. int n_best_support=0;
  1053. smartlist_t *sl, *preferredexits, *excludedexits;
  1054. routerinfo_t *router;
  1055. or_options_t *options = get_options();
  1056. connections = get_connection_array();
  1057. /* Count how many connections are waiting for a circuit to be built.
  1058. * We use this for log messages now, but in the future we may depend on it.
  1059. */
  1060. SMARTLIST_FOREACH(connections, connection_t *, conn,
  1061. {
  1062. if (ap_stream_wants_exit_attention(conn))
  1063. ++n_pending_connections;
  1064. });
  1065. // log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
  1066. // n_pending_connections);
  1067. /* Now we count, for each of the routers in the directory, how many
  1068. * of the pending connections could possibly exit from that
  1069. * router (n_supported[i]). (We can't be sure about cases where we
  1070. * don't know the IP address of the pending connection.)
  1071. */
  1072. n_supported = tor_malloc(sizeof(int)*smartlist_len(dir->routers));
  1073. for (i = 0; i < smartlist_len(dir->routers); ++i) {/* iterate over routers */
  1074. router = smartlist_get(dir->routers, i);
  1075. if (router_is_me(router)) {
  1076. n_supported[i] = -1;
  1077. // log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
  1078. /* XXX there's probably a reverse predecessor attack here, but
  1079. * it's slow. should we take this out? -RD
  1080. */
  1081. continue;
  1082. }
  1083. if (!router->is_running || router->is_bad_exit) {
  1084. n_supported[i] = -1;
  1085. continue; /* skip routers that are known to be down or bad exits */
  1086. }
  1087. if (router_is_unreliable(router, need_uptime, need_capacity, 0)) {
  1088. n_supported[i] = -1;
  1089. continue; /* skip routers that are not suitable */
  1090. }
  1091. if (!(router->is_valid || options->_AllowInvalid & ALLOW_INVALID_EXIT)) {
  1092. /* if it's invalid and we don't want it */
  1093. n_supported[i] = -1;
  1094. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- invalid router.",
  1095. // router->nickname, i);
  1096. continue; /* skip invalid routers */
  1097. }
  1098. if (router_exit_policy_rejects_all(router)) {
  1099. n_supported[i] = -1;
  1100. // log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
  1101. // router->nickname, i);
  1102. continue; /* skip routers that reject all */
  1103. }
  1104. n_supported[i] = 0;
  1105. /* iterate over connections */
  1106. SMARTLIST_FOREACH(connections, connection_t *, conn,
  1107. {
  1108. if (!ap_stream_wants_exit_attention(conn))
  1109. continue; /* Skip everything but APs in CIRCUIT_WAIT */
  1110. if (connection_ap_can_use_exit(TO_EDGE_CONN(conn), router)) {
  1111. ++n_supported[i];
  1112. // log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
  1113. // router->nickname, i, n_supported[i]);
  1114. } else {
  1115. // log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
  1116. // router->nickname, i);
  1117. }
  1118. }); /* End looping over connections. */
  1119. if (n_supported[i] > best_support) {
  1120. /* If this router is better than previous ones, remember its index
  1121. * and goodness, and start counting how many routers are this good. */
  1122. best_support = n_supported[i]; n_best_support=1;
  1123. // log_fn(LOG_DEBUG,"%s is new best supported option so far.",
  1124. // router->nickname);
  1125. } else if (n_supported[i] == best_support) {
  1126. /* If this router is _as good_ as the best one, just increment the
  1127. * count of equally good routers.*/
  1128. ++n_best_support;
  1129. }
  1130. }
  1131. log_info(LD_CIRC,
  1132. "Found %d servers that might support %d/%d pending connections.",
  1133. n_best_support, best_support >= 0 ? best_support : 0,
  1134. n_pending_connections);
  1135. preferredexits = smartlist_create();
  1136. add_nickname_list_to_smartlist(preferredexits,options->ExitNodes,1);
  1137. excludedexits = smartlist_create();
  1138. add_nickname_list_to_smartlist(excludedexits,options->ExcludeNodes,0);
  1139. sl = smartlist_create();
  1140. /* If any routers definitely support any pending connections, choose one
  1141. * at random. */
  1142. if (best_support > 0) {
  1143. for (i = 0; i < smartlist_len(dir->routers); i++)
  1144. if (n_supported[i] == best_support)
  1145. smartlist_add(sl, smartlist_get(dir->routers, i));
  1146. smartlist_subtract(sl,excludedexits);
  1147. if (options->StrictExitNodes || smartlist_overlap(sl,preferredexits))
  1148. smartlist_intersect(sl,preferredexits);
  1149. router = routerlist_sl_choose_by_bandwidth(sl, WEIGHT_FOR_EXIT);
  1150. } else {
  1151. /* Either there are no pending connections, or no routers even seem to
  1152. * possibly support any of them. Choose a router at random that satisfies
  1153. * at least one predicted exit port. */
  1154. int try;
  1155. smartlist_t *needed_ports;
  1156. if (best_support == -1) {
  1157. if (need_uptime || need_capacity) {
  1158. log_info(LD_CIRC,
  1159. "We couldn't find any live%s%s routers; falling back "
  1160. "to list of all routers.",
  1161. need_capacity?", fast":"",
  1162. need_uptime?", stable":"");
  1163. smartlist_free(preferredexits);
  1164. smartlist_free(excludedexits);
  1165. smartlist_free(sl);
  1166. tor_free(n_supported);
  1167. return choose_good_exit_server_general(dir, 0, 0);
  1168. }
  1169. log_notice(LD_CIRC, "All routers are down or won't exit -- choosing a "
  1170. "doomed exit at random.");
  1171. }
  1172. needed_ports = circuit_get_unhandled_ports(time(NULL));
  1173. for (try = 0; try < 2; try++) {
  1174. /* try once to pick only from routers that satisfy a needed port,
  1175. * then if there are none, pick from any that support exiting. */
  1176. for (i = 0; i < smartlist_len(dir->routers); i++) {
  1177. router = smartlist_get(dir->routers, i);
  1178. if (n_supported[i] != -1 &&
  1179. (try || router_handles_some_port(router, needed_ports))) {
  1180. // log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
  1181. // try, router->nickname);
  1182. smartlist_add(sl, router);
  1183. }
  1184. }
  1185. smartlist_subtract(sl,excludedexits);
  1186. if (options->StrictExitNodes || smartlist_overlap(sl,preferredexits))
  1187. smartlist_intersect(sl,preferredexits);
  1188. /* XXX sometimes the above results in null, when the requested
  1189. * exit node is down. we should pick it anyway. */
  1190. router = routerlist_sl_choose_by_bandwidth(sl, WEIGHT_FOR_EXIT);
  1191. if (router)
  1192. break;
  1193. }
  1194. SMARTLIST_FOREACH(needed_ports, uint16_t *, cp, tor_free(cp));
  1195. smartlist_free(needed_ports);
  1196. }
  1197. smartlist_free(preferredexits);
  1198. smartlist_free(excludedexits);
  1199. smartlist_free(sl);
  1200. tor_free(n_supported);
  1201. if (router) {
  1202. log_info(LD_CIRC, "Chose exit server '%s'", router->nickname);
  1203. return router;
  1204. }
  1205. if (options->StrictExitNodes) {
  1206. log_warn(LD_CIRC,
  1207. "No specified exit routers seem to be running, and "
  1208. "StrictExitNodes is set: can't choose an exit.");
  1209. }
  1210. return NULL;
  1211. }
  1212. /** Return a pointer to a suitable router to be the exit node for the
  1213. * circuit of purpose <b>purpose</b> that we're about to build (or NULL
  1214. * if no router is suitable).
  1215. *
  1216. * For general-purpose circuits, pass it off to
  1217. * choose_good_exit_server_general()
  1218. *
  1219. * For client-side rendezvous circuits, choose a random node, weighted
  1220. * toward the preferences in 'options'.
  1221. */
  1222. static routerinfo_t *
  1223. choose_good_exit_server(uint8_t purpose, routerlist_t *dir,
  1224. int need_uptime, int need_capacity, int is_internal)
  1225. {
  1226. or_options_t *options = get_options();
  1227. switch (purpose) {
  1228. case CIRCUIT_PURPOSE_C_GENERAL:
  1229. if (is_internal) /* pick it like a middle hop */
  1230. return router_choose_random_node(NULL, get_options()->ExcludeNodes,
  1231. NULL, need_uptime, need_capacity, 0,
  1232. get_options()->_AllowInvalid & ALLOW_INVALID_MIDDLE, 0, 0);
  1233. else
  1234. return choose_good_exit_server_general(dir,need_uptime,need_capacity);
  1235. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  1236. return router_choose_random_node(
  1237. options->RendNodes, options->RendExcludeNodes,
  1238. NULL, need_uptime, need_capacity, 0,
  1239. options->_AllowInvalid & ALLOW_INVALID_RENDEZVOUS, 0, 0);
  1240. }
  1241. log_warn(LD_BUG,"Unhandled purpose %d", purpose);
  1242. tor_fragile_assert();
  1243. return NULL;
  1244. }
  1245. /** Decide a suitable length for circ's cpath, and pick an exit
  1246. * router (or use <b>exit</b> if provided). Store these in the
  1247. * cpath. Return 0 if ok, -1 if circuit should be closed. */
  1248. static int
  1249. onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit)
  1250. {
  1251. cpath_build_state_t *state = circ->build_state;
  1252. routerlist_t *rl = router_get_routerlist();
  1253. if (state->onehop_tunnel) {
  1254. log_debug(LD_CIRC, "Launching a one-hop circuit for dir tunnel.");
  1255. state->desired_path_len = 1;
  1256. } else {
  1257. int r = new_route_len(circ->_base.purpose, exit, rl->routers);
  1258. if (r < 1) /* must be at least 1 */
  1259. return -1;
  1260. state->desired_path_len = r;
  1261. }
  1262. if (exit) { /* the circuit-builder pre-requested one */
  1263. log_info(LD_CIRC,"Using requested exit node '%s'", exit->nickname);
  1264. exit = extend_info_dup(exit);
  1265. } else { /* we have to decide one */
  1266. routerinfo_t *router =
  1267. choose_good_exit_server(circ->_base.purpose, rl, state->need_uptime,
  1268. state->need_capacity, state->is_internal);
  1269. if (!router) {
  1270. log_warn(LD_CIRC,"failed to choose an exit server");
  1271. return -1;
  1272. }
  1273. exit = extend_info_from_router(router);
  1274. }
  1275. state->chosen_exit = exit;
  1276. return 0;
  1277. }
  1278. /** Give <b>circ</b> a new exit destination to <b>exit</b>, and add a
  1279. * hop to the cpath reflecting this. Don't send the next extend cell --
  1280. * the caller will do this if it wants to.
  1281. */
  1282. int
  1283. circuit_append_new_exit(origin_circuit_t *circ, extend_info_t *exit)
  1284. {
  1285. cpath_build_state_t *state;
  1286. tor_assert(exit);
  1287. tor_assert(circ);
  1288. state = circ->build_state;
  1289. tor_assert(state);
  1290. if (state->chosen_exit)
  1291. extend_info_free(state->chosen_exit);
  1292. state->chosen_exit = extend_info_dup(exit);
  1293. ++circ->build_state->desired_path_len;
  1294. onion_append_hop(&circ->cpath, exit);
  1295. return 0;
  1296. }
  1297. /** Take an open <b>circ</b>, and add a new hop at the end, based on
  1298. * <b>info</b>. Set its state back to CIRCUIT_STATE_BUILDING, and then
  1299. * send the next extend cell to begin connecting to that hop.
  1300. */
  1301. int
  1302. circuit_extend_to_new_exit(origin_circuit_t *circ, extend_info_t *exit)
  1303. {
  1304. int err_reason = 0;
  1305. circuit_append_new_exit(circ, exit);
  1306. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  1307. if ((err_reason = circuit_send_next_onion_skin(circ))<0) {
  1308. log_warn(LD_CIRC, "Couldn't extend circuit to new point '%s'.",
  1309. exit->nickname);
  1310. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  1311. return -1;
  1312. }
  1313. return 0;
  1314. }
  1315. /** Return the number of routers in <b>routers</b> that are currently up
  1316. * and available for building circuits through.
  1317. */
  1318. static int
  1319. count_acceptable_routers(smartlist_t *routers)
  1320. {
  1321. int i, n;
  1322. int num=0;
  1323. routerinfo_t *r;
  1324. n = smartlist_len(routers);
  1325. for (i=0;i<n;i++) {
  1326. r = smartlist_get(routers, i);
  1327. // log_debug(LD_CIRC,
  1328. // "Contemplating whether router %d (%s) is a new option.",
  1329. // i, r->nickname);
  1330. if (r->is_running == 0) {
  1331. // log_debug(LD_CIRC,"Nope, the directory says %d is not running.",i);
  1332. goto next_i_loop;
  1333. }
  1334. if (r->is_valid == 0) {
  1335. // log_debug(LD_CIRC,"Nope, the directory says %d is not valid.",i);
  1336. goto next_i_loop;
  1337. /* XXX This clause makes us count incorrectly: if AllowInvalidRouters
  1338. * allows this node in some places, then we're getting an inaccurate
  1339. * count. For now, be conservative and don't count it. But later we
  1340. * should try to be smarter. */
  1341. }
  1342. num++;
  1343. // log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
  1344. next_i_loop:
  1345. ; /* C requires an explicit statement after the label */
  1346. }
  1347. return num;
  1348. }
  1349. /** Add <b>new_hop</b> to the end of the doubly-linked-list <b>head_ptr</b>.
  1350. * This function is used to extend cpath by another hop.
  1351. */
  1352. void
  1353. onion_append_to_cpath(crypt_path_t **head_ptr, crypt_path_t *new_hop)
  1354. {
  1355. if (*head_ptr) {
  1356. new_hop->next = (*head_ptr);
  1357. new_hop->prev = (*head_ptr)->prev;
  1358. (*head_ptr)->prev->next = new_hop;
  1359. (*head_ptr)->prev = new_hop;
  1360. } else {
  1361. *head_ptr = new_hop;
  1362. new_hop->prev = new_hop->next = new_hop;
  1363. }
  1364. }
  1365. /** Pick a random server digest that's running a Tor version that
  1366. * doesn't have the reachability bug. These are versions 0.1.1.21-cvs+
  1367. * and 0.1.2.1-alpha+. Avoid picking authorities, since we're
  1368. * probably already connected to them.
  1369. *
  1370. * We only return one, so this doesn't become stupid when the
  1371. * whole network has upgraded. */
  1372. static char *
  1373. compute_preferred_testing_list(const char *answer)
  1374. {
  1375. smartlist_t *choices;
  1376. routerlist_t *rl = router_get_routerlist();
  1377. routerinfo_t *router;
  1378. char *s;
  1379. if (answer) /* they have one in mind -- easy */
  1380. return tor_strdup(answer);
  1381. choices = smartlist_create();
  1382. /* now count up our choices */
  1383. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
  1384. if (r->is_running && r->is_valid &&
  1385. ((tor_version_as_new_as(r->platform,"0.1.1.21-cvs") &&
  1386. !tor_version_as_new_as(r->platform,"0.1.2.0-alpha-cvs")) ||
  1387. tor_version_as_new_as(r->platform,"0.1.2.1-alpha")) &&
  1388. !is_local_IP(r->addr) &&
  1389. !router_get_trusteddirserver_by_digest(r->cache_info.identity_digest))
  1390. smartlist_add(choices, r));
  1391. router = smartlist_choose(choices);
  1392. smartlist_free(choices);
  1393. if (!router) {
  1394. log_info(LD_CIRC, "Looking for middle server that doesn't have the "
  1395. "reachability bug, but didn't find one. Oh well.");
  1396. return NULL;
  1397. }
  1398. log_info(LD_CIRC, "Looking for middle server that doesn't have the "
  1399. "reachability bug, and chose '%s'. Great.", router->nickname);
  1400. s = tor_malloc(HEX_DIGEST_LEN+2);
  1401. s[0] = '$';
  1402. base16_encode(s+1, HEX_DIGEST_LEN+1,
  1403. router->cache_info.identity_digest, DIGEST_LEN);
  1404. return s;
  1405. }
  1406. /** A helper function used by onion_extend_cpath(). Use <b>purpose</b>
  1407. * and <b>state</b> and the cpath <b>head</b> (currently populated only
  1408. * to length <b>cur_len</b> to decide a suitable middle hop for a
  1409. * circuit. In particular, make sure we don't pick the exit node or its
  1410. * family, and make sure we don't duplicate any previous nodes or their
  1411. * families. */
  1412. static routerinfo_t *
  1413. choose_good_middle_server(uint8_t purpose,
  1414. cpath_build_state_t *state,
  1415. crypt_path_t *head,
  1416. int cur_len)
  1417. {
  1418. int i;
  1419. routerinfo_t *r, *choice;
  1420. crypt_path_t *cpath;
  1421. smartlist_t *excluded;
  1422. or_options_t *options = get_options();
  1423. char *preferred = NULL;
  1424. tor_assert(_CIRCUIT_PURPOSE_MIN <= purpose &&
  1425. purpose <= _CIRCUIT_PURPOSE_MAX);
  1426. log_debug(LD_CIRC, "Contemplating intermediate hop: random choice.");
  1427. excluded = smartlist_create();
  1428. if ((r = build_state_get_exit_router(state))) {
  1429. smartlist_add(excluded, r);
  1430. routerlist_add_family(excluded, r);
  1431. }
  1432. if ((r = routerlist_find_my_routerinfo())) {
  1433. smartlist_add(excluded, r);
  1434. routerlist_add_family(excluded, r);
  1435. }
  1436. for (i = 0, cpath = head; i < cur_len; ++i, cpath=cpath->next) {
  1437. if ((r = router_get_by_digest(cpath->extend_info->identity_digest))) {
  1438. smartlist_add(excluded, r);
  1439. routerlist_add_family(excluded, r);
  1440. }
  1441. }
  1442. if (purpose == CIRCUIT_PURPOSE_TESTING)
  1443. preferred = compute_preferred_testing_list(options->TestVia);
  1444. choice = router_choose_random_node(preferred,
  1445. options->ExcludeNodes, excluded,
  1446. state->need_uptime, state->need_capacity, 0,
  1447. options->_AllowInvalid & ALLOW_INVALID_MIDDLE, 0, 0);
  1448. tor_free(preferred);
  1449. smartlist_free(excluded);
  1450. return choice;
  1451. }
  1452. /** Pick a good entry server for the circuit to be built according to
  1453. * <b>state</b>. Don't reuse a chosen exit (if any), don't use this
  1454. * router (if we're an OR), and respect firewall settings; if we're
  1455. * configured to use entry guards, return one.
  1456. *
  1457. * If <b>state</b> is NULL, we're choosing a router to serve as an entry
  1458. * guard, not for any particular circuit.
  1459. */
  1460. static routerinfo_t *
  1461. choose_good_entry_server(uint8_t purpose, cpath_build_state_t *state)
  1462. {
  1463. routerinfo_t *r, *choice;
  1464. smartlist_t *excluded;
  1465. or_options_t *options = get_options();
  1466. (void)purpose; /* not used yet. */
  1467. if (state && options->UseEntryGuards) {
  1468. return choose_random_entry(state);
  1469. }
  1470. excluded = smartlist_create();
  1471. if (state && (r = build_state_get_exit_router(state))) {
  1472. smartlist_add(excluded, r);
  1473. routerlist_add_family(excluded, r);
  1474. }
  1475. if ((r = routerlist_find_my_routerinfo())) {
  1476. smartlist_add(excluded, r);
  1477. routerlist_add_family(excluded, r);
  1478. }
  1479. if (firewall_is_fascist_or()) {
  1480. /* exclude all ORs that listen on the wrong port */
  1481. routerlist_t *rl = router_get_routerlist();
  1482. int i;
  1483. for (i=0; i < smartlist_len(rl->routers); i++) {
  1484. r = smartlist_get(rl->routers, i);
  1485. if (!fascist_firewall_allows_address_or(r->addr,r->or_port))
  1486. smartlist_add(excluded, r);
  1487. }
  1488. }
  1489. /* and exclude current entry guards, if applicable */
  1490. if (options->UseEntryGuards && entry_guards) {
  1491. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  1492. {
  1493. if ((r = router_get_by_digest(entry->identity)))
  1494. smartlist_add(excluded, r);
  1495. });
  1496. }
  1497. choice = router_choose_random_node(
  1498. NULL, options->ExcludeNodes,
  1499. excluded, state ? state->need_uptime : 0,
  1500. state ? state->need_capacity : 0,
  1501. state ? 0 : 1,
  1502. options->_AllowInvalid & ALLOW_INVALID_ENTRY, 0, 0);
  1503. smartlist_free(excluded);
  1504. return choice;
  1505. }
  1506. /** Return the first non-open hop in cpath, or return NULL if all
  1507. * hops are open. */
  1508. static crypt_path_t *
  1509. onion_next_hop_in_cpath(crypt_path_t *cpath)
  1510. {
  1511. crypt_path_t *hop = cpath;
  1512. do {
  1513. if (hop->state != CPATH_STATE_OPEN)
  1514. return hop;
  1515. hop = hop->next;
  1516. } while (hop != cpath);
  1517. return NULL;
  1518. }
  1519. /** Choose a suitable next hop in the cpath <b>head_ptr</b>,
  1520. * based on <b>state</b>. Append the hop info to head_ptr.
  1521. */
  1522. static int
  1523. onion_extend_cpath(origin_circuit_t *circ)
  1524. {
  1525. uint8_t purpose = circ->_base.purpose;
  1526. cpath_build_state_t *state = circ->build_state;
  1527. int cur_len = circuit_get_cpath_len(circ);
  1528. extend_info_t *info = NULL;
  1529. if (cur_len >= state->desired_path_len) {
  1530. log_debug(LD_CIRC, "Path is complete: %d steps long",
  1531. state->desired_path_len);
  1532. return 1;
  1533. }
  1534. log_debug(LD_CIRC, "Path is %d long; we want %d", cur_len,
  1535. state->desired_path_len);
  1536. if (cur_len == state->desired_path_len - 1) { /* Picking last node */
  1537. info = extend_info_dup(state->chosen_exit);
  1538. } else if (cur_len == 0) { /* picking first node */
  1539. routerinfo_t *r = choose_good_entry_server(purpose, state);
  1540. if (r)
  1541. info = extend_info_from_router(r);
  1542. } else {
  1543. routerinfo_t *r =
  1544. choose_good_middle_server(purpose, state, circ->cpath, cur_len);
  1545. if (r)
  1546. info = extend_info_from_router(r);
  1547. }
  1548. if (!info) {
  1549. log_warn(LD_CIRC,"Failed to find node for hop %d of our path. Discarding "
  1550. "this circuit.", cur_len);
  1551. return -1;
  1552. }
  1553. log_debug(LD_CIRC,"Chose router %s for hop %d (exit is %s)",
  1554. info->nickname, cur_len+1, build_state_get_exit_nickname(state));
  1555. onion_append_hop(&circ->cpath, info);
  1556. extend_info_free(info);
  1557. return 0;
  1558. }
  1559. /** Create a new hop, annotate it with information about its
  1560. * corresponding router <b>choice</b>, and append it to the
  1561. * end of the cpath <b>head_ptr</b>. */
  1562. static int
  1563. onion_append_hop(crypt_path_t **head_ptr, extend_info_t *choice)
  1564. {
  1565. crypt_path_t *hop = tor_malloc_zero(sizeof(crypt_path_t));
  1566. /* link hop into the cpath, at the end. */
  1567. onion_append_to_cpath(head_ptr, hop);
  1568. hop->magic = CRYPT_PATH_MAGIC;
  1569. hop->state = CPATH_STATE_CLOSED;
  1570. hop->extend_info = extend_info_dup(choice);
  1571. hop->package_window = CIRCWINDOW_START;
  1572. hop->deliver_window = CIRCWINDOW_START;
  1573. return 0;
  1574. }
  1575. /** Allocate a new extend_info object based on the various arguments. */
  1576. extend_info_t *
  1577. extend_info_alloc(const char *nickname, const char *digest,
  1578. crypto_pk_env_t *onion_key,
  1579. uint32_t addr, uint16_t port)
  1580. {
  1581. extend_info_t *info = tor_malloc_zero(sizeof(extend_info_t));
  1582. memcpy(info->identity_digest, digest, DIGEST_LEN);
  1583. if (nickname)
  1584. strlcpy(info->nickname, nickname, sizeof(info->nickname));
  1585. if (onion_key)
  1586. info->onion_key = crypto_pk_dup_key(onion_key);
  1587. info->addr = addr;
  1588. info->port = port;
  1589. return info;
  1590. }
  1591. /** Allocate and return a new extend_info_t that can be used to build a
  1592. * circuit to or through the router <b>r</b>. */
  1593. extend_info_t *
  1594. extend_info_from_router(routerinfo_t *r)
  1595. {
  1596. tor_assert(r);
  1597. return extend_info_alloc(r->nickname, r->cache_info.identity_digest,
  1598. r->onion_pkey, r->addr, r->or_port);
  1599. }
  1600. #if 0
  1601. /** What router purpose is <b>digest</b>?
  1602. * It's a general purpose router unless it's on our bridges list.
  1603. */
  1604. static uint8_t
  1605. get_router_purpose_from_digest(char *digest)
  1606. {
  1607. if (digest_is_a_bridge(digest))
  1608. return ROUTER_PURPOSE_BRIDGE;
  1609. return ROUTER_PURPOSE_GENERAL;
  1610. }
  1611. #endif
  1612. #if 0
  1613. /** Allocate and return a new extend_info_t that can be used to build a
  1614. * circuit to or through the router <b>r</b>. */
  1615. extend_info_t *
  1616. extend_info_from_routerstatus(routerstatus_t *s)
  1617. {
  1618. tor_assert(s);
  1619. /* routerstatus doesn't know onion_key; leave it NULL */
  1620. return extend_info_alloc(s->nickname, s->identity_digest,
  1621. NULL, s->addr, s->or_port);
  1622. // get_router_purpose_from_digest(s->identity_digest));
  1623. }
  1624. #endif
  1625. /** Release storage held by an extend_info_t struct. */
  1626. void
  1627. extend_info_free(extend_info_t *info)
  1628. {
  1629. tor_assert(info);
  1630. if (info->onion_key)
  1631. crypto_free_pk_env(info->onion_key);
  1632. tor_free(info);
  1633. }
  1634. /** Allocate and return a new extend_info_t with the same contents as
  1635. * <b>info</b>. */
  1636. extend_info_t *
  1637. extend_info_dup(extend_info_t *info)
  1638. {
  1639. extend_info_t *newinfo;
  1640. tor_assert(info);
  1641. newinfo = tor_malloc(sizeof(extend_info_t));
  1642. memcpy(newinfo, info, sizeof(extend_info_t));
  1643. if (info->onion_key)
  1644. newinfo->onion_key = crypto_pk_dup_key(info->onion_key);
  1645. else
  1646. newinfo->onion_key = NULL;
  1647. return newinfo;
  1648. }
  1649. /** Return the routerinfo_t for the chosen exit router in <b>state</b>.
  1650. * If there is no chosen exit, or if we don't know the routerinfo_t for
  1651. * the chosen exit, return NULL.
  1652. */
  1653. routerinfo_t *
  1654. build_state_get_exit_router(cpath_build_state_t *state)
  1655. {
  1656. if (!state || !state->chosen_exit)
  1657. return NULL;
  1658. return router_get_by_digest(state->chosen_exit->identity_digest);
  1659. }
  1660. /** Return the nickname for the chosen exit router in <b>state</b>. If
  1661. * there is no chosen exit, or if we don't know the routerinfo_t for the
  1662. * chosen exit, return NULL.
  1663. */
  1664. const char *
  1665. build_state_get_exit_nickname(cpath_build_state_t *state)
  1666. {
  1667. if (!state || !state->chosen_exit)
  1668. return NULL;
  1669. return state->chosen_exit->nickname;
  1670. }
  1671. /** Check whether the entry guard <b>e</b> is usable, given the directory
  1672. * authorities' opinion about the router (stored in <b>ri</b>) and the user's
  1673. * configuration (in <b>options</b>). Set <b>e</b>-&gt;bad_since
  1674. * accordingly. Return true iff the entry guard's status changes.
  1675. *
  1676. * If it's not usable, set *<b>reason</b> to a static string explaining why.
  1677. */
  1678. static int
  1679. entry_guard_set_status(entry_guard_t *e, routerinfo_t *ri,
  1680. time_t now, or_options_t *options, const char **reason)
  1681. {
  1682. char buf[HEX_DIGEST_LEN+1];
  1683. int changed = 0;
  1684. tor_assert(options);
  1685. *reason = NULL;
  1686. /* Do we want to mark this guard as bad? */
  1687. if (!ri)
  1688. *reason = "unlisted";
  1689. else if (!ri->is_running)
  1690. *reason = "down";
  1691. else if (options->UseBridges && ri->purpose != ROUTER_PURPOSE_BRIDGE)
  1692. *reason = "not a bridge";
  1693. else if (!options->UseBridges && !ri->is_possible_guard &&
  1694. !router_nickname_is_in_list(ri, options->EntryNodes))
  1695. *reason = "not recommended as a guard";
  1696. else if (router_nickname_is_in_list(ri, options->ExcludeNodes))
  1697. *reason = "excluded";
  1698. if (*reason && ! e->bad_since) {
  1699. /* Router is newly bad. */
  1700. base16_encode(buf, sizeof(buf), e->identity, DIGEST_LEN);
  1701. log_info(LD_CIRC, "Entry guard %s (%s) is %s: marking as unusable.",
  1702. e->nickname, buf, *reason);
  1703. e->bad_since = now;
  1704. control_event_guard(e->nickname, e->identity, "BAD");
  1705. changed = 1;
  1706. } else if (!*reason && e->bad_since) {
  1707. /* There's nothing wrong with the router any more. */
  1708. base16_encode(buf, sizeof(buf), e->identity, DIGEST_LEN);
  1709. log_info(LD_CIRC, "Entry guard %s (%s) is no longer unusable: "
  1710. "marking as ok.", e->nickname, buf);
  1711. e->bad_since = 0;
  1712. control_event_guard(e->nickname, e->identity, "GOOD");
  1713. changed = 1;
  1714. }
  1715. return changed;
  1716. }
  1717. /** Return true iff enough time has passed since we last tried to connect
  1718. * to the unreachable guard <b>e</b> that we're willing to try again. */
  1719. static int
  1720. entry_is_time_to_retry(entry_guard_t *e, time_t now)
  1721. {
  1722. long diff;
  1723. if (e->last_attempted < e->unreachable_since)
  1724. return 1;
  1725. diff = now - e->unreachable_since;
  1726. if (diff < 6*60*60)
  1727. return now > (e->last_attempted + 60*60);
  1728. else if (diff < 3*24*60*60)
  1729. return now > (e->last_attempted + 4*60*60);
  1730. else if (diff < 7*24*60*60)
  1731. return now > (e->last_attempted + 18*60*60);
  1732. else
  1733. return now > (e->last_attempted + 36*60*60);
  1734. }
  1735. /** Return the router corresponding to <b>e</b>, if <b>e</b> is
  1736. * working well enough that we are willing to use it as an entry
  1737. * right now. (Else return NULL.) In particular, it must be
  1738. * - Listed as either up or never yet contacted;
  1739. * - Present in the routerlist;
  1740. * - Listed as 'stable' or 'fast' by the current dirserver concensus,
  1741. * if demanded by <b>need_uptime</b> or <b>need_capacity</b>;
  1742. * (This check is currently redundant with the Guard flag, but in
  1743. * the future that might change. Best to leave it in for now.)
  1744. * - Allowed by our current ReachableORAddresses config option; and
  1745. * - Currently thought to be reachable by us (unless assume_reachable
  1746. * is true).
  1747. */
  1748. static INLINE routerinfo_t *
  1749. entry_is_live(entry_guard_t *e, int need_uptime, int need_capacity,
  1750. int assume_reachable)
  1751. {
  1752. routerinfo_t *r;
  1753. if (e->bad_since)
  1754. return NULL;
  1755. /* no good if it's unreachable, unless assume_unreachable or can_retry. */
  1756. if ((!assume_reachable && !e->can_retry) &&
  1757. e->unreachable_since && !entry_is_time_to_retry(e, time(NULL)))
  1758. return NULL;
  1759. r = router_get_by_digest(e->identity);
  1760. if (!r)
  1761. return NULL;
  1762. if (get_options()->UseBridges && r->purpose != ROUTER_PURPOSE_BRIDGE)
  1763. return NULL;
  1764. if (!get_options()->UseBridges && r->purpose != ROUTER_PURPOSE_GENERAL)
  1765. return NULL;
  1766. if (router_is_unreliable(r, need_uptime, need_capacity, 0))
  1767. return NULL;
  1768. if (!fascist_firewall_allows_address_or(r->addr,r->or_port))
  1769. return NULL;
  1770. return r;
  1771. }
  1772. /** Return the number of entry guards that we think are usable. */
  1773. static int
  1774. num_live_entry_guards(void)
  1775. {
  1776. int n = 0;
  1777. if (! entry_guards)
  1778. return 0;
  1779. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  1780. {
  1781. if (entry_is_live(entry, 0, 1, 0))
  1782. ++n;
  1783. });
  1784. return n;
  1785. }
  1786. /** If <b>digest</b> matches the identity of any node in the
  1787. * entry_guards list, return that node. Else return NULL. */
  1788. static INLINE entry_guard_t *
  1789. is_an_entry_guard(const char *digest)
  1790. {
  1791. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  1792. if (!memcmp(digest, entry->identity, DIGEST_LEN))
  1793. return entry;
  1794. );
  1795. return NULL;
  1796. }
  1797. /** Dump a description of our list of entry guards to the log at level
  1798. * <b>severity</b>. */
  1799. static void
  1800. log_entry_guards(int severity)
  1801. {
  1802. smartlist_t *elements = smartlist_create();
  1803. char buf[1024];
  1804. char *s;
  1805. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  1806. {
  1807. tor_snprintf(buf, sizeof(buf), "%s (%s%s)",
  1808. e->nickname,
  1809. e->bad_since ? "down " : "up ",
  1810. e->made_contact ? "made-contact" : "never-contacted");
  1811. smartlist_add(elements, tor_strdup(buf));
  1812. });
  1813. s = smartlist_join_strings(elements, ",", 0, NULL);
  1814. SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
  1815. smartlist_free(elements);
  1816. log_fn(severity,LD_CIRC,"%s",s);
  1817. tor_free(s);
  1818. }
  1819. /** Called when one or more guards that we would previously have used for some
  1820. * purpose are no longer in use because a higher-priority guard has become
  1821. * useable again. */
  1822. static void
  1823. control_event_guard_deferred(void)
  1824. {
  1825. /* XXXX We don't actually have a good way to figure out _how many_ entries
  1826. * are live for some purpose. We need an entry_is_even_slightly_live()
  1827. * function for this to work right. NumEntryGuards isn't reliable: if we
  1828. * need guards with weird properties, we can have more than that number
  1829. * live.
  1830. **/
  1831. #if 0
  1832. int n = 0;
  1833. or_options_t *options = get_options();
  1834. if (!entry_guards)
  1835. return;
  1836. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  1837. {
  1838. if (entry_is_live(entry, 0, 1, 0)) {
  1839. if (n++ == options->NumEntryGuards) {
  1840. control_event_guard(entry->nickname, entry->identity, "DEFERRED");
  1841. return;
  1842. }
  1843. }
  1844. });
  1845. #endif
  1846. }
  1847. /** Add a new (preferably stable and fast) router to our
  1848. * entry_guards list. Return a pointer to the router if we succeed,
  1849. * or NULL if we can't find any more suitable entries.
  1850. *
  1851. * If <b>chosen</b> is defined, use that one, and if it's not
  1852. * already in our entry_guards list, put it at the *beginning*.
  1853. * Else, put the one we pick at the end of the list. */
  1854. static routerinfo_t *
  1855. add_an_entry_guard(routerinfo_t *chosen, int reset_status)
  1856. {
  1857. routerinfo_t *router;
  1858. entry_guard_t *entry;
  1859. if (chosen) {
  1860. router = chosen;
  1861. entry = is_an_entry_guard(router->cache_info.identity_digest);
  1862. if (entry) {
  1863. if (reset_status) {
  1864. entry->bad_since = 0;
  1865. entry->can_retry = 1;
  1866. }
  1867. return NULL;
  1868. }
  1869. } else {
  1870. router = choose_good_entry_server(CIRCUIT_PURPOSE_C_GENERAL, NULL);
  1871. if (!router)
  1872. return NULL;
  1873. }
  1874. entry = tor_malloc_zero(sizeof(entry_guard_t));
  1875. log_info(LD_CIRC, "Chose '%s' as new entry guard.", router->nickname);
  1876. strlcpy(entry->nickname, router->nickname, sizeof(entry->nickname));
  1877. memcpy(entry->identity, router->cache_info.identity_digest, DIGEST_LEN);
  1878. entry->chosen_on_date = start_of_month(time(NULL));
  1879. entry->chosen_by_version = tor_strdup(VERSION);
  1880. if (chosen) /* prepend */
  1881. smartlist_insert(entry_guards, 0, entry);
  1882. else /* append */
  1883. smartlist_add(entry_guards, entry);
  1884. control_event_guard(entry->nickname, entry->identity, "NEW");
  1885. control_event_guard_deferred();
  1886. log_entry_guards(LOG_INFO);
  1887. return router;
  1888. }
  1889. /** If the use of entry guards is configured, choose more entry guards
  1890. * until we have enough in the list. */
  1891. static void
  1892. pick_entry_guards(void)
  1893. {
  1894. or_options_t *options = get_options();
  1895. int changed = 0;
  1896. tor_assert(entry_guards);
  1897. while (num_live_entry_guards() < options->NumEntryGuards) {
  1898. if (!add_an_entry_guard(NULL, 0))
  1899. break;
  1900. changed = 1;
  1901. }
  1902. if (changed)
  1903. entry_guards_changed();
  1904. }
  1905. /** How long (in seconds) do we allow an entry guard to be nonfunctional,
  1906. * unlisted, excluded, or otherwise nonusable before we give up on it? */
  1907. #define ENTRY_GUARD_REMOVE_AFTER (30*24*60*60)
  1908. /** Release all storage held by <b>e</b>. */
  1909. static void
  1910. entry_guard_free(entry_guard_t *e)
  1911. {
  1912. tor_assert(e);
  1913. tor_free(e->chosen_by_version);
  1914. tor_free(e);
  1915. }
  1916. /** Remove any entry guard which was selected by an unknown version of Tor,
  1917. * or which was selected by a version of Tor that's known to select
  1918. * entry guards badly. */
  1919. static int
  1920. remove_obsolete_entry_guards(void)
  1921. {
  1922. int changed = 0, i;
  1923. for (i = 0; i < smartlist_len(entry_guards); ++i) {
  1924. entry_guard_t *entry = smartlist_get(entry_guards, i);
  1925. const char *ver = entry->chosen_by_version;
  1926. const char *msg = NULL;
  1927. tor_version_t v;
  1928. int version_is_bad = 0;
  1929. if (!ver) {
  1930. msg = "does not say what version of Tor it was selected by";
  1931. version_is_bad = 1;
  1932. } else if (tor_version_parse(ver, &v)) {
  1933. msg = "does not seem to be from any recognized version of Tor";
  1934. version_is_bad = 1;
  1935. } else if ((tor_version_as_new_as(ver, "0.1.0.10-alpha") &&
  1936. !tor_version_as_new_as(ver, "0.1.2.16-dev")) ||
  1937. (tor_version_as_new_as(ver, "0.2.0.0-alpha") &&
  1938. !tor_version_as_new_as(ver, "0.2.0.6-alpha"))) {
  1939. msg = "was selected without regard for guard bandwidth";
  1940. version_is_bad = 1;
  1941. }
  1942. if (version_is_bad) {
  1943. char dbuf[HEX_DIGEST_LEN+1];
  1944. tor_assert(msg);
  1945. base16_encode(dbuf, sizeof(dbuf), entry->identity, DIGEST_LEN);
  1946. log_notice(LD_CIRC, "Entry guard '%s' (%s) %s. (Version=%s.) "
  1947. "Replacing it.",
  1948. entry->nickname, dbuf, msg, ver?escaped(ver):"none");
  1949. control_event_guard(entry->nickname, entry->identity, "DROPPED");
  1950. entry_guard_free(entry);
  1951. smartlist_del_keeporder(entry_guards, i--);
  1952. log_entry_guards(LOG_INFO);
  1953. changed = 1;
  1954. }
  1955. }
  1956. return changed ? 1 : 0;
  1957. }
  1958. /** Remove all entry guards that have been down or unlisted for so
  1959. * long that we don't think they'll come up again. Return 1 if we
  1960. * removed any, or 0 if we did nothing. */
  1961. static int
  1962. remove_dead_entry_guards(void)
  1963. {
  1964. char dbuf[HEX_DIGEST_LEN+1];
  1965. char tbuf[ISO_TIME_LEN+1];
  1966. time_t now = time(NULL);
  1967. int i;
  1968. int changed = 0;
  1969. for (i = 0; i < smartlist_len(entry_guards); ) {
  1970. entry_guard_t *entry = smartlist_get(entry_guards, i);
  1971. if (entry->bad_since &&
  1972. entry->bad_since + ENTRY_GUARD_REMOVE_AFTER < now) {
  1973. base16_encode(dbuf, sizeof(dbuf), entry->identity, DIGEST_LEN);
  1974. format_local_iso_time(tbuf, entry->bad_since);
  1975. log_info(LD_CIRC, "Entry guard '%s' (%s) has been down or unlisted "
  1976. "since %s local time; removing.",
  1977. entry->nickname, dbuf, tbuf);
  1978. control_event_guard(entry->nickname, entry->identity, "DROPPED");
  1979. entry_guard_free(entry);
  1980. smartlist_del_keeporder(entry_guards, i);
  1981. log_entry_guards(LOG_INFO);
  1982. changed = 1;
  1983. } else
  1984. ++i;
  1985. }
  1986. return changed ? 1 : 0;
  1987. }
  1988. /** A new directory or router-status has arrived; update the down/listed
  1989. * status of the entry guards.
  1990. *
  1991. * An entry is 'down' if the directory lists it as nonrunning.
  1992. * An entry is 'unlisted' if the directory doesn't include it.
  1993. *
  1994. * Don't call this on startup; only on a fresh download. Otherwise we'll
  1995. * think that things are unlisted.
  1996. */
  1997. void
  1998. entry_guards_compute_status(void)
  1999. {
  2000. time_t now;
  2001. int changed = 0;
  2002. int severity = LOG_INFO;
  2003. or_options_t *options;
  2004. if (! entry_guards)
  2005. return;
  2006. options = get_options();
  2007. now = time(NULL);
  2008. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  2009. {
  2010. routerinfo_t *r = router_get_by_digest(entry->identity);
  2011. const char *reason = NULL;
  2012. if (entry_guard_set_status(entry, r, now, options, &reason))
  2013. changed = 1;
  2014. if (entry->bad_since)
  2015. tor_assert(reason);
  2016. log_info(LD_CIRC, "Summary: Entry '%s' is %s, %s%s, and %s.",
  2017. entry->nickname,
  2018. entry->unreachable_since ? "unreachable" : "reachable",
  2019. entry->bad_since ? "unusable: " : "usable",
  2020. entry->bad_since ? reason : "",
  2021. entry_is_live(entry, 0, 1, 0) ? "live" : "not live");
  2022. });
  2023. if (remove_dead_entry_guards())
  2024. changed = 1;
  2025. if (changed) {
  2026. log_fn(severity, LD_CIRC, " (%d/%d entry guards are usable/new)",
  2027. num_live_entry_guards(), smartlist_len(entry_guards));
  2028. log_entry_guards(LOG_INFO);
  2029. entry_guards_changed();
  2030. }
  2031. }
  2032. /** Called when a connection to an OR with the identity digest <b>digest</b>
  2033. * is established (<b>succeeded</b>==1) or has failed (<b>succeeded</b>==0).
  2034. * If the OR is an entry, change that entry's up/down status.
  2035. * Return 0 normally, or -1 if we want to tear down the new connection.
  2036. */
  2037. int
  2038. entry_guard_register_connect_status(const char *digest, int succeeded,
  2039. time_t now)
  2040. {
  2041. int changed = 0;
  2042. int refuse_conn = 0;
  2043. int first_contact = 0;
  2044. entry_guard_t *entry = NULL;
  2045. int idx = -1;
  2046. char buf[HEX_DIGEST_LEN+1];
  2047. if (! entry_guards)
  2048. return 0;
  2049. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  2050. {
  2051. if (!memcmp(e->identity, digest, DIGEST_LEN)) {
  2052. entry = e;
  2053. idx = e_sl_idx;
  2054. break;
  2055. }
  2056. });
  2057. if (!entry)
  2058. return 0;
  2059. base16_encode(buf, sizeof(buf), entry->identity, DIGEST_LEN);
  2060. if (succeeded) {
  2061. if (entry->unreachable_since) {
  2062. log_info(LD_CIRC, "Entry guard '%s' (%s) is now reachable again. Good.",
  2063. entry->nickname, buf);
  2064. entry->can_retry = 0;
  2065. entry->unreachable_since = 0;
  2066. entry->last_attempted = now;
  2067. control_event_guard(entry->nickname, entry->identity, "UP");
  2068. changed = 1;
  2069. }
  2070. if (!entry->made_contact) {
  2071. entry->made_contact = 1;
  2072. first_contact = changed = 1;
  2073. }
  2074. } else { /* ! succeeded */
  2075. if (!entry->made_contact) {
  2076. /* We've never connected to this one. */
  2077. log_info(LD_CIRC,
  2078. "Connection to never-contacted entry guard '%s' (%s) failed. "
  2079. "Removing from the list. %d/%d entry guards usable/new.",
  2080. entry->nickname, buf,
  2081. num_live_entry_guards()-1, smartlist_len(entry_guards)-1);
  2082. entry_guard_free(entry);
  2083. smartlist_del_keeporder(entry_guards, idx);
  2084. log_entry_guards(LOG_INFO);
  2085. changed = 1;
  2086. } else if (!entry->unreachable_since) {
  2087. log_info(LD_CIRC, "Unable to connect to entry guard '%s' (%s). "
  2088. "Marking as unreachable.", entry->nickname, buf);
  2089. entry->unreachable_since = entry->last_attempted = now;
  2090. control_event_guard(entry->nickname, entry->identity, "DOWN");
  2091. changed = 1;
  2092. entry->can_retry = 0; /* We gave it an early chance; no good. */
  2093. } else {
  2094. char tbuf[ISO_TIME_LEN+1];
  2095. format_iso_time(tbuf, entry->unreachable_since);
  2096. log_debug(LD_CIRC, "Failed to connect to unreachable entry guard "
  2097. "'%s' (%s). It has been unreachable since %s.",
  2098. entry->nickname, buf, tbuf);
  2099. entry->last_attempted = now;
  2100. entry->can_retry = 0; /* We gave it an early chance; no good. */
  2101. }
  2102. }
  2103. if (first_contact) {
  2104. /* We've just added a new long-term entry guard. Perhaps the network just
  2105. * came back? We should give our earlier entries another try too,
  2106. * and close this connection so we don't use it before we've given
  2107. * the others a shot. */
  2108. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e, {
  2109. if (e == entry)
  2110. break;
  2111. if (e->made_contact) {
  2112. routerinfo_t *r = entry_is_live(e, 0, 1, 1);
  2113. if (r && e->unreachable_since) {
  2114. refuse_conn = 1;
  2115. e->can_retry = 1;
  2116. }
  2117. }
  2118. });
  2119. if (refuse_conn) {
  2120. log_info(LD_CIRC,
  2121. "Connected to new entry guard '%s' (%s). Marking earlier "
  2122. "entry guards up. %d/%d entry guards usable/new.",
  2123. entry->nickname, buf,
  2124. num_live_entry_guards(), smartlist_len(entry_guards));
  2125. log_entry_guards(LOG_INFO);
  2126. changed = 1;
  2127. }
  2128. }
  2129. if (changed)
  2130. entry_guards_changed();
  2131. return refuse_conn ? -1 : 0;
  2132. }
  2133. /** When we try to choose an entry guard, should we parse and add
  2134. * config's EntryNodes first? */
  2135. static int should_add_entry_nodes = 0;
  2136. /** Called when the value of EntryNodes changes in our configuration. */
  2137. void
  2138. entry_nodes_should_be_added(void)
  2139. {
  2140. log_info(LD_CIRC, "New EntryNodes config option detected. Will use.");
  2141. should_add_entry_nodes = 1;
  2142. }
  2143. /** Add all nodes in EntryNodes that aren't currently guard nodes to the list
  2144. * of guard nodes, at the front. */
  2145. static void
  2146. entry_guards_prepend_from_config(void)
  2147. {
  2148. or_options_t *options = get_options();
  2149. smartlist_t *entry_routers, *entry_fps;
  2150. smartlist_t *old_entry_guards_on_list, *old_entry_guards_not_on_list;
  2151. tor_assert(entry_guards);
  2152. should_add_entry_nodes = 0;
  2153. if (!options->EntryNodes) {
  2154. /* It's possible that a controller set EntryNodes, thus making
  2155. * should_add_entry_nodes set, then cleared it again, all before the
  2156. * call to choose_random_entry() that triggered us. If so, just return.
  2157. */
  2158. return;
  2159. }
  2160. log_info(LD_CIRC,"Adding configured EntryNodes '%s'.",
  2161. options->EntryNodes);
  2162. entry_routers = smartlist_create();
  2163. entry_fps = smartlist_create();
  2164. old_entry_guards_on_list = smartlist_create();
  2165. old_entry_guards_not_on_list = smartlist_create();
  2166. /* Split entry guards into those on the list and those not. */
  2167. add_nickname_list_to_smartlist(entry_routers, options->EntryNodes, 0);
  2168. SMARTLIST_FOREACH(entry_routers, routerinfo_t *, ri,
  2169. smartlist_add(entry_fps,ri->cache_info.identity_digest));
  2170. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e, {
  2171. if (smartlist_digest_isin(entry_fps, e->identity))
  2172. smartlist_add(old_entry_guards_on_list, e);
  2173. else
  2174. smartlist_add(old_entry_guards_not_on_list, e);
  2175. });
  2176. /* Remove all currently configured entry guards from entry_routers. */
  2177. SMARTLIST_FOREACH(entry_routers, routerinfo_t *, ri, {
  2178. if (is_an_entry_guard(ri->cache_info.identity_digest)) {
  2179. SMARTLIST_DEL_CURRENT(entry_routers, ri);
  2180. }
  2181. });
  2182. /* Now build the new entry_guards list. */
  2183. smartlist_clear(entry_guards);
  2184. /* First, the previously configured guards that are in EntryNodes. */
  2185. smartlist_add_all(entry_guards, old_entry_guards_on_list);
  2186. /* Next, the rest of EntryNodes */
  2187. SMARTLIST_FOREACH(entry_routers, routerinfo_t *, ri, {
  2188. add_an_entry_guard(ri, 0);
  2189. });
  2190. /* Finally, the remaining EntryNodes, unless we're strict */
  2191. if (options->StrictEntryNodes) {
  2192. SMARTLIST_FOREACH(old_entry_guards_not_on_list, entry_guard_t *, e,
  2193. entry_guard_free(e));
  2194. } else {
  2195. smartlist_add_all(entry_guards, old_entry_guards_not_on_list);
  2196. }
  2197. smartlist_free(entry_routers);
  2198. smartlist_free(entry_fps);
  2199. smartlist_free(old_entry_guards_on_list);
  2200. smartlist_free(old_entry_guards_not_on_list);
  2201. entry_guards_changed();
  2202. }
  2203. /** Return 1 if we're fine adding arbitrary routers out of the
  2204. * directory to our entry guard list. Else return 0. */
  2205. int
  2206. entry_list_can_grow(or_options_t *options)
  2207. {
  2208. if (options->StrictEntryNodes)
  2209. return 0;
  2210. if (options->UseBridges)
  2211. return 0;
  2212. return 1;
  2213. }
  2214. /** Pick a live (up and listed) entry guard from entry_guards. If
  2215. * <b>state</b> is non-NULL, this is for a specific circuit --
  2216. * make sure not to pick this circuit's exit or any node in the
  2217. * exit's family. If <b>state</b> is NULL, we're looking for a random
  2218. * guard (likely a bridge). */
  2219. routerinfo_t *
  2220. choose_random_entry(cpath_build_state_t *state)
  2221. {
  2222. or_options_t *options = get_options();
  2223. smartlist_t *live_entry_guards = smartlist_create();
  2224. smartlist_t *exit_family = smartlist_create();
  2225. routerinfo_t *chosen_exit = state?build_state_get_exit_router(state) : NULL;
  2226. routerinfo_t *r = NULL;
  2227. int need_uptime = state ? state->need_uptime : 0;
  2228. int need_capacity = state ? state->need_capacity : 0;
  2229. int consider_exit_family = 0;
  2230. if (chosen_exit) {
  2231. smartlist_add(exit_family, chosen_exit);
  2232. routerlist_add_family(exit_family, chosen_exit);
  2233. consider_exit_family = 1;
  2234. }
  2235. if (!entry_guards)
  2236. entry_guards = smartlist_create();
  2237. if (should_add_entry_nodes)
  2238. entry_guards_prepend_from_config();
  2239. if (entry_list_can_grow(options) &&
  2240. (! entry_guards ||
  2241. smartlist_len(entry_guards) < options->NumEntryGuards))
  2242. pick_entry_guards();
  2243. retry:
  2244. smartlist_clear(live_entry_guards);
  2245. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  2246. {
  2247. r = entry_is_live(entry, need_uptime, need_capacity, 0);
  2248. if (r && (!consider_exit_family || !smartlist_isin(exit_family, r))) {
  2249. smartlist_add(live_entry_guards, r);
  2250. if (!entry->made_contact) {
  2251. /* Always start with the first not-yet-contacted entry
  2252. * guard. Otherwise we might add several new ones, pick
  2253. * the second new one, and now we've expanded our entry
  2254. * guard list without needing to. */
  2255. goto choose_and_finish;
  2256. }
  2257. if (smartlist_len(live_entry_guards) >= options->NumEntryGuards)
  2258. break; /* we have enough */
  2259. }
  2260. });
  2261. /* Try to have at least 2 choices available. This way we don't
  2262. * get stuck with a single live-but-crummy entry and just keep
  2263. * using him.
  2264. * (We might get 2 live-but-crummy entry guards, but so be it.) */
  2265. if (smartlist_len(live_entry_guards) < 2) {
  2266. if (entry_list_can_grow(options)) {
  2267. /* still no? try adding a new entry then */
  2268. /* XXX if guard doesn't imply fast and stable, then we need
  2269. * to tell add_an_entry_guard below what we want, or it might
  2270. * be a long time til we get it. -RD */
  2271. r = add_an_entry_guard(NULL, 0);
  2272. if (r) {
  2273. smartlist_add(live_entry_guards, r);
  2274. entry_guards_changed();
  2275. }
  2276. }
  2277. if (!r && need_uptime) {
  2278. need_uptime = 0; /* try without that requirement */
  2279. goto retry;
  2280. }
  2281. if (!r && need_capacity) {
  2282. /* still no? last attempt, try without requiring capacity */
  2283. need_capacity = 0;
  2284. goto retry;
  2285. }
  2286. if (!r && !entry_list_can_grow(options) && consider_exit_family) {
  2287. /* still no? if we're using bridges or have strictentrynodes
  2288. * set, and our chosen exit is in the same family as all our
  2289. * bridges/entry guards, then be flexible about families. */
  2290. consider_exit_family = 0;
  2291. goto retry;
  2292. }
  2293. /* live_entry_guards may be empty below. Oh well, we tried. */
  2294. }
  2295. choose_and_finish:
  2296. r = smartlist_choose(live_entry_guards);
  2297. smartlist_free(live_entry_guards);
  2298. smartlist_free(exit_family);
  2299. return r;
  2300. }
  2301. /** Helper: Return the start of the month containing <b>time</b>. */
  2302. static time_t
  2303. start_of_month(time_t now)
  2304. {
  2305. struct tm tm;
  2306. tor_gmtime_r(&now, &tm);
  2307. tm.tm_sec = 0;
  2308. tm.tm_min = 0;
  2309. tm.tm_hour = 0;
  2310. tm.tm_mday = 1;
  2311. return tor_timegm(&tm);
  2312. }
  2313. /** Parse <b>state</b> and learn about the entry guards it describes.
  2314. * If <b>set</b> is true, and there are no errors, replace the global
  2315. * entry_list with what we find.
  2316. * On success, return 0. On failure, alloc into *<b>msg</b> a string
  2317. * describing the error, and return -1.
  2318. */
  2319. int
  2320. entry_guards_parse_state(or_state_t *state, int set, char **msg)
  2321. {
  2322. entry_guard_t *node = NULL;
  2323. smartlist_t *new_entry_guards = smartlist_create();
  2324. config_line_t *line;
  2325. time_t now = time(NULL);
  2326. const char *state_version = state->TorVersion;
  2327. digestmap_t *added_by = digestmap_new();
  2328. *msg = NULL;
  2329. for (line = state->EntryGuards; line; line = line->next) {
  2330. if (!strcasecmp(line->key, "EntryGuard")) {
  2331. smartlist_t *args = smartlist_create();
  2332. node = tor_malloc_zero(sizeof(entry_guard_t));
  2333. /* all entry guards on disk have been contacted */
  2334. node->made_contact = 1;
  2335. smartlist_add(new_entry_guards, node);
  2336. smartlist_split_string(args, line->value, " ",
  2337. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2338. if (smartlist_len(args)<2) {
  2339. *msg = tor_strdup("Unable to parse entry nodes: "
  2340. "Too few arguments to EntryGuard");
  2341. } else if (!is_legal_nickname(smartlist_get(args,0))) {
  2342. *msg = tor_strdup("Unable to parse entry nodes: "
  2343. "Bad nickname for EntryGuard");
  2344. } else {
  2345. strlcpy(node->nickname, smartlist_get(args,0), MAX_NICKNAME_LEN+1);
  2346. if (base16_decode(node->identity, DIGEST_LEN, smartlist_get(args,1),
  2347. strlen(smartlist_get(args,1)))<0) {
  2348. *msg = tor_strdup("Unable to parse entry nodes: "
  2349. "Bad hex digest for EntryGuard");
  2350. }
  2351. }
  2352. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  2353. smartlist_free(args);
  2354. if (*msg)
  2355. break;
  2356. } else if (!strcasecmp(line->key, "EntryGuardDownSince") ||
  2357. !strcasecmp(line->key, "EntryGuardUnlistedSince")) {
  2358. time_t when;
  2359. time_t last_try = 0;
  2360. if (!node) {
  2361. *msg = tor_strdup("Unable to parse entry nodes: "
  2362. "EntryGuardDownSince/UnlistedSince without EntryGuard");
  2363. break;
  2364. }
  2365. if (parse_iso_time(line->value, &when)<0) {
  2366. *msg = tor_strdup("Unable to parse entry nodes: "
  2367. "Bad time in EntryGuardDownSince/UnlistedSince");
  2368. break;
  2369. }
  2370. if (when > now) {
  2371. /* It's a bad idea to believe info in the future: you can wind
  2372. * up with timeouts that aren't allowed to happen for years. */
  2373. continue;
  2374. }
  2375. if (strlen(line->value) >= ISO_TIME_LEN+ISO_TIME_LEN+1) {
  2376. /* ignore failure */
  2377. (void) parse_iso_time(line->value+ISO_TIME_LEN+1, &last_try);
  2378. }
  2379. if (!strcasecmp(line->key, "EntryGuardDownSince")) {
  2380. node->unreachable_since = when;
  2381. node->last_attempted = last_try;
  2382. } else {
  2383. node->bad_since = when;
  2384. }
  2385. } else if (!strcasecmp(line->key, "EntryGuardAddedBy")) {
  2386. char d[DIGEST_LEN];
  2387. /* format is digest version date */
  2388. if (strlen(line->value) < HEX_DIGEST_LEN+1+1+1+ISO_TIME_LEN) {
  2389. log_warn(LD_BUG, "EntryGuardAddedBy line is not long enough.");
  2390. continue;
  2391. }
  2392. if (base16_decode(d, sizeof(d), line->value, HEX_DIGEST_LEN)<0 ||
  2393. line->value[HEX_DIGEST_LEN] != ' ') {
  2394. log_warn(LD_BUG, "EntryGuardAddedBy line %s does not begin with "
  2395. "hex digest", escaped(line->value));
  2396. continue;
  2397. }
  2398. digestmap_set(added_by, d, tor_strdup(line->value+HEX_DIGEST_LEN+1));
  2399. } else {
  2400. log_warn(LD_BUG, "Unexpected key %s", line->key);
  2401. }
  2402. }
  2403. SMARTLIST_FOREACH(new_entry_guards, entry_guard_t *, e,
  2404. {
  2405. char *sp;
  2406. char *val = digestmap_get(added_by, e->identity);
  2407. if (val && (sp = strchr(val, ' '))) {
  2408. time_t when;
  2409. *sp++ = '\0';
  2410. if (parse_iso_time(sp, &when)<0) {
  2411. log_warn(LD_BUG, "Can't read time %s in EntryGuardAddedBy", sp);
  2412. } else {
  2413. e->chosen_by_version = tor_strdup(val);
  2414. e->chosen_on_date = when;
  2415. }
  2416. } else {
  2417. if (state_version) {
  2418. e->chosen_by_version = tor_strdup(state_version);
  2419. e->chosen_on_date = start_of_month(time(NULL));
  2420. }
  2421. }
  2422. });
  2423. if (*msg || !set) {
  2424. SMARTLIST_FOREACH(new_entry_guards, entry_guard_t *, e,
  2425. entry_guard_free(e));
  2426. smartlist_free(new_entry_guards);
  2427. } else { /* !*err && set */
  2428. if (entry_guards) {
  2429. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  2430. entry_guard_free(e));
  2431. smartlist_free(entry_guards);
  2432. }
  2433. entry_guards = new_entry_guards;
  2434. entry_guards_dirty = 0;
  2435. if (remove_obsolete_entry_guards())
  2436. entry_guards_dirty = 1;
  2437. }
  2438. digestmap_free(added_by, _tor_free);
  2439. return *msg ? -1 : 0;
  2440. }
  2441. /** Our list of entry guards has changed, or some element of one
  2442. * of our entry guards has changed. Write the changes to disk within
  2443. * the next few minutes.
  2444. */
  2445. static void
  2446. entry_guards_changed(void)
  2447. {
  2448. time_t when;
  2449. entry_guards_dirty = 1;
  2450. /* or_state_save() will call entry_guards_update_state(). */
  2451. when = get_options()->AvoidDiskWrites ? time(NULL) + 3600 : time(NULL)+600;
  2452. or_state_mark_dirty(get_or_state(), when);
  2453. }
  2454. /** If the entry guard info has not changed, do nothing and return.
  2455. * Otherwise, free the EntryGuards piece of <b>state</b> and create
  2456. * a new one out of the global entry_guards list, and then mark
  2457. * <b>state</b> dirty so it will get saved to disk.
  2458. */
  2459. void
  2460. entry_guards_update_state(or_state_t *state)
  2461. {
  2462. config_line_t **next, *line;
  2463. if (! entry_guards_dirty)
  2464. return;
  2465. config_free_lines(state->EntryGuards);
  2466. next = &state->EntryGuards;
  2467. *next = NULL;
  2468. if (!entry_guards)
  2469. entry_guards = smartlist_create();
  2470. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  2471. {
  2472. char dbuf[HEX_DIGEST_LEN+1];
  2473. if (!e->made_contact)
  2474. continue; /* don't write this one to disk */
  2475. *next = line = tor_malloc_zero(sizeof(config_line_t));
  2476. line->key = tor_strdup("EntryGuard");
  2477. line->value = tor_malloc(HEX_DIGEST_LEN+MAX_NICKNAME_LEN+2);
  2478. base16_encode(dbuf, sizeof(dbuf), e->identity, DIGEST_LEN);
  2479. tor_snprintf(line->value,HEX_DIGEST_LEN+MAX_NICKNAME_LEN+2,
  2480. "%s %s", e->nickname, dbuf);
  2481. next = &(line->next);
  2482. if (e->unreachable_since) {
  2483. *next = line = tor_malloc_zero(sizeof(config_line_t));
  2484. line->key = tor_strdup("EntryGuardDownSince");
  2485. line->value = tor_malloc(ISO_TIME_LEN+1+ISO_TIME_LEN+1);
  2486. format_iso_time(line->value, e->unreachable_since);
  2487. if (e->last_attempted) {
  2488. line->value[ISO_TIME_LEN] = ' ';
  2489. format_iso_time(line->value+ISO_TIME_LEN+1, e->last_attempted);
  2490. }
  2491. next = &(line->next);
  2492. }
  2493. if (e->bad_since) {
  2494. *next = line = tor_malloc_zero(sizeof(config_line_t));
  2495. line->key = tor_strdup("EntryGuardUnlistedSince");
  2496. line->value = tor_malloc(ISO_TIME_LEN+1);
  2497. format_iso_time(line->value, e->bad_since);
  2498. next = &(line->next);
  2499. }
  2500. if (e->chosen_on_date && e->chosen_by_version &&
  2501. !strchr(e->chosen_by_version, ' ')) {
  2502. char d[HEX_DIGEST_LEN+1];
  2503. char t[ISO_TIME_LEN+1];
  2504. size_t val_len;
  2505. *next = line = tor_malloc_zero(sizeof(config_line_t));
  2506. line->key = tor_strdup("EntryGuardAddedBy");
  2507. val_len = (HEX_DIGEST_LEN+1+strlen(e->chosen_by_version)
  2508. +1+ISO_TIME_LEN+1);
  2509. line->value = tor_malloc(val_len);
  2510. base16_encode(d, sizeof(d), e->identity, DIGEST_LEN);
  2511. format_iso_time(t, e->chosen_on_date);
  2512. tor_snprintf(line->value, val_len, "%s %s %s",
  2513. d, e->chosen_by_version, t);
  2514. next = &(line->next);
  2515. }
  2516. });
  2517. if (!get_options()->AvoidDiskWrites)
  2518. or_state_mark_dirty(get_or_state(), 0);
  2519. entry_guards_dirty = 0;
  2520. }
  2521. /** If <b>question</b> is the string "entry-guards", then dump
  2522. * to *<b>answer</b> a newly allocated string describing all of
  2523. * the nodes in the global entry_guards list. See control-spec.txt
  2524. * for details.
  2525. * For backward compatibility, we also handle the string "helper-nodes".
  2526. * */
  2527. int
  2528. getinfo_helper_entry_guards(control_connection_t *conn,
  2529. const char *question, char **answer)
  2530. {
  2531. int use_long_names = conn->use_long_names;
  2532. if (!strcmp(question,"entry-guards") ||
  2533. !strcmp(question,"helper-nodes")) {
  2534. smartlist_t *sl = smartlist_create();
  2535. char tbuf[ISO_TIME_LEN+1];
  2536. char nbuf[MAX_VERBOSE_NICKNAME_LEN+1];
  2537. if (!entry_guards)
  2538. entry_guards = smartlist_create();
  2539. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  2540. {
  2541. size_t len = MAX_VERBOSE_NICKNAME_LEN+ISO_TIME_LEN+32;
  2542. char *c = tor_malloc(len);
  2543. const char *status = NULL;
  2544. time_t when = 0;
  2545. if (!e->made_contact) {
  2546. status = "never-connected";
  2547. } else if (e->bad_since) {
  2548. when = e->bad_since;
  2549. status = "unusable";
  2550. } else {
  2551. status = "up";
  2552. }
  2553. if (use_long_names) {
  2554. routerinfo_t *ri = router_get_by_digest(e->identity);
  2555. if (ri) {
  2556. router_get_verbose_nickname(nbuf, ri);
  2557. } else {
  2558. nbuf[0] = '$';
  2559. base16_encode(nbuf+1, sizeof(nbuf)-1, e->identity, DIGEST_LEN);
  2560. /* e->nickname field is not very reliable if we don't know about
  2561. * this router any longer; don't include it. */
  2562. }
  2563. } else {
  2564. base16_encode(nbuf, sizeof(nbuf), e->identity, DIGEST_LEN);
  2565. }
  2566. if (when) {
  2567. format_iso_time(tbuf, when);
  2568. tor_snprintf(c, len, "%s %s %s\n", nbuf, status, tbuf);
  2569. } else {
  2570. tor_snprintf(c, len, "%s %s\n", nbuf, status);
  2571. }
  2572. smartlist_add(sl, c);
  2573. });
  2574. *answer = smartlist_join_strings(sl, "", 0, NULL);
  2575. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  2576. smartlist_free(sl);
  2577. }
  2578. return 0;
  2579. }
  2580. /** DOCDOC */
  2581. typedef struct {
  2582. uint32_t addr;
  2583. uint16_t port;
  2584. char identity[DIGEST_LEN];
  2585. download_status_t fetch_status;
  2586. } bridge_info_t;
  2587. /** A list of known bridges. */
  2588. static smartlist_t *bridge_list = NULL;
  2589. /** Initialize the bridge list to empty, creating it if needed. */
  2590. void
  2591. clear_bridge_list(void)
  2592. {
  2593. if (!bridge_list)
  2594. bridge_list = smartlist_create();
  2595. SMARTLIST_FOREACH(bridge_list, bridge_info_t *, b, tor_free(b));
  2596. smartlist_clear(bridge_list);
  2597. }
  2598. /** Return a bridge pointer if <b>ri</b> is one of our known bridges
  2599. * (either by comparing keys if possible, else by comparing addr/port).
  2600. * Else return NULL. */
  2601. static bridge_info_t *
  2602. routerinfo_get_configured_bridge(routerinfo_t *ri)
  2603. {
  2604. if (!bridge_list)
  2605. return NULL;
  2606. SMARTLIST_FOREACH(bridge_list, bridge_info_t *, bridge,
  2607. {
  2608. if (tor_digest_is_zero(bridge->identity) &&
  2609. bridge->addr == ri->addr && bridge->port == ri->or_port)
  2610. return bridge;
  2611. if (!memcmp(bridge->identity, ri->cache_info.identity_digest,
  2612. DIGEST_LEN))
  2613. return bridge;
  2614. });
  2615. return NULL;
  2616. }
  2617. /** Return 1 if <b>ri</b> is one of our known bridges, else 0. */
  2618. int
  2619. routerinfo_is_a_configured_bridge(routerinfo_t *ri)
  2620. {
  2621. return routerinfo_get_configured_bridge(ri) ? 1 : 0;
  2622. }
  2623. /** Remember a new bridge at <b>addr</b>:<b>port</b>. If <b>digest</b>
  2624. * is set, it tells us the identity key too. */
  2625. void
  2626. bridge_add_from_config(uint32_t addr, uint16_t port, char *digest)
  2627. {
  2628. bridge_info_t *b = tor_malloc_zero(sizeof(bridge_info_t));
  2629. b->addr = addr;
  2630. b->port = port;
  2631. if (digest)
  2632. memcpy(b->identity, digest, DIGEST_LEN);
  2633. if (!bridge_list)
  2634. bridge_list = smartlist_create();
  2635. smartlist_add(bridge_list, b);
  2636. }
  2637. /** Schedule the next fetch for <b>bridge</b>, based on
  2638. * some retry schedule. */
  2639. static void
  2640. bridge_fetch_status_increment(bridge_info_t *bridge, time_t now)
  2641. {
  2642. switch (bridge->fetch_status.n_download_failures) {
  2643. case 0: bridge->fetch_status.next_attempt_at = now+60*15; break;
  2644. case 1: bridge->fetch_status.next_attempt_at = now+60*15; break;
  2645. default: bridge->fetch_status.next_attempt_at = now+60*60; break;
  2646. }
  2647. if (bridge->fetch_status.n_download_failures < 10)
  2648. bridge->fetch_status.n_download_failures++;
  2649. }
  2650. /** We just got a new descriptor for <b>bridge</b>. Reschedule the
  2651. * next fetch for a long time from <b>now</b>. */
  2652. static void
  2653. bridge_fetch_status_arrived(bridge_info_t *bridge, time_t now)
  2654. {
  2655. tor_assert(bridge);
  2656. bridge->fetch_status.next_attempt_at = now+60*60;
  2657. bridge->fetch_status.n_download_failures = 0;
  2658. }
  2659. /** If <b>digest</b> is one of our known bridges, return it. */
  2660. static bridge_info_t *
  2661. find_bridge_by_digest(char *digest)
  2662. {
  2663. SMARTLIST_FOREACH(bridge_list, bridge_info_t *, bridge,
  2664. {
  2665. if (!memcmp(bridge->identity, digest, DIGEST_LEN))
  2666. return bridge;
  2667. });
  2668. return NULL;
  2669. }
  2670. /** We need to ask <b>bridge</b> for its server descriptor. <b>address</b>
  2671. * is a helpful string describing this bridge. */
  2672. static void
  2673. launch_direct_bridge_descriptor_fetch(char *address, bridge_info_t *bridge)
  2674. {
  2675. if (connection_get_by_type_addr_port_purpose(
  2676. CONN_TYPE_DIR, bridge->addr, bridge->port,
  2677. DIR_PURPOSE_FETCH_SERVERDESC))
  2678. return; /* it's already on the way */
  2679. directory_initiate_command(address, bridge->addr,
  2680. bridge->port, 0,
  2681. 1, bridge->identity,
  2682. DIR_PURPOSE_FETCH_SERVERDESC,
  2683. ROUTER_PURPOSE_BRIDGE,
  2684. 0, "authority.z", NULL, 0, 0);
  2685. }
  2686. /** Fetching the bridge descriptor from the bridge authority returned a
  2687. * "not found". Fall back to trying a direct fetch. */
  2688. void
  2689. retry_bridge_descriptor_fetch_directly(char *digest)
  2690. {
  2691. bridge_info_t *bridge = find_bridge_by_digest(digest);
  2692. char address_buf[INET_NTOA_BUF_LEN+1];
  2693. struct in_addr in;
  2694. if (!bridge)
  2695. return; /* not found? oh well. */
  2696. in.s_addr = htonl(bridge->addr);
  2697. tor_inet_ntoa(&in, address_buf, sizeof(address_buf));
  2698. launch_direct_bridge_descriptor_fetch(address_buf, bridge);
  2699. }
  2700. /** For each bridge in our list for which we don't currently have a
  2701. * descriptor, fetch a new copy of its descriptor -- either directly
  2702. * from the bridge or via a bridge authority. */
  2703. void
  2704. fetch_bridge_descriptors(time_t now)
  2705. {
  2706. char address_buf[INET_NTOA_BUF_LEN+1];
  2707. struct in_addr in;
  2708. or_options_t *options = get_options();
  2709. int num_bridge_auths = get_n_authorities(BRIDGE_AUTHORITY);
  2710. int ask_bridge_directly;
  2711. int can_use_bridge_authority;
  2712. if (!bridge_list)
  2713. return;
  2714. SMARTLIST_FOREACH(bridge_list, bridge_info_t *, bridge,
  2715. {
  2716. if (bridge->fetch_status.next_attempt_at > now)
  2717. continue; /* don't bother, no need to retry yet */
  2718. /* schedule another fetch as if this one will fail, in case it does */
  2719. bridge_fetch_status_increment(bridge, now);
  2720. in.s_addr = htonl(bridge->addr);
  2721. tor_inet_ntoa(&in, address_buf, sizeof(address_buf));
  2722. can_use_bridge_authority = !tor_digest_is_zero(bridge->identity) &&
  2723. num_bridge_auths;
  2724. ask_bridge_directly = !can_use_bridge_authority ||
  2725. !options->UpdateBridgesFromAuthority;
  2726. log_debug(LD_DIR, "ask_bridge_directly=%d (%d, %d, %d)",
  2727. ask_bridge_directly, tor_digest_is_zero(bridge->identity),
  2728. !options->UpdateBridgesFromAuthority, !num_bridge_auths);
  2729. if (ask_bridge_directly &&
  2730. !fascist_firewall_allows_address_or(bridge->addr, bridge->port)) {
  2731. log_notice(LD_DIR, "Bridge at '%s:%d' isn't reachable by our "
  2732. "firewall policy. %s.", address_buf, bridge->port,
  2733. can_use_bridge_authority ?
  2734. "Asking bridge authority instead" : "Skipping");
  2735. if (can_use_bridge_authority)
  2736. ask_bridge_directly = 0;
  2737. else
  2738. continue;
  2739. }
  2740. if (ask_bridge_directly) {
  2741. /* we need to ask the bridge itself for its descriptor. */
  2742. launch_direct_bridge_descriptor_fetch(address_buf, bridge);
  2743. } else {
  2744. /* We have a digest and we want to ask an authority. We could
  2745. * combine all the requests into one, but that may give more
  2746. * hints to the bridge authority than we want to give. */
  2747. char resource[10 + HEX_DIGEST_LEN];
  2748. memcpy(resource, "fp/", 3);
  2749. base16_encode(resource+3, HEX_DIGEST_LEN+1,
  2750. bridge->identity, DIGEST_LEN);
  2751. memcpy(resource+3+HEX_DIGEST_LEN, ".z", 3);
  2752. log_info(LD_DIR, "Fetching bridge info '%s' from bridge authority.",
  2753. resource);
  2754. directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,
  2755. ROUTER_PURPOSE_BRIDGE, resource, 0);
  2756. }
  2757. });
  2758. }
  2759. /** We just learned a descriptor for a bridge. See if that
  2760. * digest is in our entry guard list, and add it if not. */
  2761. void
  2762. learned_bridge_descriptor(routerinfo_t *ri, int from_cache)
  2763. {
  2764. tor_assert(ri);
  2765. tor_assert(ri->purpose == ROUTER_PURPOSE_BRIDGE);
  2766. if (get_options()->UseBridges) {
  2767. int first = !any_bridge_descriptors_known();
  2768. bridge_info_t *bridge = routerinfo_get_configured_bridge(ri);
  2769. time_t now = time(NULL);
  2770. ri->is_running = 1;
  2771. if (bridge) { /* if we actually want to use this one */
  2772. /* it's here; schedule its re-fetch for a long time from now. */
  2773. if (!from_cache)
  2774. bridge_fetch_status_arrived(bridge, now);
  2775. add_an_entry_guard(ri, 1);
  2776. log_notice(LD_DIR, "new bridge descriptor '%s' (%s)", ri->nickname,
  2777. from_cache ? "cached" : "fresh");
  2778. if (first)
  2779. routerlist_retry_directory_downloads(now);
  2780. }
  2781. }
  2782. }
  2783. /** Return 1 if any of our entry guards have descriptors that
  2784. * are marked with purpose 'bridge' and are running. Else return 0.
  2785. *
  2786. * We use this function to decide if we're ready to start building
  2787. * circuits through our bridges, or if we need to wait until the
  2788. * directory "server/authority" requests finish. */
  2789. int
  2790. any_bridge_descriptors_known(void)
  2791. {
  2792. tor_assert(get_options()->UseBridges);
  2793. return choose_random_entry(NULL)!=NULL ? 1 : 0;
  2794. }
  2795. /** Return 1 if we have at least one descriptor for a bridge and
  2796. * all descriptors we know are down. Else return 0. If <b>act</b> is
  2797. * 1, then mark the down bridges up; else just observe and report. */
  2798. static int
  2799. bridges_retry_helper(int act)
  2800. {
  2801. routerinfo_t *ri;
  2802. int any_known = 0;
  2803. int any_running = 0;
  2804. if (!entry_guards)
  2805. entry_guards = smartlist_create();
  2806. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  2807. {
  2808. ri = router_get_by_digest(e->identity);
  2809. if (ri && ri->purpose == ROUTER_PURPOSE_BRIDGE) {
  2810. any_known = 1;
  2811. if (ri->is_running)
  2812. any_running = 1; /* some bridge is both known and running */
  2813. else if (act) { /* mark it for retry */
  2814. ri->is_running = 1;
  2815. e->can_retry = 1;
  2816. e->bad_since = 0;
  2817. }
  2818. }
  2819. });
  2820. return any_known && !any_running;
  2821. }
  2822. /** Do we know any descriptors for our bridges, and are they all
  2823. * down? */
  2824. int
  2825. bridges_known_but_down(void)
  2826. {
  2827. return bridges_retry_helper(0);
  2828. }
  2829. /** Mark all down known bridges up. */
  2830. void
  2831. bridges_retry_all(void)
  2832. {
  2833. bridges_retry_helper(1);
  2834. }
  2835. /** Release all storage held by the list of entry guards and related
  2836. * memory structs. */
  2837. void
  2838. entry_guards_free_all(void)
  2839. {
  2840. if (entry_guards) {
  2841. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
  2842. entry_guard_free(e));
  2843. smartlist_free(entry_guards);
  2844. entry_guards = NULL;
  2845. }
  2846. clear_bridge_list();
  2847. smartlist_free(bridge_list);
  2848. bridge_list = NULL;
  2849. }