circuitbuild.c 67 KB

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