circuitbuild.c 107 KB

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