circuitbuild.c 78 KB

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