circuitbuild.c 105 KB

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