circuitbuild.c 86 KB

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