circuitbuild.c 78 KB

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