circuitbuild.c 66 KB

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