circuitbuild.c 64 KB

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