circuitbuild.c 93 KB

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