circuitbuild.c 65 KB

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