circuitbuild.c 104 KB

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