circuitbuild.c 92 KB

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