circuitlist.c 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894
  1. /* Copyright 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2013, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file circuitlist.c
  8. * \brief Manage the global circuit list.
  9. **/
  10. #include "or.h"
  11. #include "channel.h"
  12. #include "circuitbuild.h"
  13. #include "circuitlist.h"
  14. #include "circuituse.h"
  15. #include "circuitstats.h"
  16. #include "connection.h"
  17. #include "config.h"
  18. #include "connection_edge.h"
  19. #include "connection_or.h"
  20. #include "control.h"
  21. #include "networkstatus.h"
  22. #include "nodelist.h"
  23. #include "onion.h"
  24. #include "onion_fast.h"
  25. #include "policies.h"
  26. #include "relay.h"
  27. #include "rendclient.h"
  28. #include "rendcommon.h"
  29. #include "rephist.h"
  30. #include "routerlist.h"
  31. #include "routerset.h"
  32. #include "ht.h"
  33. /********* START VARIABLES **********/
  34. /** A global list of all circuits at this hop. */
  35. circuit_t *global_circuitlist=NULL;
  36. /** A list of all the circuits in CIRCUIT_STATE_CHAN_WAIT. */
  37. static smartlist_t *circuits_pending_chans = NULL;
  38. static void circuit_free(circuit_t *circ);
  39. static void circuit_free_cpath(crypt_path_t *cpath);
  40. static void circuit_free_cpath_node(crypt_path_t *victim);
  41. static void cpath_ref_decref(crypt_path_reference_t *cpath_ref);
  42. //static void circuit_set_rend_token(or_circuit_t *circ, int is_rend_circ,
  43. // const uint8_t *token);
  44. static void circuit_clear_rend_token(or_circuit_t *circ);
  45. /********* END VARIABLES ************/
  46. /** A map from channel and circuit ID to circuit. (Lookup performance is
  47. * very important here, since we need to do it every time a cell arrives.) */
  48. typedef struct chan_circid_circuit_map_t {
  49. HT_ENTRY(chan_circid_circuit_map_t) node;
  50. channel_t *chan;
  51. circid_t circ_id;
  52. circuit_t *circuit;
  53. } chan_circid_circuit_map_t;
  54. /** Helper for hash tables: compare the channel and circuit ID for a and
  55. * b, and return less than, equal to, or greater than zero appropriately.
  56. */
  57. static INLINE int
  58. chan_circid_entries_eq_(chan_circid_circuit_map_t *a,
  59. chan_circid_circuit_map_t *b)
  60. {
  61. return a->chan == b->chan && a->circ_id == b->circ_id;
  62. }
  63. /** Helper: return a hash based on circuit ID and the pointer value of
  64. * chan in <b>a</b>. */
  65. static INLINE unsigned int
  66. chan_circid_entry_hash_(chan_circid_circuit_map_t *a)
  67. {
  68. return ((unsigned)a->circ_id) ^ (unsigned)(uintptr_t)(a->chan);
  69. }
  70. /** Map from [chan,circid] to circuit. */
  71. static HT_HEAD(chan_circid_map, chan_circid_circuit_map_t)
  72. chan_circid_map = HT_INITIALIZER();
  73. HT_PROTOTYPE(chan_circid_map, chan_circid_circuit_map_t, node,
  74. chan_circid_entry_hash_, chan_circid_entries_eq_)
  75. HT_GENERATE(chan_circid_map, chan_circid_circuit_map_t, node,
  76. chan_circid_entry_hash_, chan_circid_entries_eq_, 0.6,
  77. malloc, realloc, free)
  78. /** The most recently returned entry from circuit_get_by_circid_chan;
  79. * used to improve performance when many cells arrive in a row from the
  80. * same circuit.
  81. */
  82. chan_circid_circuit_map_t *_last_circid_chan_ent = NULL;
  83. /** Implementation helper for circuit_set_{p,n}_circid_channel: A circuit ID
  84. * and/or channel for circ has just changed from <b>old_chan, old_id</b>
  85. * to <b>chan, id</b>. Adjust the chan,circid map as appropriate, removing
  86. * the old entry (if any) and adding a new one. */
  87. static void
  88. circuit_set_circid_chan_helper(circuit_t *circ, int direction,
  89. circid_t id,
  90. channel_t *chan)
  91. {
  92. chan_circid_circuit_map_t search;
  93. chan_circid_circuit_map_t *found;
  94. channel_t *old_chan, **chan_ptr;
  95. circid_t old_id, *circid_ptr;
  96. int make_active, attached = 0;
  97. if (direction == CELL_DIRECTION_OUT) {
  98. chan_ptr = &circ->n_chan;
  99. circid_ptr = &circ->n_circ_id;
  100. make_active = circ->n_chan_cells.n > 0;
  101. } else {
  102. or_circuit_t *c = TO_OR_CIRCUIT(circ);
  103. chan_ptr = &c->p_chan;
  104. circid_ptr = &c->p_circ_id;
  105. make_active = c->p_chan_cells.n > 0;
  106. }
  107. old_chan = *chan_ptr;
  108. old_id = *circid_ptr;
  109. if (id == old_id && chan == old_chan)
  110. return;
  111. if (_last_circid_chan_ent &&
  112. ((old_id == _last_circid_chan_ent->circ_id &&
  113. old_chan == _last_circid_chan_ent->chan) ||
  114. (id == _last_circid_chan_ent->circ_id &&
  115. chan == _last_circid_chan_ent->chan))) {
  116. _last_circid_chan_ent = NULL;
  117. }
  118. if (old_chan) {
  119. /*
  120. * If we're changing channels or ID and had an old channel and a non
  121. * zero old ID and weren't marked for close (i.e., we should have been
  122. * attached), detach the circuit. ID changes require this because
  123. * circuitmux hashes on (channel_id, circuit_id).
  124. */
  125. if (old_id != 0 && (old_chan != chan || old_id != id) &&
  126. !(circ->marked_for_close)) {
  127. tor_assert(old_chan->cmux);
  128. circuitmux_detach_circuit(old_chan->cmux, circ);
  129. }
  130. /* we may need to remove it from the conn-circid map */
  131. search.circ_id = old_id;
  132. search.chan = old_chan;
  133. found = HT_REMOVE(chan_circid_map, &chan_circid_map, &search);
  134. if (found) {
  135. tor_free(found);
  136. if (direction == CELL_DIRECTION_OUT) {
  137. /* One fewer circuits use old_chan as n_chan */
  138. --(old_chan->num_n_circuits);
  139. } else {
  140. /* One fewer circuits use old_chan as p_chan */
  141. --(old_chan->num_p_circuits);
  142. }
  143. }
  144. }
  145. /* Change the values only after we have possibly made the circuit inactive
  146. * on the previous chan. */
  147. *chan_ptr = chan;
  148. *circid_ptr = id;
  149. if (chan == NULL)
  150. return;
  151. /* now add the new one to the conn-circid map */
  152. search.circ_id = id;
  153. search.chan = chan;
  154. found = HT_FIND(chan_circid_map, &chan_circid_map, &search);
  155. if (found) {
  156. found->circuit = circ;
  157. } else {
  158. found = tor_malloc_zero(sizeof(chan_circid_circuit_map_t));
  159. found->circ_id = id;
  160. found->chan = chan;
  161. found->circuit = circ;
  162. HT_INSERT(chan_circid_map, &chan_circid_map, found);
  163. }
  164. /*
  165. * Attach to the circuitmux if we're changing channels or IDs and
  166. * have a new channel and ID to use and the circuit is not marked for
  167. * close.
  168. */
  169. if (chan && id != 0 && (old_chan != chan || old_id != id) &&
  170. !(circ->marked_for_close)) {
  171. tor_assert(chan->cmux);
  172. circuitmux_attach_circuit(chan->cmux, circ, direction);
  173. attached = 1;
  174. }
  175. /*
  176. * This is a no-op if we have no cells, but if we do it marks us active to
  177. * the circuitmux
  178. */
  179. if (make_active && attached)
  180. update_circuit_on_cmux(circ, direction);
  181. /* Adjust circuit counts on new channel */
  182. if (direction == CELL_DIRECTION_OUT) {
  183. ++chan->num_n_circuits;
  184. } else {
  185. ++chan->num_p_circuits;
  186. }
  187. }
  188. /** Set the p_conn field of a circuit <b>circ</b>, along
  189. * with the corresponding circuit ID, and add the circuit as appropriate
  190. * to the (chan,id)-\>circuit map. */
  191. void
  192. circuit_set_p_circid_chan(or_circuit_t *circ, circid_t id,
  193. channel_t *chan)
  194. {
  195. circuit_set_circid_chan_helper(TO_CIRCUIT(circ), CELL_DIRECTION_IN,
  196. id, chan);
  197. if (chan)
  198. tor_assert(bool_eq(circ->p_chan_cells.n, circ->next_active_on_p_chan));
  199. }
  200. /** Set the n_conn field of a circuit <b>circ</b>, along
  201. * with the corresponding circuit ID, and add the circuit as appropriate
  202. * to the (chan,id)-\>circuit map. */
  203. void
  204. circuit_set_n_circid_chan(circuit_t *circ, circid_t id,
  205. channel_t *chan)
  206. {
  207. circuit_set_circid_chan_helper(circ, CELL_DIRECTION_OUT, id, chan);
  208. if (chan)
  209. tor_assert(bool_eq(circ->n_chan_cells.n, circ->next_active_on_n_chan));
  210. }
  211. /** Change the state of <b>circ</b> to <b>state</b>, adding it to or removing
  212. * it from lists as appropriate. */
  213. void
  214. circuit_set_state(circuit_t *circ, uint8_t state)
  215. {
  216. tor_assert(circ);
  217. if (state == circ->state)
  218. return;
  219. if (!circuits_pending_chans)
  220. circuits_pending_chans = smartlist_new();
  221. if (circ->state == CIRCUIT_STATE_CHAN_WAIT) {
  222. /* remove from waiting-circuit list. */
  223. smartlist_remove(circuits_pending_chans, circ);
  224. }
  225. if (state == CIRCUIT_STATE_CHAN_WAIT) {
  226. /* add to waiting-circuit list. */
  227. smartlist_add(circuits_pending_chans, circ);
  228. }
  229. if (state == CIRCUIT_STATE_OPEN)
  230. tor_assert(!circ->n_chan_create_cell);
  231. circ->state = state;
  232. }
  233. /** Add <b>circ</b> to the global list of circuits. This is called only from
  234. * within circuit_new.
  235. */
  236. static void
  237. circuit_add(circuit_t *circ)
  238. {
  239. if (!global_circuitlist) { /* first one */
  240. global_circuitlist = circ;
  241. circ->next = NULL;
  242. } else {
  243. circ->next = global_circuitlist;
  244. global_circuitlist = circ;
  245. }
  246. }
  247. /** Append to <b>out</b> all circuits in state CHAN_WAIT waiting for
  248. * the given connection. */
  249. void
  250. circuit_get_all_pending_on_channel(smartlist_t *out, channel_t *chan)
  251. {
  252. tor_assert(out);
  253. tor_assert(chan);
  254. if (!circuits_pending_chans)
  255. return;
  256. SMARTLIST_FOREACH_BEGIN(circuits_pending_chans, circuit_t *, circ) {
  257. if (circ->marked_for_close)
  258. continue;
  259. if (!circ->n_hop)
  260. continue;
  261. tor_assert(circ->state == CIRCUIT_STATE_CHAN_WAIT);
  262. if (tor_digest_is_zero(circ->n_hop->identity_digest)) {
  263. /* Look at addr/port. This is an unkeyed connection. */
  264. if (!channel_matches_extend_info(chan, circ->n_hop))
  265. continue;
  266. } else {
  267. /* We expected a key. See if it's the right one. */
  268. if (tor_memneq(chan->identity_digest,
  269. circ->n_hop->identity_digest, DIGEST_LEN))
  270. continue;
  271. }
  272. smartlist_add(out, circ);
  273. } SMARTLIST_FOREACH_END(circ);
  274. }
  275. /** Return the number of circuits in state CHAN_WAIT, waiting for the given
  276. * channel. */
  277. int
  278. circuit_count_pending_on_channel(channel_t *chan)
  279. {
  280. int cnt;
  281. smartlist_t *sl = smartlist_new();
  282. tor_assert(chan);
  283. circuit_get_all_pending_on_channel(sl, chan);
  284. cnt = smartlist_len(sl);
  285. smartlist_free(sl);
  286. log_debug(LD_CIRC,"or_conn to %s at %s, %d pending circs",
  287. chan->nickname ? chan->nickname : "NULL",
  288. channel_get_canonical_remote_descr(chan),
  289. cnt);
  290. return cnt;
  291. }
  292. /** Detach from the global circuit list, and deallocate, all
  293. * circuits that have been marked for close.
  294. */
  295. void
  296. circuit_close_all_marked(void)
  297. {
  298. circuit_t *tmp,*m;
  299. while (global_circuitlist && global_circuitlist->marked_for_close) {
  300. tmp = global_circuitlist->next;
  301. circuit_free(global_circuitlist);
  302. global_circuitlist = tmp;
  303. }
  304. tmp = global_circuitlist;
  305. while (tmp && tmp->next) {
  306. if (tmp->next->marked_for_close) {
  307. m = tmp->next->next;
  308. circuit_free(tmp->next);
  309. tmp->next = m;
  310. /* Need to check new tmp->next; don't advance tmp. */
  311. } else {
  312. /* Advance tmp. */
  313. tmp = tmp->next;
  314. }
  315. }
  316. }
  317. /** Return the head of the global linked list of circuits. */
  318. circuit_t *
  319. circuit_get_global_list_(void)
  320. {
  321. return global_circuitlist;
  322. }
  323. /** Function to make circ-\>state human-readable */
  324. const char *
  325. circuit_state_to_string(int state)
  326. {
  327. static char buf[64];
  328. switch (state) {
  329. case CIRCUIT_STATE_BUILDING: return "doing handshakes";
  330. case CIRCUIT_STATE_ONIONSKIN_PENDING: return "processing the onion";
  331. case CIRCUIT_STATE_CHAN_WAIT: return "connecting to server";
  332. case CIRCUIT_STATE_OPEN: return "open";
  333. default:
  334. log_warn(LD_BUG, "Unknown circuit state %d", state);
  335. tor_snprintf(buf, sizeof(buf), "unknown state [%d]", state);
  336. return buf;
  337. }
  338. }
  339. /** Map a circuit purpose to a string suitable to be displayed to a
  340. * controller. */
  341. const char *
  342. circuit_purpose_to_controller_string(uint8_t purpose)
  343. {
  344. static char buf[32];
  345. switch (purpose) {
  346. case CIRCUIT_PURPOSE_OR:
  347. case CIRCUIT_PURPOSE_INTRO_POINT:
  348. case CIRCUIT_PURPOSE_REND_POINT_WAITING:
  349. case CIRCUIT_PURPOSE_REND_ESTABLISHED:
  350. return "SERVER"; /* A controller should never see these, actually. */
  351. case CIRCUIT_PURPOSE_C_GENERAL:
  352. return "GENERAL";
  353. case CIRCUIT_PURPOSE_C_INTRODUCING:
  354. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  355. case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
  356. return "HS_CLIENT_INTRO";
  357. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  358. case CIRCUIT_PURPOSE_C_REND_READY:
  359. case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
  360. case CIRCUIT_PURPOSE_C_REND_JOINED:
  361. return "HS_CLIENT_REND";
  362. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  363. case CIRCUIT_PURPOSE_S_INTRO:
  364. return "HS_SERVICE_INTRO";
  365. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  366. case CIRCUIT_PURPOSE_S_REND_JOINED:
  367. return "HS_SERVICE_REND";
  368. case CIRCUIT_PURPOSE_TESTING:
  369. return "TESTING";
  370. case CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT:
  371. return "MEASURE_TIMEOUT";
  372. case CIRCUIT_PURPOSE_CONTROLLER:
  373. return "CONTROLLER";
  374. case CIRCUIT_PURPOSE_PATH_BIAS_TESTING:
  375. return "PATH_BIAS_TESTING";
  376. default:
  377. tor_snprintf(buf, sizeof(buf), "UNKNOWN_%d", (int)purpose);
  378. return buf;
  379. }
  380. }
  381. /** Return a string specifying the state of the hidden-service circuit
  382. * purpose <b>purpose</b>, or NULL if <b>purpose</b> is not a
  383. * hidden-service-related circuit purpose. */
  384. const char *
  385. circuit_purpose_to_controller_hs_state_string(uint8_t purpose)
  386. {
  387. switch (purpose)
  388. {
  389. default:
  390. log_fn(LOG_WARN, LD_BUG,
  391. "Unrecognized circuit purpose: %d",
  392. (int)purpose);
  393. tor_fragile_assert();
  394. /* fall through */
  395. case CIRCUIT_PURPOSE_OR:
  396. case CIRCUIT_PURPOSE_C_GENERAL:
  397. case CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT:
  398. case CIRCUIT_PURPOSE_TESTING:
  399. case CIRCUIT_PURPOSE_CONTROLLER:
  400. case CIRCUIT_PURPOSE_PATH_BIAS_TESTING:
  401. return NULL;
  402. case CIRCUIT_PURPOSE_INTRO_POINT:
  403. return "OR_HSSI_ESTABLISHED";
  404. case CIRCUIT_PURPOSE_REND_POINT_WAITING:
  405. return "OR_HSCR_ESTABLISHED";
  406. case CIRCUIT_PURPOSE_REND_ESTABLISHED:
  407. return "OR_HS_R_JOINED";
  408. case CIRCUIT_PURPOSE_C_INTRODUCING:
  409. return "HSCI_CONNECTING";
  410. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  411. return "HSCI_INTRO_SENT";
  412. case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
  413. return "HSCI_DONE";
  414. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  415. return "HSCR_CONNECTING";
  416. case CIRCUIT_PURPOSE_C_REND_READY:
  417. return "HSCR_ESTABLISHED_IDLE";
  418. case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
  419. return "HSCR_ESTABLISHED_WAITING";
  420. case CIRCUIT_PURPOSE_C_REND_JOINED:
  421. return "HSCR_JOINED";
  422. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  423. return "HSSI_CONNECTING";
  424. case CIRCUIT_PURPOSE_S_INTRO:
  425. return "HSSI_ESTABLISHED";
  426. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  427. return "HSSR_CONNECTING";
  428. case CIRCUIT_PURPOSE_S_REND_JOINED:
  429. return "HSSR_JOINED";
  430. }
  431. }
  432. /** Return a human-readable string for the circuit purpose <b>purpose</b>. */
  433. const char *
  434. circuit_purpose_to_string(uint8_t purpose)
  435. {
  436. static char buf[32];
  437. switch (purpose)
  438. {
  439. case CIRCUIT_PURPOSE_OR:
  440. return "Circuit at relay";
  441. case CIRCUIT_PURPOSE_INTRO_POINT:
  442. return "Acting as intro point";
  443. case CIRCUIT_PURPOSE_REND_POINT_WAITING:
  444. return "Acting as rendevous (pending)";
  445. case CIRCUIT_PURPOSE_REND_ESTABLISHED:
  446. return "Acting as rendevous (established)";
  447. case CIRCUIT_PURPOSE_C_GENERAL:
  448. return "General-purpose client";
  449. case CIRCUIT_PURPOSE_C_INTRODUCING:
  450. return "Hidden service client: Connecting to intro point";
  451. case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
  452. return "Hidden service client: Waiting for ack from intro point";
  453. case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
  454. return "Hidden service client: Received ack from intro point";
  455. case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
  456. return "Hidden service client: Establishing rendezvous point";
  457. case CIRCUIT_PURPOSE_C_REND_READY:
  458. return "Hidden service client: Pending rendezvous point";
  459. case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
  460. return "Hidden service client: Pending rendezvous point (ack received)";
  461. case CIRCUIT_PURPOSE_C_REND_JOINED:
  462. return "Hidden service client: Active rendezvous point";
  463. case CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT:
  464. return "Measuring circuit timeout";
  465. case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
  466. return "Hidden service: Establishing introduction point";
  467. case CIRCUIT_PURPOSE_S_INTRO:
  468. return "Hidden service: Introduction point";
  469. case CIRCUIT_PURPOSE_S_CONNECT_REND:
  470. return "Hidden service: Connecting to rendezvous point";
  471. case CIRCUIT_PURPOSE_S_REND_JOINED:
  472. return "Hidden service: Active rendezvous point";
  473. case CIRCUIT_PURPOSE_TESTING:
  474. return "Testing circuit";
  475. case CIRCUIT_PURPOSE_CONTROLLER:
  476. return "Circuit made by controller";
  477. case CIRCUIT_PURPOSE_PATH_BIAS_TESTING:
  478. return "Path-bias testing circuit";
  479. default:
  480. tor_snprintf(buf, sizeof(buf), "UNKNOWN_%d", (int)purpose);
  481. return buf;
  482. }
  483. }
  484. /** Pick a reasonable package_window to start out for our circuits.
  485. * Originally this was hard-coded at 1000, but now the consensus votes
  486. * on the answer. See proposal 168. */
  487. int32_t
  488. circuit_initial_package_window(void)
  489. {
  490. int32_t num = networkstatus_get_param(NULL, "circwindow", CIRCWINDOW_START,
  491. CIRCWINDOW_START_MIN,
  492. CIRCWINDOW_START_MAX);
  493. /* If the consensus tells us a negative number, we'd assert. */
  494. if (num < 0)
  495. num = CIRCWINDOW_START;
  496. return num;
  497. }
  498. /** Initialize the common elements in a circuit_t, and add it to the global
  499. * list. */
  500. static void
  501. init_circuit_base(circuit_t *circ)
  502. {
  503. tor_gettimeofday(&circ->timestamp_created);
  504. // Gets reset when we send CREATE_FAST.
  505. // circuit_expire_building() expects these to be equal
  506. // until the orconn is built.
  507. circ->timestamp_began = circ->timestamp_created;
  508. circ->package_window = circuit_initial_package_window();
  509. circ->deliver_window = CIRCWINDOW_START;
  510. circuit_add(circ);
  511. }
  512. /** Allocate space for a new circuit, initializing with <b>p_circ_id</b>
  513. * and <b>p_conn</b>. Add it to the global circuit list.
  514. */
  515. origin_circuit_t *
  516. origin_circuit_new(void)
  517. {
  518. origin_circuit_t *circ;
  519. /* never zero, since a global ID of 0 is treated specially by the
  520. * controller */
  521. static uint32_t n_circuits_allocated = 1;
  522. circ = tor_malloc_zero(sizeof(origin_circuit_t));
  523. circ->base_.magic = ORIGIN_CIRCUIT_MAGIC;
  524. circ->next_stream_id = crypto_rand_int(1<<16);
  525. circ->global_identifier = n_circuits_allocated++;
  526. circ->remaining_relay_early_cells = MAX_RELAY_EARLY_CELLS_PER_CIRCUIT;
  527. circ->remaining_relay_early_cells -= crypto_rand_int(2);
  528. init_circuit_base(TO_CIRCUIT(circ));
  529. circ_times.last_circ_at = approx_time();
  530. return circ;
  531. }
  532. /** Allocate a new or_circuit_t, connected to <b>p_conn</b> as
  533. * <b>p_circ_id</b>. If <b>p_conn</b> is NULL, the circuit is unattached. */
  534. or_circuit_t *
  535. or_circuit_new(circid_t p_circ_id, channel_t *p_chan)
  536. {
  537. /* CircIDs */
  538. or_circuit_t *circ;
  539. circ = tor_malloc_zero(sizeof(or_circuit_t));
  540. circ->base_.magic = OR_CIRCUIT_MAGIC;
  541. if (p_chan)
  542. circuit_set_p_circid_chan(circ, p_circ_id, p_chan);
  543. circ->remaining_relay_early_cells = MAX_RELAY_EARLY_CELLS_PER_CIRCUIT;
  544. init_circuit_base(TO_CIRCUIT(circ));
  545. return circ;
  546. }
  547. /** Deallocate space associated with circ.
  548. */
  549. static void
  550. circuit_free(circuit_t *circ)
  551. {
  552. void *mem;
  553. size_t memlen;
  554. if (!circ)
  555. return;
  556. if (CIRCUIT_IS_ORIGIN(circ)) {
  557. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  558. mem = ocirc;
  559. memlen = sizeof(origin_circuit_t);
  560. tor_assert(circ->magic == ORIGIN_CIRCUIT_MAGIC);
  561. if (ocirc->build_state) {
  562. extend_info_free(ocirc->build_state->chosen_exit);
  563. circuit_free_cpath_node(ocirc->build_state->pending_final_cpath);
  564. cpath_ref_decref(ocirc->build_state->service_pending_final_cpath_ref);
  565. }
  566. tor_free(ocirc->build_state);
  567. circuit_free_cpath(ocirc->cpath);
  568. crypto_pk_free(ocirc->intro_key);
  569. rend_data_free(ocirc->rend_data);
  570. tor_free(ocirc->dest_address);
  571. if (ocirc->socks_username) {
  572. memwipe(ocirc->socks_username, 0x12, ocirc->socks_username_len);
  573. tor_free(ocirc->socks_username);
  574. }
  575. if (ocirc->socks_password) {
  576. memwipe(ocirc->socks_password, 0x06, ocirc->socks_password_len);
  577. tor_free(ocirc->socks_password);
  578. }
  579. addr_policy_list_free(ocirc->prepend_policy);
  580. } else {
  581. or_circuit_t *ocirc = TO_OR_CIRCUIT(circ);
  582. /* Remember cell statistics for this circuit before deallocating. */
  583. if (get_options()->CellStatistics)
  584. rep_hist_buffer_stats_add_circ(circ, time(NULL));
  585. mem = ocirc;
  586. memlen = sizeof(or_circuit_t);
  587. tor_assert(circ->magic == OR_CIRCUIT_MAGIC);
  588. crypto_cipher_free(ocirc->p_crypto);
  589. crypto_digest_free(ocirc->p_digest);
  590. crypto_cipher_free(ocirc->n_crypto);
  591. crypto_digest_free(ocirc->n_digest);
  592. circuit_clear_rend_token(ocirc);
  593. if (ocirc->rend_splice) {
  594. or_circuit_t *other = ocirc->rend_splice;
  595. tor_assert(other->base_.magic == OR_CIRCUIT_MAGIC);
  596. other->rend_splice = NULL;
  597. }
  598. /* remove from map. */
  599. circuit_set_p_circid_chan(ocirc, 0, NULL);
  600. /* Clear cell queue _after_ removing it from the map. Otherwise our
  601. * "active" checks will be violated. */
  602. cell_queue_clear(&ocirc->p_chan_cells);
  603. }
  604. extend_info_free(circ->n_hop);
  605. tor_free(circ->n_chan_create_cell);
  606. /* Remove from map. */
  607. circuit_set_n_circid_chan(circ, 0, NULL);
  608. /* Clear cell queue _after_ removing it from the map. Otherwise our
  609. * "active" checks will be violated. */
  610. cell_queue_clear(&circ->n_chan_cells);
  611. memwipe(mem, 0xAA, memlen); /* poison memory */
  612. tor_free(mem);
  613. }
  614. /** Deallocate space associated with the linked list <b>cpath</b>. */
  615. static void
  616. circuit_free_cpath(crypt_path_t *cpath)
  617. {
  618. crypt_path_t *victim, *head=cpath;
  619. if (!cpath)
  620. return;
  621. /* it's a doubly linked list, so we have to notice when we've
  622. * gone through it once. */
  623. while (cpath->next && cpath->next != head) {
  624. victim = cpath;
  625. cpath = victim->next;
  626. circuit_free_cpath_node(victim);
  627. }
  628. circuit_free_cpath_node(cpath);
  629. }
  630. /** Release all storage held by circuits. */
  631. void
  632. circuit_free_all(void)
  633. {
  634. circuit_t *next;
  635. while (global_circuitlist) {
  636. next = global_circuitlist->next;
  637. if (! CIRCUIT_IS_ORIGIN(global_circuitlist)) {
  638. or_circuit_t *or_circ = TO_OR_CIRCUIT(global_circuitlist);
  639. while (or_circ->resolving_streams) {
  640. edge_connection_t *next_conn;
  641. next_conn = or_circ->resolving_streams->next_stream;
  642. connection_free(TO_CONN(or_circ->resolving_streams));
  643. or_circ->resolving_streams = next_conn;
  644. }
  645. }
  646. circuit_free(global_circuitlist);
  647. global_circuitlist = next;
  648. }
  649. smartlist_free(circuits_pending_chans);
  650. circuits_pending_chans = NULL;
  651. HT_CLEAR(chan_circid_map, &chan_circid_map);
  652. }
  653. /** Deallocate space associated with the cpath node <b>victim</b>. */
  654. static void
  655. circuit_free_cpath_node(crypt_path_t *victim)
  656. {
  657. if (!victim)
  658. return;
  659. crypto_cipher_free(victim->f_crypto);
  660. crypto_cipher_free(victim->b_crypto);
  661. crypto_digest_free(victim->f_digest);
  662. crypto_digest_free(victim->b_digest);
  663. onion_handshake_state_release(&victim->handshake_state);
  664. crypto_dh_free(victim->rend_dh_handshake_state);
  665. extend_info_free(victim->extend_info);
  666. memwipe(victim, 0xBB, sizeof(crypt_path_t)); /* poison memory */
  667. tor_free(victim);
  668. }
  669. /** Release a crypt_path_reference_t*, which may be NULL. */
  670. static void
  671. cpath_ref_decref(crypt_path_reference_t *cpath_ref)
  672. {
  673. if (cpath_ref != NULL) {
  674. if (--(cpath_ref->refcount) == 0) {
  675. circuit_free_cpath_node(cpath_ref->cpath);
  676. tor_free(cpath_ref);
  677. }
  678. }
  679. }
  680. /** A helper function for circuit_dump_by_conn() below. Log a bunch
  681. * of information about circuit <b>circ</b>.
  682. */
  683. static void
  684. circuit_dump_conn_details(int severity,
  685. circuit_t *circ,
  686. int conn_array_index,
  687. const char *type,
  688. circid_t this_circid,
  689. circid_t other_circid)
  690. {
  691. tor_log(severity, LD_CIRC, "Conn %d has %s circuit: circID %u "
  692. "(other side %u), state %d (%s), born %ld:",
  693. conn_array_index, type, (unsigned)this_circid, (unsigned)other_circid,
  694. circ->state, circuit_state_to_string(circ->state),
  695. (long)circ->timestamp_began.tv_sec);
  696. if (CIRCUIT_IS_ORIGIN(circ)) { /* circ starts at this node */
  697. circuit_log_path(severity, LD_CIRC, TO_ORIGIN_CIRCUIT(circ));
  698. }
  699. }
  700. /** Log, at severity <b>severity</b>, information about each circuit
  701. * that is connected to <b>conn</b>.
  702. */
  703. void
  704. circuit_dump_by_conn(connection_t *conn, int severity)
  705. {
  706. circuit_t *circ;
  707. edge_connection_t *tmpconn;
  708. for (circ = global_circuitlist; circ; circ = circ->next) {
  709. circid_t n_circ_id = circ->n_circ_id, p_circ_id = 0;
  710. if (circ->marked_for_close) {
  711. continue;
  712. }
  713. if (!CIRCUIT_IS_ORIGIN(circ)) {
  714. p_circ_id = TO_OR_CIRCUIT(circ)->p_circ_id;
  715. }
  716. if (CIRCUIT_IS_ORIGIN(circ)) {
  717. for (tmpconn=TO_ORIGIN_CIRCUIT(circ)->p_streams; tmpconn;
  718. tmpconn=tmpconn->next_stream) {
  719. if (TO_CONN(tmpconn) == conn) {
  720. circuit_dump_conn_details(severity, circ, conn->conn_array_index,
  721. "App-ward", p_circ_id, n_circ_id);
  722. }
  723. }
  724. }
  725. if (! CIRCUIT_IS_ORIGIN(circ)) {
  726. for (tmpconn=TO_OR_CIRCUIT(circ)->n_streams; tmpconn;
  727. tmpconn=tmpconn->next_stream) {
  728. if (TO_CONN(tmpconn) == conn) {
  729. circuit_dump_conn_details(severity, circ, conn->conn_array_index,
  730. "Exit-ward", n_circ_id, p_circ_id);
  731. }
  732. }
  733. }
  734. }
  735. }
  736. /** A helper function for circuit_dump_by_chan() below. Log a bunch
  737. * of information about circuit <b>circ</b>.
  738. */
  739. static void
  740. circuit_dump_chan_details(int severity,
  741. circuit_t *circ,
  742. channel_t *chan,
  743. const char *type,
  744. circid_t this_circid,
  745. circid_t other_circid)
  746. {
  747. tor_log(severity, LD_CIRC, "Conn %p has %s circuit: circID %u "
  748. "(other side %u), state %d (%s), born %ld:",
  749. chan, type, (unsigned)this_circid, (unsigned)other_circid, circ->state,
  750. circuit_state_to_string(circ->state),
  751. (long)circ->timestamp_began.tv_sec);
  752. if (CIRCUIT_IS_ORIGIN(circ)) { /* circ starts at this node */
  753. circuit_log_path(severity, LD_CIRC, TO_ORIGIN_CIRCUIT(circ));
  754. }
  755. }
  756. /** Log, at severity <b>severity</b>, information about each circuit
  757. * that is connected to <b>chan</b>.
  758. */
  759. void
  760. circuit_dump_by_chan(channel_t *chan, int severity)
  761. {
  762. circuit_t *circ;
  763. tor_assert(chan);
  764. for (circ = global_circuitlist; circ; circ = circ->next) {
  765. circid_t n_circ_id = circ->n_circ_id, p_circ_id = 0;
  766. if (circ->marked_for_close) {
  767. continue;
  768. }
  769. if (!CIRCUIT_IS_ORIGIN(circ)) {
  770. p_circ_id = TO_OR_CIRCUIT(circ)->p_circ_id;
  771. }
  772. if (! CIRCUIT_IS_ORIGIN(circ) && TO_OR_CIRCUIT(circ)->p_chan &&
  773. TO_OR_CIRCUIT(circ)->p_chan == chan) {
  774. circuit_dump_chan_details(severity, circ, chan, "App-ward",
  775. p_circ_id, n_circ_id);
  776. }
  777. if (circ->n_chan && circ->n_chan == chan) {
  778. circuit_dump_chan_details(severity, circ, chan, "Exit-ward",
  779. n_circ_id, p_circ_id);
  780. }
  781. if (!circ->n_chan && circ->n_hop &&
  782. channel_matches_extend_info(chan, circ->n_hop) &&
  783. tor_memeq(chan->identity_digest,
  784. circ->n_hop->identity_digest, DIGEST_LEN)) {
  785. circuit_dump_chan_details(severity, circ, chan,
  786. (circ->state == CIRCUIT_STATE_OPEN &&
  787. !CIRCUIT_IS_ORIGIN(circ)) ?
  788. "Endpoint" : "Pending",
  789. n_circ_id, p_circ_id);
  790. }
  791. }
  792. }
  793. /** Return the circuit whose global ID is <b>id</b>, or NULL if no
  794. * such circuit exists. */
  795. origin_circuit_t *
  796. circuit_get_by_global_id(uint32_t id)
  797. {
  798. circuit_t *circ;
  799. for (circ=global_circuitlist;circ;circ = circ->next) {
  800. if (CIRCUIT_IS_ORIGIN(circ) &&
  801. TO_ORIGIN_CIRCUIT(circ)->global_identifier == id) {
  802. if (circ->marked_for_close)
  803. return NULL;
  804. else
  805. return TO_ORIGIN_CIRCUIT(circ);
  806. }
  807. }
  808. return NULL;
  809. }
  810. /** Return a circ such that:
  811. * - circ-\>n_circ_id or circ-\>p_circ_id is equal to <b>circ_id</b>, and
  812. * - circ is attached to <b>chan</b>, either as p_chan or n_chan.
  813. * Return NULL if no such circuit exists.
  814. */
  815. static INLINE circuit_t *
  816. circuit_get_by_circid_channel_impl(circid_t circ_id, channel_t *chan)
  817. {
  818. chan_circid_circuit_map_t search;
  819. chan_circid_circuit_map_t *found;
  820. if (_last_circid_chan_ent &&
  821. circ_id == _last_circid_chan_ent->circ_id &&
  822. chan == _last_circid_chan_ent->chan) {
  823. found = _last_circid_chan_ent;
  824. } else {
  825. search.circ_id = circ_id;
  826. search.chan = chan;
  827. found = HT_FIND(chan_circid_map, &chan_circid_map, &search);
  828. _last_circid_chan_ent = found;
  829. }
  830. if (found && found->circuit) {
  831. log_debug(LD_CIRC,
  832. "circuit_get_by_circid_channel_impl() returning circuit %p for"
  833. " circ_id %u, channel ID " U64_FORMAT " (%p)",
  834. found->circuit, (unsigned)circ_id,
  835. U64_PRINTF_ARG(chan->global_identifier), chan);
  836. return found->circuit;
  837. }
  838. log_debug(LD_CIRC,
  839. "circuit_get_by_circid_channel_impl() found nothing for"
  840. " circ_id %u, channel ID " U64_FORMAT " (%p)",
  841. (unsigned)circ_id,
  842. U64_PRINTF_ARG(chan->global_identifier), chan);
  843. return NULL;
  844. /* The rest of this checks for bugs. Disabled by default. */
  845. /* We comment it out because coverity complains otherwise.
  846. {
  847. circuit_t *circ;
  848. for (circ=global_circuitlist;circ;circ = circ->next) {
  849. if (! CIRCUIT_IS_ORIGIN(circ)) {
  850. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  851. if (or_circ->p_chan == chan && or_circ->p_circ_id == circ_id) {
  852. log_warn(LD_BUG,
  853. "circuit matches p_chan, but not in hash table (Bug!)");
  854. return circ;
  855. }
  856. }
  857. if (circ->n_chan == chan && circ->n_circ_id == circ_id) {
  858. log_warn(LD_BUG,
  859. "circuit matches n_chan, but not in hash table (Bug!)");
  860. return circ;
  861. }
  862. }
  863. return NULL;
  864. } */
  865. }
  866. /** Return a circ such that:
  867. * - circ-\>n_circ_id or circ-\>p_circ_id is equal to <b>circ_id</b>, and
  868. * - circ is attached to <b>chan</b>, either as p_chan or n_chan.
  869. * - circ is not marked for close.
  870. * Return NULL if no such circuit exists.
  871. */
  872. circuit_t *
  873. circuit_get_by_circid_channel(circid_t circ_id, channel_t *chan)
  874. {
  875. circuit_t *circ = circuit_get_by_circid_channel_impl(circ_id, chan);
  876. if (!circ || circ->marked_for_close)
  877. return NULL;
  878. else
  879. return circ;
  880. }
  881. /** Return a circ such that:
  882. * - circ-\>n_circ_id or circ-\>p_circ_id is equal to <b>circ_id</b>, and
  883. * - circ is attached to <b>chan</b>, either as p_chan or n_chan.
  884. * Return NULL if no such circuit exists.
  885. */
  886. circuit_t *
  887. circuit_get_by_circid_channel_even_if_marked(circid_t circ_id,
  888. channel_t *chan)
  889. {
  890. return circuit_get_by_circid_channel_impl(circ_id, chan);
  891. }
  892. /** Return true iff the circuit ID <b>circ_id</b> is currently used by a
  893. * circuit, marked or not, on <b>chan</b>. */
  894. int
  895. circuit_id_in_use_on_channel(circid_t circ_id, channel_t *chan)
  896. {
  897. return circuit_get_by_circid_channel_impl(circ_id, chan) != NULL;
  898. }
  899. /** Return the circuit that a given edge connection is using. */
  900. circuit_t *
  901. circuit_get_by_edge_conn(edge_connection_t *conn)
  902. {
  903. circuit_t *circ;
  904. circ = conn->on_circuit;
  905. tor_assert(!circ ||
  906. (CIRCUIT_IS_ORIGIN(circ) ? circ->magic == ORIGIN_CIRCUIT_MAGIC
  907. : circ->magic == OR_CIRCUIT_MAGIC));
  908. return circ;
  909. }
  910. /** For each circuit that has <b>chan</b> as n_chan or p_chan, unlink the
  911. * circuit from the chan,circid map, and mark it for close if it hasn't
  912. * been marked already.
  913. */
  914. void
  915. circuit_unlink_all_from_channel(channel_t *chan, int reason)
  916. {
  917. circuit_t *circ;
  918. channel_unlink_all_circuits(chan);
  919. for (circ = global_circuitlist; circ; circ = circ->next) {
  920. int mark = 0;
  921. if (circ->n_chan == chan) {
  922. circuit_set_n_circid_chan(circ, 0, NULL);
  923. mark = 1;
  924. /* If we didn't request this closure, pass the remote
  925. * bit to mark_for_close. */
  926. if (chan->reason_for_closing != CHANNEL_CLOSE_REQUESTED)
  927. reason |= END_CIRC_REASON_FLAG_REMOTE;
  928. }
  929. if (! CIRCUIT_IS_ORIGIN(circ)) {
  930. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  931. if (or_circ->p_chan == chan) {
  932. circuit_set_p_circid_chan(or_circ, 0, NULL);
  933. mark = 1;
  934. }
  935. }
  936. if (mark && !circ->marked_for_close)
  937. circuit_mark_for_close(circ, reason);
  938. }
  939. }
  940. /** Return a circ such that
  941. * - circ-\>rend_data-\>onion_address is equal to
  942. * <b>rend_data</b>-\>onion_address,
  943. * - circ-\>rend_data-\>rend_cookie is equal to
  944. * <b>rend_data</b>-\>rend_cookie, and
  945. * - circ-\>purpose is equal to CIRCUIT_PURPOSE_C_REND_READY.
  946. *
  947. * Return NULL if no such circuit exists.
  948. */
  949. origin_circuit_t *
  950. circuit_get_ready_rend_circ_by_rend_data(const rend_data_t *rend_data)
  951. {
  952. circuit_t *circ;
  953. for (circ = global_circuitlist; circ; circ = circ->next) {
  954. if (!circ->marked_for_close &&
  955. circ->purpose == CIRCUIT_PURPOSE_C_REND_READY) {
  956. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  957. if (ocirc->rend_data &&
  958. !rend_cmp_service_ids(rend_data->onion_address,
  959. ocirc->rend_data->onion_address) &&
  960. tor_memeq(ocirc->rend_data->rend_cookie,
  961. rend_data->rend_cookie,
  962. REND_COOKIE_LEN))
  963. return ocirc;
  964. }
  965. }
  966. return NULL;
  967. }
  968. /** Return the first circuit originating here in global_circuitlist after
  969. * <b>start</b> whose purpose is <b>purpose</b>, and where
  970. * <b>digest</b> (if set) matches the rend_pk_digest field. Return NULL if no
  971. * circuit is found. If <b>start</b> is NULL, begin at the start of the list.
  972. */
  973. origin_circuit_t *
  974. circuit_get_next_by_pk_and_purpose(origin_circuit_t *start,
  975. const char *digest, uint8_t purpose)
  976. {
  977. circuit_t *circ;
  978. tor_assert(CIRCUIT_PURPOSE_IS_ORIGIN(purpose));
  979. if (start == NULL)
  980. circ = global_circuitlist;
  981. else
  982. circ = TO_CIRCUIT(start)->next;
  983. for ( ; circ; circ = circ->next) {
  984. if (circ->marked_for_close)
  985. continue;
  986. if (circ->purpose != purpose)
  987. continue;
  988. if (!digest)
  989. return TO_ORIGIN_CIRCUIT(circ);
  990. else if (TO_ORIGIN_CIRCUIT(circ)->rend_data &&
  991. tor_memeq(TO_ORIGIN_CIRCUIT(circ)->rend_data->rend_pk_digest,
  992. digest, DIGEST_LEN))
  993. return TO_ORIGIN_CIRCUIT(circ);
  994. }
  995. return NULL;
  996. }
  997. /** Map from rendezvous cookie to or_circuit_t */
  998. static digestmap_t *rend_cookie_map = NULL;
  999. /** Map from introduction point digest to or_circuit_t */
  1000. static digestmap_t *intro_digest_map = NULL;
  1001. /** Return the OR circuit whose purpose is <b>purpose</b>, and whose
  1002. * rend_token is the REND_TOKEN_LEN-byte <b>token</b>. If <b>is_rend_circ</b>,
  1003. * look for rendezvous point circuits; otherwise look for introduction point
  1004. * circuits. */
  1005. static or_circuit_t *
  1006. circuit_get_by_rend_token_and_purpose(uint8_t purpose, int is_rend_circ,
  1007. const char *token)
  1008. {
  1009. or_circuit_t *circ;
  1010. digestmap_t *map = is_rend_circ ? rend_cookie_map : intro_digest_map;
  1011. if (!map)
  1012. return NULL;
  1013. circ = digestmap_get(map, token);
  1014. if (!circ ||
  1015. circ->base_.purpose != purpose ||
  1016. circ->base_.marked_for_close)
  1017. return NULL;
  1018. if (!circ->rendinfo ||
  1019. ! bool_eq(circ->rendinfo->is_rend_circ, is_rend_circ) ||
  1020. tor_memneq(circ->rendinfo->rend_token, token, REND_TOKEN_LEN)) {
  1021. char *t = tor_strdup(hex_str(token, REND_TOKEN_LEN));
  1022. log_warn(LD_BUG, "Wanted a circuit with %s:%d, but lookup returned %s:%d",
  1023. safe_str(t), is_rend_circ,
  1024. safe_str(hex_str(circ->rendinfo->rend_token, REND_TOKEN_LEN)),
  1025. (int)circ->rendinfo->is_rend_circ);
  1026. tor_free(t);
  1027. return NULL;
  1028. }
  1029. return circ;
  1030. }
  1031. /** Clear the rendezvous cookie or introduction point key digest that's
  1032. * configured on <b>circ</b>, if any, and remove it from any such maps. */
  1033. static void
  1034. circuit_clear_rend_token(or_circuit_t *circ)
  1035. {
  1036. or_circuit_t *found_circ;
  1037. digestmap_t *map;
  1038. if (!circ || !circ->rendinfo)
  1039. return;
  1040. map = circ->rendinfo->is_rend_circ ? rend_cookie_map : intro_digest_map;
  1041. if (!map) {
  1042. log_warn(LD_BUG, "Tried to clear rend token on circuit, but found no map");
  1043. return;
  1044. }
  1045. found_circ = digestmap_get(map, circ->rendinfo->rend_token);
  1046. if (found_circ == circ) {
  1047. /* Great, this is the right one. */
  1048. digestmap_remove(map, circ->rendinfo->rend_token);
  1049. } else if (found_circ) {
  1050. log_warn(LD_BUG, "Tried to clear rend token on circuit, but "
  1051. "it was already replaced in the map.");
  1052. } else {
  1053. log_warn(LD_BUG, "Tried to clear rend token on circuit, but "
  1054. "it not in the map at all.");
  1055. }
  1056. tor_free(circ->rendinfo); /* Sets it to NULL too */
  1057. }
  1058. /** Set the rendezvous cookie (if is_rend_circ), or the introduction point
  1059. * digest (if ! is_rend_circ) of <b>circ</b> to the REND_TOKEN_LEN-byte value
  1060. * in <b>token</b>, and add it to the appropriate map. If it previously had a
  1061. * token, clear it. If another circuit previously had the same
  1062. * cookie/intro-digest, mark that circuit and remove it from the map. */
  1063. static void
  1064. circuit_set_rend_token(or_circuit_t *circ, int is_rend_circ,
  1065. const uint8_t *token)
  1066. {
  1067. digestmap_t **map_p, *map;
  1068. or_circuit_t *found_circ;
  1069. /* Find the right map, creating it as needed */
  1070. map_p = is_rend_circ ? &rend_cookie_map : &intro_digest_map;
  1071. if (!*map_p)
  1072. *map_p = digestmap_new();
  1073. map = *map_p;
  1074. /* If this circuit already has a token, we need to remove that. */
  1075. if (circ->rendinfo)
  1076. circuit_clear_rend_token(circ);
  1077. found_circ = digestmap_get(map, (const char *)token);
  1078. if (found_circ) {
  1079. tor_assert(found_circ != circ);
  1080. circuit_clear_rend_token(found_circ);
  1081. if (! found_circ->base_.marked_for_close)
  1082. circuit_mark_for_close(TO_CIRCUIT(found_circ), END_CIRC_REASON_FINISHED);
  1083. }
  1084. /* Now set up the rendinfo */
  1085. circ->rendinfo = tor_malloc(sizeof(*circ->rendinfo));
  1086. memcpy(circ->rendinfo->rend_token, token, REND_TOKEN_LEN);
  1087. circ->rendinfo->is_rend_circ = is_rend_circ ? 1 : 0;
  1088. digestmap_set(map, (const char *)token, circ);
  1089. }
  1090. /** Return the circuit waiting for a rendezvous with the provided cookie.
  1091. * Return NULL if no such circuit is found.
  1092. */
  1093. or_circuit_t *
  1094. circuit_get_rendezvous(const char *cookie)
  1095. {
  1096. return circuit_get_by_rend_token_and_purpose(
  1097. CIRCUIT_PURPOSE_REND_POINT_WAITING,
  1098. 1, cookie);
  1099. }
  1100. /** Return the circuit waiting for intro cells of the given digest.
  1101. * Return NULL if no such circuit is found.
  1102. */
  1103. or_circuit_t *
  1104. circuit_get_intro_point(const char *digest)
  1105. {
  1106. return circuit_get_by_rend_token_and_purpose(
  1107. CIRCUIT_PURPOSE_INTRO_POINT, 0, digest);
  1108. }
  1109. /** Set the rendezvous cookie of <b>circ</b> to <b>cookie</b>. If another
  1110. * circuit previously had that cookie, mark it. */
  1111. void
  1112. circuit_set_rendezvous_cookie(or_circuit_t *circ, const uint8_t *cookie)
  1113. {
  1114. circuit_set_rend_token(circ, 1, cookie);
  1115. }
  1116. /** Set the intro point key digest of <b>circ</b> to <b>cookie</b>. If another
  1117. * circuit previously had that intro point digest, mark it. */
  1118. void
  1119. circuit_set_intro_point_digest(or_circuit_t *circ, const uint8_t *digest)
  1120. {
  1121. circuit_set_rend_token(circ, 0, digest);
  1122. }
  1123. /** Return a circuit that is open, is CIRCUIT_PURPOSE_C_GENERAL,
  1124. * has a timestamp_dirty value of 0, has flags matching the CIRCLAUNCH_*
  1125. * flags in <b>flags</b>, and if info is defined, does not already use info
  1126. * as any of its hops; or NULL if no circuit fits this description.
  1127. *
  1128. * The <b>purpose</b> argument (currently ignored) refers to the purpose of
  1129. * the circuit we want to create, not the purpose of the circuit we want to
  1130. * cannibalize.
  1131. *
  1132. * If !CIRCLAUNCH_NEED_UPTIME, prefer returning non-uptime circuits.
  1133. */
  1134. origin_circuit_t *
  1135. circuit_find_to_cannibalize(uint8_t purpose, extend_info_t *info,
  1136. int flags)
  1137. {
  1138. circuit_t *circ_;
  1139. origin_circuit_t *best=NULL;
  1140. int need_uptime = (flags & CIRCLAUNCH_NEED_UPTIME) != 0;
  1141. int need_capacity = (flags & CIRCLAUNCH_NEED_CAPACITY) != 0;
  1142. int internal = (flags & CIRCLAUNCH_IS_INTERNAL) != 0;
  1143. const or_options_t *options = get_options();
  1144. /* Make sure we're not trying to create a onehop circ by
  1145. * cannibalization. */
  1146. tor_assert(!(flags & CIRCLAUNCH_ONEHOP_TUNNEL));
  1147. log_debug(LD_CIRC,
  1148. "Hunting for a circ to cannibalize: purpose %d, uptime %d, "
  1149. "capacity %d, internal %d",
  1150. purpose, need_uptime, need_capacity, internal);
  1151. for (circ_=global_circuitlist; circ_; circ_ = circ_->next) {
  1152. if (CIRCUIT_IS_ORIGIN(circ_) &&
  1153. circ_->state == CIRCUIT_STATE_OPEN &&
  1154. !circ_->marked_for_close &&
  1155. circ_->purpose == CIRCUIT_PURPOSE_C_GENERAL &&
  1156. !circ_->timestamp_dirty) {
  1157. origin_circuit_t *circ = TO_ORIGIN_CIRCUIT(circ_);
  1158. if ((!need_uptime || circ->build_state->need_uptime) &&
  1159. (!need_capacity || circ->build_state->need_capacity) &&
  1160. (internal == circ->build_state->is_internal) &&
  1161. !circ->unusable_for_new_conns &&
  1162. circ->remaining_relay_early_cells &&
  1163. circ->build_state->desired_path_len == DEFAULT_ROUTE_LEN &&
  1164. !circ->build_state->onehop_tunnel &&
  1165. !circ->isolation_values_set) {
  1166. if (info) {
  1167. /* need to make sure we don't duplicate hops */
  1168. crypt_path_t *hop = circ->cpath;
  1169. const node_t *ri1 = node_get_by_id(info->identity_digest);
  1170. do {
  1171. const node_t *ri2;
  1172. if (tor_memeq(hop->extend_info->identity_digest,
  1173. info->identity_digest, DIGEST_LEN))
  1174. goto next;
  1175. if (ri1 &&
  1176. (ri2 = node_get_by_id(hop->extend_info->identity_digest))
  1177. && nodes_in_same_family(ri1, ri2))
  1178. goto next;
  1179. hop=hop->next;
  1180. } while (hop!=circ->cpath);
  1181. }
  1182. if (options->ExcludeNodes) {
  1183. /* Make sure no existing nodes in the circuit are excluded for
  1184. * general use. (This may be possible if StrictNodes is 0, and we
  1185. * thought we needed to use an otherwise excluded node for, say, a
  1186. * directory operation.) */
  1187. crypt_path_t *hop = circ->cpath;
  1188. do {
  1189. if (routerset_contains_extendinfo(options->ExcludeNodes,
  1190. hop->extend_info))
  1191. goto next;
  1192. hop = hop->next;
  1193. } while (hop != circ->cpath);
  1194. }
  1195. if (!best || (best->build_state->need_uptime && !need_uptime))
  1196. best = circ;
  1197. next: ;
  1198. }
  1199. }
  1200. }
  1201. return best;
  1202. }
  1203. /** Return the number of hops in circuit's path. */
  1204. int
  1205. circuit_get_cpath_len(origin_circuit_t *circ)
  1206. {
  1207. int n = 0;
  1208. if (circ && circ->cpath) {
  1209. crypt_path_t *cpath, *cpath_next = NULL;
  1210. for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
  1211. cpath_next = cpath->next;
  1212. ++n;
  1213. }
  1214. }
  1215. return n;
  1216. }
  1217. /** Return the <b>hopnum</b>th hop in <b>circ</b>->cpath, or NULL if there
  1218. * aren't that many hops in the list. */
  1219. crypt_path_t *
  1220. circuit_get_cpath_hop(origin_circuit_t *circ, int hopnum)
  1221. {
  1222. if (circ && circ->cpath && hopnum > 0) {
  1223. crypt_path_t *cpath, *cpath_next = NULL;
  1224. for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
  1225. cpath_next = cpath->next;
  1226. if (--hopnum <= 0)
  1227. return cpath;
  1228. }
  1229. }
  1230. return NULL;
  1231. }
  1232. /** Go through the circuitlist; mark-for-close each circuit that starts
  1233. * at us but has not yet been used. */
  1234. void
  1235. circuit_mark_all_unused_circs(void)
  1236. {
  1237. circuit_t *circ;
  1238. for (circ=global_circuitlist; circ; circ = circ->next) {
  1239. if (CIRCUIT_IS_ORIGIN(circ) &&
  1240. !circ->marked_for_close &&
  1241. !circ->timestamp_dirty)
  1242. circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
  1243. }
  1244. }
  1245. /** Go through the circuitlist; for each circuit that starts at us
  1246. * and is dirty, frob its timestamp_dirty so we won't use it for any
  1247. * new streams.
  1248. *
  1249. * This is useful for letting the user change pseudonyms, so new
  1250. * streams will not be linkable to old streams.
  1251. */
  1252. void
  1253. circuit_mark_all_dirty_circs_as_unusable(void)
  1254. {
  1255. circuit_t *circ;
  1256. for (circ=global_circuitlist; circ; circ = circ->next) {
  1257. if (CIRCUIT_IS_ORIGIN(circ) &&
  1258. !circ->marked_for_close &&
  1259. circ->timestamp_dirty) {
  1260. mark_circuit_unusable_for_new_conns(TO_ORIGIN_CIRCUIT(circ));
  1261. }
  1262. }
  1263. }
  1264. /** Mark <b>circ</b> to be closed next time we call
  1265. * circuit_close_all_marked(). Do any cleanup needed:
  1266. * - If state is onionskin_pending, remove circ from the onion_pending
  1267. * list.
  1268. * - If circ isn't open yet: call circuit_build_failed() if we're
  1269. * the origin, and in either case call circuit_rep_hist_note_result()
  1270. * to note stats.
  1271. * - If purpose is C_INTRODUCE_ACK_WAIT, report the intro point
  1272. * failure we just had to the hidden service client module.
  1273. * - If purpose is C_INTRODUCING and <b>reason</b> isn't TIMEOUT,
  1274. * report to the hidden service client module that the intro point
  1275. * we just tried may be unreachable.
  1276. * - Send appropriate destroys and edge_destroys for conns and
  1277. * streams attached to circ.
  1278. * - If circ->rend_splice is set (we are the midpoint of a joined
  1279. * rendezvous stream), then mark the other circuit to close as well.
  1280. */
  1281. void
  1282. circuit_mark_for_close_(circuit_t *circ, int reason, int line,
  1283. const char *file)
  1284. {
  1285. int orig_reason = reason; /* Passed to the controller */
  1286. assert_circuit_ok(circ);
  1287. tor_assert(line);
  1288. tor_assert(file);
  1289. if (circ->marked_for_close) {
  1290. log_warn(LD_BUG,
  1291. "Duplicate call to circuit_mark_for_close at %s:%d"
  1292. " (first at %s:%d)", file, line,
  1293. circ->marked_for_close_file, circ->marked_for_close);
  1294. return;
  1295. }
  1296. if (reason == END_CIRC_AT_ORIGIN) {
  1297. if (!CIRCUIT_IS_ORIGIN(circ)) {
  1298. log_warn(LD_BUG, "Specified 'at-origin' non-reason for ending circuit, "
  1299. "but circuit was not at origin. (called %s:%d, purpose=%d)",
  1300. file, line, circ->purpose);
  1301. }
  1302. reason = END_CIRC_REASON_NONE;
  1303. }
  1304. if (CIRCUIT_IS_ORIGIN(circ)) {
  1305. if (pathbias_check_close(TO_ORIGIN_CIRCUIT(circ), reason) == -1) {
  1306. /* Don't close it yet, we need to test it first */
  1307. return;
  1308. }
  1309. /* We don't send reasons when closing circuits at the origin. */
  1310. reason = END_CIRC_REASON_NONE;
  1311. }
  1312. if (reason & END_CIRC_REASON_FLAG_REMOTE)
  1313. reason &= ~END_CIRC_REASON_FLAG_REMOTE;
  1314. if (reason < END_CIRC_REASON_MIN_ || reason > END_CIRC_REASON_MAX_) {
  1315. if (!(orig_reason & END_CIRC_REASON_FLAG_REMOTE))
  1316. log_warn(LD_BUG, "Reason %d out of range at %s:%d", reason, file, line);
  1317. reason = END_CIRC_REASON_NONE;
  1318. }
  1319. if (circ->state == CIRCUIT_STATE_ONIONSKIN_PENDING) {
  1320. onion_pending_remove(TO_OR_CIRCUIT(circ));
  1321. }
  1322. /* If the circuit ever became OPEN, we sent it to the reputation history
  1323. * module then. If it isn't OPEN, we send it there now to remember which
  1324. * links worked and which didn't.
  1325. */
  1326. if (circ->state != CIRCUIT_STATE_OPEN) {
  1327. if (CIRCUIT_IS_ORIGIN(circ)) {
  1328. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  1329. circuit_build_failed(ocirc); /* take actions if necessary */
  1330. circuit_rep_hist_note_result(ocirc);
  1331. }
  1332. }
  1333. if (circ->state == CIRCUIT_STATE_CHAN_WAIT) {
  1334. if (circuits_pending_chans)
  1335. smartlist_remove(circuits_pending_chans, circ);
  1336. }
  1337. if (CIRCUIT_IS_ORIGIN(circ)) {
  1338. control_event_circuit_status(TO_ORIGIN_CIRCUIT(circ),
  1339. (circ->state == CIRCUIT_STATE_OPEN)?CIRC_EVENT_CLOSED:CIRC_EVENT_FAILED,
  1340. orig_reason);
  1341. }
  1342. if (circ->purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
  1343. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  1344. int timed_out = (reason == END_CIRC_REASON_TIMEOUT);
  1345. tor_assert(circ->state == CIRCUIT_STATE_OPEN);
  1346. tor_assert(ocirc->build_state->chosen_exit);
  1347. tor_assert(ocirc->rend_data);
  1348. /* treat this like getting a nack from it */
  1349. log_info(LD_REND, "Failed intro circ %s to %s (awaiting ack). %s",
  1350. safe_str_client(ocirc->rend_data->onion_address),
  1351. safe_str_client(build_state_get_exit_nickname(ocirc->build_state)),
  1352. timed_out ? "Recording timeout." : "Removing from descriptor.");
  1353. rend_client_report_intro_point_failure(ocirc->build_state->chosen_exit,
  1354. ocirc->rend_data,
  1355. timed_out ?
  1356. INTRO_POINT_FAILURE_TIMEOUT :
  1357. INTRO_POINT_FAILURE_GENERIC);
  1358. } else if (circ->purpose == CIRCUIT_PURPOSE_C_INTRODUCING &&
  1359. reason != END_CIRC_REASON_TIMEOUT) {
  1360. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  1361. if (ocirc->build_state->chosen_exit && ocirc->rend_data) {
  1362. log_info(LD_REND, "Failed intro circ %s to %s "
  1363. "(building circuit to intro point). "
  1364. "Marking intro point as possibly unreachable.",
  1365. safe_str_client(ocirc->rend_data->onion_address),
  1366. safe_str_client(build_state_get_exit_nickname(ocirc->build_state)));
  1367. rend_client_report_intro_point_failure(ocirc->build_state->chosen_exit,
  1368. ocirc->rend_data,
  1369. INTRO_POINT_FAILURE_UNREACHABLE);
  1370. }
  1371. }
  1372. if (circ->n_chan) {
  1373. circuit_clear_cell_queue(circ, circ->n_chan);
  1374. /* Only send destroy if the channel isn't closing anyway */
  1375. if (!(circ->n_chan->state == CHANNEL_STATE_CLOSING ||
  1376. circ->n_chan->state == CHANNEL_STATE_CLOSED ||
  1377. circ->n_chan->state == CHANNEL_STATE_ERROR)) {
  1378. channel_send_destroy(circ->n_circ_id, circ->n_chan, reason);
  1379. }
  1380. circuitmux_detach_circuit(circ->n_chan->cmux, circ);
  1381. }
  1382. if (! CIRCUIT_IS_ORIGIN(circ)) {
  1383. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  1384. edge_connection_t *conn;
  1385. for (conn=or_circ->n_streams; conn; conn=conn->next_stream)
  1386. connection_edge_destroy(or_circ->p_circ_id, conn);
  1387. or_circ->n_streams = NULL;
  1388. while (or_circ->resolving_streams) {
  1389. conn = or_circ->resolving_streams;
  1390. or_circ->resolving_streams = conn->next_stream;
  1391. if (!conn->base_.marked_for_close) {
  1392. /* The client will see a DESTROY, and infer that the connections
  1393. * are closing because the circuit is getting torn down. No need
  1394. * to send an end cell. */
  1395. conn->edge_has_sent_end = 1;
  1396. conn->end_reason = END_STREAM_REASON_DESTROY;
  1397. conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
  1398. connection_mark_for_close(TO_CONN(conn));
  1399. }
  1400. conn->on_circuit = NULL;
  1401. }
  1402. if (or_circ->p_chan) {
  1403. circuit_clear_cell_queue(circ, or_circ->p_chan);
  1404. /* Only send destroy if the channel isn't closing anyway */
  1405. if (!(or_circ->p_chan->state == CHANNEL_STATE_CLOSING ||
  1406. or_circ->p_chan->state == CHANNEL_STATE_CLOSED ||
  1407. or_circ->p_chan->state == CHANNEL_STATE_ERROR)) {
  1408. channel_send_destroy(or_circ->p_circ_id, or_circ->p_chan, reason);
  1409. }
  1410. circuitmux_detach_circuit(or_circ->p_chan->cmux, circ);
  1411. }
  1412. } else {
  1413. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  1414. edge_connection_t *conn;
  1415. for (conn=ocirc->p_streams; conn; conn=conn->next_stream)
  1416. connection_edge_destroy(circ->n_circ_id, conn);
  1417. ocirc->p_streams = NULL;
  1418. }
  1419. circ->marked_for_close = line;
  1420. circ->marked_for_close_file = file;
  1421. if (!CIRCUIT_IS_ORIGIN(circ)) {
  1422. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  1423. if (or_circ->rend_splice) {
  1424. if (!or_circ->rend_splice->base_.marked_for_close) {
  1425. /* do this after marking this circuit, to avoid infinite recursion. */
  1426. circuit_mark_for_close(TO_CIRCUIT(or_circ->rend_splice), reason);
  1427. }
  1428. or_circ->rend_splice = NULL;
  1429. }
  1430. }
  1431. }
  1432. /** Given a marked circuit <b>circ</b>, aggressively free its cell queues to
  1433. * recover memory. */
  1434. static void
  1435. marked_circuit_free_cells(circuit_t *circ)
  1436. {
  1437. if (!circ->marked_for_close) {
  1438. log_warn(LD_BUG, "Called on non-marked circuit");
  1439. return;
  1440. }
  1441. cell_queue_clear(&circ->n_chan_cells);
  1442. if (! CIRCUIT_IS_ORIGIN(circ))
  1443. cell_queue_clear(& TO_OR_CIRCUIT(circ)->p_chan_cells);
  1444. }
  1445. /** Return the number of cells used by the circuit <b>c</b>'s cell queues. */
  1446. static size_t
  1447. n_cells_in_circ_queues(const circuit_t *c)
  1448. {
  1449. size_t n = c->n_chan_cells.n;
  1450. if (! CIRCUIT_IS_ORIGIN(c)) {
  1451. circuit_t *cc = (circuit_t *) c;
  1452. n += TO_OR_CIRCUIT(cc)->p_chan_cells.n;
  1453. }
  1454. return n;
  1455. }
  1456. /**
  1457. * Return the age of the oldest cell queued on <b>c</b>, in milliseconds.
  1458. * Return 0 if there are no cells queued on c. Requires that <b>now</b> be
  1459. * the current time in milliseconds since the epoch, truncated.
  1460. *
  1461. * This function will return incorrect results if the oldest cell queued on
  1462. * the circuit is older than 2**32 msec (about 49 days) old.
  1463. */
  1464. static uint32_t
  1465. circuit_max_queued_cell_age(const circuit_t *c, uint32_t now)
  1466. {
  1467. uint32_t age = 0;
  1468. if (c->n_chan_cells.head)
  1469. age = now - c->n_chan_cells.head->inserted_time;
  1470. if (! CIRCUIT_IS_ORIGIN(c)) {
  1471. const or_circuit_t *orcirc = TO_OR_CIRCUIT((circuit_t*)c);
  1472. if (orcirc->p_chan_cells.head) {
  1473. uint32_t age2 = now - orcirc->p_chan_cells.head->inserted_time;
  1474. if (age2 > age)
  1475. return age2;
  1476. }
  1477. }
  1478. return age;
  1479. }
  1480. /** Temporary variable for circuits_compare_by_oldest_queued_cell_ This is a
  1481. * kludge to work around the fact that qsort doesn't provide a way for
  1482. * comparison functions to take an extra argument. */
  1483. static uint32_t circcomp_now_tmp;
  1484. /** Helper to sort a list of circuit_t by age of oldest cell, in descending
  1485. * order. Requires that circcomp_now_tmp is set correctly. */
  1486. static int
  1487. circuits_compare_by_oldest_queued_cell_(const void **a_, const void **b_)
  1488. {
  1489. const circuit_t *a = *a_;
  1490. const circuit_t *b = *b_;
  1491. uint32_t age_a = circuit_max_queued_cell_age(a, circcomp_now_tmp);
  1492. uint32_t age_b = circuit_max_queued_cell_age(b, circcomp_now_tmp);
  1493. if (age_a < age_b)
  1494. return 1;
  1495. else if (age_a == age_b)
  1496. return 0;
  1497. else
  1498. return -1;
  1499. }
  1500. #define FRACTION_OF_CELLS_TO_RETAIN_ON_OOM 0.90
  1501. /** We're out of memory for cells, having allocated <b>current_allocation</b>
  1502. * bytes' worth. Kill the 'worst' circuits until we're under
  1503. * FRACTION_OF_CIRCS_TO_RETAIN_ON_OOM of our maximum usage. */
  1504. void
  1505. circuits_handle_oom(size_t current_allocation)
  1506. {
  1507. /* Let's hope there's enough slack space for this allocation here... */
  1508. smartlist_t *circlist = smartlist_new();
  1509. circuit_t *circ;
  1510. size_t n_cells_removed=0, n_cells_to_remove;
  1511. int n_circuits_killed=0;
  1512. struct timeval now;
  1513. log_notice(LD_GENERAL, "We're low on memory. Killing circuits with "
  1514. "over-long queues. (This behavior is controlled by "
  1515. "MaxMemInCellQueues.)");
  1516. {
  1517. size_t mem_target = (size_t)(get_options()->MaxMemInCellQueues *
  1518. FRACTION_OF_CELLS_TO_RETAIN_ON_OOM);
  1519. size_t mem_to_recover;
  1520. if (current_allocation <= mem_target)
  1521. return;
  1522. mem_to_recover = current_allocation - mem_target;
  1523. n_cells_to_remove = CEIL_DIV(mem_to_recover, packed_cell_mem_cost());
  1524. }
  1525. /* This algorithm itself assumes that you've got enough memory slack
  1526. * to actually run it. */
  1527. for (circ = global_circuitlist; circ; circ = circ->next)
  1528. smartlist_add(circlist, circ);
  1529. /* Set circcomp_now_tmp so that the sort can work. */
  1530. tor_gettimeofday_cached(&now);
  1531. circcomp_now_tmp = (uint32_t)tv_to_msec(&now);
  1532. /* This is O(n log n); there are faster algorithms we could use instead.
  1533. * Let's hope this doesn't happen enough to be in the critical path. */
  1534. smartlist_sort(circlist, circuits_compare_by_oldest_queued_cell_);
  1535. /* Okay, now the worst circuits are at the front of the list. Let's mark
  1536. * them, and reclaim their storage aggressively. */
  1537. SMARTLIST_FOREACH_BEGIN(circlist, circuit_t *, circ) {
  1538. size_t n = n_cells_in_circ_queues(circ);
  1539. if (! circ->marked_for_close) {
  1540. circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
  1541. }
  1542. marked_circuit_free_cells(circ);
  1543. ++n_circuits_killed;
  1544. n_cells_removed += n;
  1545. if (n_cells_removed >= n_cells_to_remove)
  1546. break;
  1547. } SMARTLIST_FOREACH_END(circ);
  1548. clean_cell_pool(); /* In case this helps. */
  1549. log_notice(LD_GENERAL, "Removed "U64_FORMAT" bytes by killing %d circuits.",
  1550. U64_PRINTF_ARG(n_cells_removed * packed_cell_mem_cost()),
  1551. n_circuits_killed);
  1552. smartlist_free(circlist);
  1553. }
  1554. /** Verify that cpath layer <b>cp</b> has all of its invariants
  1555. * correct. Trigger an assert if anything is invalid.
  1556. */
  1557. void
  1558. assert_cpath_layer_ok(const crypt_path_t *cp)
  1559. {
  1560. // tor_assert(cp->addr); /* these are zero for rendezvous extra-hops */
  1561. // tor_assert(cp->port);
  1562. tor_assert(cp);
  1563. tor_assert(cp->magic == CRYPT_PATH_MAGIC);
  1564. switch (cp->state)
  1565. {
  1566. case CPATH_STATE_OPEN:
  1567. tor_assert(cp->f_crypto);
  1568. tor_assert(cp->b_crypto);
  1569. /* fall through */
  1570. case CPATH_STATE_CLOSED:
  1571. /*XXXX Assert that there's no handshake_state either. */
  1572. tor_assert(!cp->rend_dh_handshake_state);
  1573. break;
  1574. case CPATH_STATE_AWAITING_KEYS:
  1575. /* tor_assert(cp->dh_handshake_state); */
  1576. break;
  1577. default:
  1578. log_fn(LOG_ERR, LD_BUG, "Unexpected state %d", cp->state);
  1579. tor_assert(0);
  1580. }
  1581. tor_assert(cp->package_window >= 0);
  1582. tor_assert(cp->deliver_window >= 0);
  1583. }
  1584. /** Verify that cpath <b>cp</b> has all of its invariants
  1585. * correct. Trigger an assert if anything is invalid.
  1586. */
  1587. static void
  1588. assert_cpath_ok(const crypt_path_t *cp)
  1589. {
  1590. const crypt_path_t *start = cp;
  1591. do {
  1592. assert_cpath_layer_ok(cp);
  1593. /* layers must be in sequence of: "open* awaiting? closed*" */
  1594. if (cp != start) {
  1595. if (cp->state == CPATH_STATE_AWAITING_KEYS) {
  1596. tor_assert(cp->prev->state == CPATH_STATE_OPEN);
  1597. } else if (cp->state == CPATH_STATE_OPEN) {
  1598. tor_assert(cp->prev->state == CPATH_STATE_OPEN);
  1599. }
  1600. }
  1601. cp = cp->next;
  1602. tor_assert(cp);
  1603. } while (cp != start);
  1604. }
  1605. /** Verify that circuit <b>c</b> has all of its invariants
  1606. * correct. Trigger an assert if anything is invalid.
  1607. */
  1608. void
  1609. assert_circuit_ok(const circuit_t *c)
  1610. {
  1611. edge_connection_t *conn;
  1612. const or_circuit_t *or_circ = NULL;
  1613. const origin_circuit_t *origin_circ = NULL;
  1614. tor_assert(c);
  1615. tor_assert(c->magic == ORIGIN_CIRCUIT_MAGIC || c->magic == OR_CIRCUIT_MAGIC);
  1616. tor_assert(c->purpose >= CIRCUIT_PURPOSE_MIN_ &&
  1617. c->purpose <= CIRCUIT_PURPOSE_MAX_);
  1618. {
  1619. /* Having a separate variable for this pleases GCC 4.2 in ways I hope I
  1620. * never understand. -NM. */
  1621. circuit_t *nonconst_circ = (circuit_t*) c;
  1622. if (CIRCUIT_IS_ORIGIN(c))
  1623. origin_circ = TO_ORIGIN_CIRCUIT(nonconst_circ);
  1624. else
  1625. or_circ = TO_OR_CIRCUIT(nonconst_circ);
  1626. }
  1627. if (c->n_chan) {
  1628. tor_assert(!c->n_hop);
  1629. if (c->n_circ_id) {
  1630. /* We use the _impl variant here to make sure we don't fail on marked
  1631. * circuits, which would not be returned by the regular function. */
  1632. circuit_t *c2 = circuit_get_by_circid_channel_impl(c->n_circ_id,
  1633. c->n_chan);
  1634. tor_assert(c == c2);
  1635. }
  1636. }
  1637. if (or_circ && or_circ->p_chan) {
  1638. if (or_circ->p_circ_id) {
  1639. /* ibid */
  1640. circuit_t *c2 = circuit_get_by_circid_channel_impl(or_circ->p_circ_id,
  1641. or_circ->p_chan);
  1642. tor_assert(c == c2);
  1643. }
  1644. }
  1645. if (or_circ)
  1646. for (conn = or_circ->n_streams; conn; conn = conn->next_stream)
  1647. tor_assert(conn->base_.type == CONN_TYPE_EXIT);
  1648. tor_assert(c->deliver_window >= 0);
  1649. tor_assert(c->package_window >= 0);
  1650. if (c->state == CIRCUIT_STATE_OPEN) {
  1651. tor_assert(!c->n_chan_create_cell);
  1652. if (or_circ) {
  1653. tor_assert(or_circ->n_crypto);
  1654. tor_assert(or_circ->p_crypto);
  1655. tor_assert(or_circ->n_digest);
  1656. tor_assert(or_circ->p_digest);
  1657. }
  1658. }
  1659. if (c->state == CIRCUIT_STATE_CHAN_WAIT && !c->marked_for_close) {
  1660. tor_assert(circuits_pending_chans &&
  1661. smartlist_contains(circuits_pending_chans, c));
  1662. } else {
  1663. tor_assert(!circuits_pending_chans ||
  1664. !smartlist_contains(circuits_pending_chans, c));
  1665. }
  1666. if (origin_circ && origin_circ->cpath) {
  1667. assert_cpath_ok(origin_circ->cpath);
  1668. }
  1669. if (c->purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED) {
  1670. tor_assert(or_circ);
  1671. if (!c->marked_for_close) {
  1672. tor_assert(or_circ->rend_splice);
  1673. tor_assert(or_circ->rend_splice->rend_splice == or_circ);
  1674. }
  1675. tor_assert(or_circ->rend_splice != or_circ);
  1676. } else {
  1677. tor_assert(!or_circ || !or_circ->rend_splice);
  1678. }
  1679. }