circuitbuild.c 103 KB

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