circuitbuild.c 104 KB

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