circuitbuild.c 84 KB

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