relay.c 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2010, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file relay.c
  8. * \brief Handle relay cell encryption/decryption, plus packaging and
  9. * receiving from circuits, plus queuing on circuits.
  10. **/
  11. #include <math.h>
  12. #include "or.h"
  13. #include "buffers.h"
  14. #include "circuitbuild.h"
  15. #include "circuitlist.h"
  16. #include "config.h"
  17. #include "geoip.h"
  18. #include "mempool.h"
  19. #include "rendcommon.h"
  20. #include "routerlist.h"
  21. static int relay_crypt(circuit_t *circ, cell_t *cell,
  22. cell_direction_t cell_direction,
  23. crypt_path_t **layer_hint, char *recognized);
  24. static edge_connection_t *relay_lookup_conn(circuit_t *circ, cell_t *cell,
  25. cell_direction_t cell_direction,
  26. crypt_path_t *layer_hint);
  27. static int
  28. connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
  29. edge_connection_t *conn,
  30. crypt_path_t *layer_hint);
  31. static void
  32. circuit_consider_sending_sendme(circuit_t *circ, crypt_path_t *layer_hint);
  33. static void
  34. circuit_resume_edge_reading(circuit_t *circ, crypt_path_t *layer_hint);
  35. static int
  36. circuit_resume_edge_reading_helper(edge_connection_t *conn,
  37. circuit_t *circ,
  38. crypt_path_t *layer_hint);
  39. static int
  40. circuit_consider_stop_edge_reading(circuit_t *circ, crypt_path_t *layer_hint);
  41. /** Cache the current hi-res time; the cache gets reset when libevent
  42. * calls us. */
  43. static struct timeval cached_time_hires = {0, 0};
  44. static void
  45. tor_gettimeofday_cached(struct timeval *tv)
  46. {
  47. if (cached_time_hires.tv_sec == 0) {
  48. tor_gettimeofday(&cached_time_hires);
  49. }
  50. *tv = cached_time_hires;
  51. }
  52. void
  53. tor_gettimeofday_cache_clear(void)
  54. {
  55. cached_time_hires.tv_sec = 0;
  56. }
  57. /** Stats: how many relay cells have originated at this hop, or have
  58. * been relayed onward (not recognized at this hop)?
  59. */
  60. uint64_t stats_n_relay_cells_relayed = 0;
  61. /** Stats: how many relay cells have been delivered to streams at this
  62. * hop?
  63. */
  64. uint64_t stats_n_relay_cells_delivered = 0;
  65. /** Update digest from the payload of cell. Assign integrity part to
  66. * cell.
  67. */
  68. static void
  69. relay_set_digest(crypto_digest_env_t *digest, cell_t *cell)
  70. {
  71. char integrity[4];
  72. relay_header_t rh;
  73. crypto_digest_add_bytes(digest, cell->payload, CELL_PAYLOAD_SIZE);
  74. crypto_digest_get_digest(digest, integrity, 4);
  75. // log_fn(LOG_DEBUG,"Putting digest of %u %u %u %u into relay cell.",
  76. // integrity[0], integrity[1], integrity[2], integrity[3]);
  77. relay_header_unpack(&rh, cell->payload);
  78. memcpy(rh.integrity, integrity, 4);
  79. relay_header_pack(cell->payload, &rh);
  80. }
  81. /** Does the digest for this circuit indicate that this cell is for us?
  82. *
  83. * Update digest from the payload of cell (with the integrity part set
  84. * to 0). If the integrity part is valid, return 1, else restore digest
  85. * and cell to their original state and return 0.
  86. */
  87. static int
  88. relay_digest_matches(crypto_digest_env_t *digest, cell_t *cell)
  89. {
  90. char received_integrity[4], calculated_integrity[4];
  91. relay_header_t rh;
  92. crypto_digest_env_t *backup_digest=NULL;
  93. backup_digest = crypto_digest_dup(digest);
  94. relay_header_unpack(&rh, cell->payload);
  95. memcpy(received_integrity, rh.integrity, 4);
  96. memset(rh.integrity, 0, 4);
  97. relay_header_pack(cell->payload, &rh);
  98. // log_fn(LOG_DEBUG,"Reading digest of %u %u %u %u from relay cell.",
  99. // received_integrity[0], received_integrity[1],
  100. // received_integrity[2], received_integrity[3]);
  101. crypto_digest_add_bytes(digest, cell->payload, CELL_PAYLOAD_SIZE);
  102. crypto_digest_get_digest(digest, calculated_integrity, 4);
  103. if (memcmp(received_integrity, calculated_integrity, 4)) {
  104. // log_fn(LOG_INFO,"Recognized=0 but bad digest. Not recognizing.");
  105. // (%d vs %d).", received_integrity, calculated_integrity);
  106. /* restore digest to its old form */
  107. crypto_digest_assign(digest, backup_digest);
  108. /* restore the relay header */
  109. memcpy(rh.integrity, received_integrity, 4);
  110. relay_header_pack(cell->payload, &rh);
  111. crypto_free_digest_env(backup_digest);
  112. return 0;
  113. }
  114. crypto_free_digest_env(backup_digest);
  115. return 1;
  116. }
  117. /** Apply <b>cipher</b> to CELL_PAYLOAD_SIZE bytes of <b>in</b>
  118. * (in place).
  119. *
  120. * If <b>encrypt_mode</b> is 1 then encrypt, else decrypt.
  121. *
  122. * Return -1 if the crypto fails, else return 0.
  123. */
  124. static int
  125. relay_crypt_one_payload(crypto_cipher_env_t *cipher, char *in,
  126. int encrypt_mode)
  127. {
  128. int r;
  129. (void)encrypt_mode;
  130. r = crypto_cipher_crypt_inplace(cipher, in, CELL_PAYLOAD_SIZE);
  131. if (r) {
  132. log_warn(LD_BUG,"Error during relay encryption");
  133. return -1;
  134. }
  135. return 0;
  136. }
  137. /** Receive a relay cell:
  138. * - Crypt it (encrypt if headed toward the origin or if we <b>are</b> the
  139. * origin; decrypt if we're headed toward the exit).
  140. * - Check if recognized (if exitward).
  141. * - If recognized and the digest checks out, then find if there's a stream
  142. * that the cell is intended for, and deliver it to the right
  143. * connection_edge.
  144. * - If not recognized, then we need to relay it: append it to the appropriate
  145. * cell_queue on <b>circ</b>.
  146. *
  147. * Return -<b>reason</b> on failure.
  148. */
  149. int
  150. circuit_receive_relay_cell(cell_t *cell, circuit_t *circ,
  151. cell_direction_t cell_direction)
  152. {
  153. or_connection_t *or_conn=NULL;
  154. crypt_path_t *layer_hint=NULL;
  155. char recognized=0;
  156. int reason;
  157. tor_assert(cell);
  158. tor_assert(circ);
  159. tor_assert(cell_direction == CELL_DIRECTION_OUT ||
  160. cell_direction == CELL_DIRECTION_IN);
  161. if (circ->marked_for_close)
  162. return 0;
  163. if (relay_crypt(circ, cell, cell_direction, &layer_hint, &recognized) < 0) {
  164. log_warn(LD_BUG,"relay crypt failed. Dropping connection.");
  165. return -END_CIRC_REASON_INTERNAL;
  166. }
  167. if (recognized) {
  168. edge_connection_t *conn = relay_lookup_conn(circ, cell, cell_direction,
  169. layer_hint);
  170. if (cell_direction == CELL_DIRECTION_OUT) {
  171. ++stats_n_relay_cells_delivered;
  172. log_debug(LD_OR,"Sending away from origin.");
  173. if ((reason=connection_edge_process_relay_cell(cell, circ, conn, NULL))
  174. < 0) {
  175. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  176. "connection_edge_process_relay_cell (away from origin) "
  177. "failed.");
  178. return reason;
  179. }
  180. }
  181. if (cell_direction == CELL_DIRECTION_IN) {
  182. ++stats_n_relay_cells_delivered;
  183. log_debug(LD_OR,"Sending to origin.");
  184. if ((reason = connection_edge_process_relay_cell(cell, circ, conn,
  185. layer_hint)) < 0) {
  186. log_warn(LD_OR,
  187. "connection_edge_process_relay_cell (at origin) failed.");
  188. return reason;
  189. }
  190. }
  191. return 0;
  192. }
  193. /* not recognized. pass it on. */
  194. if (cell_direction == CELL_DIRECTION_OUT) {
  195. cell->circ_id = circ->n_circ_id; /* switch it */
  196. or_conn = circ->n_conn;
  197. } else if (! CIRCUIT_IS_ORIGIN(circ)) {
  198. cell->circ_id = TO_OR_CIRCUIT(circ)->p_circ_id; /* switch it */
  199. or_conn = TO_OR_CIRCUIT(circ)->p_conn;
  200. } else {
  201. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  202. "Dropping unrecognized inbound cell on origin circuit.");
  203. return 0;
  204. }
  205. if (!or_conn) {
  206. // XXXX Can this splice stuff be done more cleanly?
  207. if (! CIRCUIT_IS_ORIGIN(circ) &&
  208. TO_OR_CIRCUIT(circ)->rend_splice &&
  209. cell_direction == CELL_DIRECTION_OUT) {
  210. or_circuit_t *splice = TO_OR_CIRCUIT(circ)->rend_splice;
  211. tor_assert(circ->purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED);
  212. tor_assert(splice->_base.purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED);
  213. cell->circ_id = splice->p_circ_id;
  214. cell->command = CELL_RELAY; /* can't be relay_early anyway */
  215. if ((reason = circuit_receive_relay_cell(cell, TO_CIRCUIT(splice),
  216. CELL_DIRECTION_IN)) < 0) {
  217. log_warn(LD_REND, "Error relaying cell across rendezvous; closing "
  218. "circuits");
  219. /* XXXX Do this here, or just return -1? */
  220. circuit_mark_for_close(circ, -reason);
  221. return reason;
  222. }
  223. return 0;
  224. }
  225. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  226. "Didn't recognize cell, but circ stops here! Closing circ.");
  227. return -END_CIRC_REASON_TORPROTOCOL;
  228. }
  229. log_debug(LD_OR,"Passing on unrecognized cell.");
  230. ++stats_n_relay_cells_relayed; /* XXXX no longer quite accurate {cells}
  231. * we might kill the circ before we relay
  232. * the cells. */
  233. append_cell_to_circuit_queue(circ, or_conn, cell, cell_direction);
  234. return 0;
  235. }
  236. /** Do the appropriate en/decryptions for <b>cell</b> arriving on
  237. * <b>circ</b> in direction <b>cell_direction</b>.
  238. *
  239. * If cell_direction == CELL_DIRECTION_IN:
  240. * - If we're at the origin (we're the OP), for hops 1..N,
  241. * decrypt cell. If recognized, stop.
  242. * - Else (we're not the OP), encrypt one hop. Cell is not recognized.
  243. *
  244. * If cell_direction == CELL_DIRECTION_OUT:
  245. * - decrypt one hop. Check if recognized.
  246. *
  247. * If cell is recognized, set *recognized to 1, and set
  248. * *layer_hint to the hop that recognized it.
  249. *
  250. * Return -1 to indicate that we should mark the circuit for close,
  251. * else return 0.
  252. */
  253. static int
  254. relay_crypt(circuit_t *circ, cell_t *cell, cell_direction_t cell_direction,
  255. crypt_path_t **layer_hint, char *recognized)
  256. {
  257. relay_header_t rh;
  258. tor_assert(circ);
  259. tor_assert(cell);
  260. tor_assert(recognized);
  261. tor_assert(cell_direction == CELL_DIRECTION_IN ||
  262. cell_direction == CELL_DIRECTION_OUT);
  263. if (cell_direction == CELL_DIRECTION_IN) {
  264. if (CIRCUIT_IS_ORIGIN(circ)) { /* We're at the beginning of the circuit.
  265. * We'll want to do layered decrypts. */
  266. crypt_path_t *thishop, *cpath = TO_ORIGIN_CIRCUIT(circ)->cpath;
  267. thishop = cpath;
  268. if (thishop->state != CPATH_STATE_OPEN) {
  269. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  270. "Relay cell before first created cell? Closing.");
  271. return -1;
  272. }
  273. do { /* Remember: cpath is in forward order, that is, first hop first. */
  274. tor_assert(thishop);
  275. if (relay_crypt_one_payload(thishop->b_crypto, cell->payload, 0) < 0)
  276. return -1;
  277. relay_header_unpack(&rh, cell->payload);
  278. if (rh.recognized == 0) {
  279. /* it's possibly recognized. have to check digest to be sure. */
  280. if (relay_digest_matches(thishop->b_digest, cell)) {
  281. *recognized = 1;
  282. *layer_hint = thishop;
  283. return 0;
  284. }
  285. }
  286. thishop = thishop->next;
  287. } while (thishop != cpath && thishop->state == CPATH_STATE_OPEN);
  288. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  289. "Incoming cell at client not recognized. Closing.");
  290. return -1;
  291. } else { /* we're in the middle. Just one crypt. */
  292. if (relay_crypt_one_payload(TO_OR_CIRCUIT(circ)->p_crypto,
  293. cell->payload, 1) < 0)
  294. return -1;
  295. // log_fn(LOG_DEBUG,"Skipping recognized check, because we're not "
  296. // "the client.");
  297. }
  298. } else /* cell_direction == CELL_DIRECTION_OUT */ {
  299. /* we're in the middle. Just one crypt. */
  300. if (relay_crypt_one_payload(TO_OR_CIRCUIT(circ)->n_crypto,
  301. cell->payload, 0) < 0)
  302. return -1;
  303. relay_header_unpack(&rh, cell->payload);
  304. if (rh.recognized == 0) {
  305. /* it's possibly recognized. have to check digest to be sure. */
  306. if (relay_digest_matches(TO_OR_CIRCUIT(circ)->n_digest, cell)) {
  307. *recognized = 1;
  308. return 0;
  309. }
  310. }
  311. }
  312. return 0;
  313. }
  314. /** Package a relay cell from an edge:
  315. * - Encrypt it to the right layer
  316. * - Append it to the appropriate cell_queue on <b>circ</b>.
  317. */
  318. static int
  319. circuit_package_relay_cell(cell_t *cell, circuit_t *circ,
  320. cell_direction_t cell_direction,
  321. crypt_path_t *layer_hint)
  322. {
  323. or_connection_t *conn; /* where to send the cell */
  324. if (cell_direction == CELL_DIRECTION_OUT) {
  325. crypt_path_t *thishop; /* counter for repeated crypts */
  326. conn = circ->n_conn;
  327. if (!CIRCUIT_IS_ORIGIN(circ) || !conn) {
  328. log_warn(LD_BUG,"outgoing relay cell has n_conn==NULL. Dropping.");
  329. return 0; /* just drop it */
  330. }
  331. relay_set_digest(layer_hint->f_digest, cell);
  332. thishop = layer_hint;
  333. /* moving from farthest to nearest hop */
  334. do {
  335. tor_assert(thishop);
  336. /* XXXX RD This is a bug, right? */
  337. log_debug(LD_OR,"crypting a layer of the relay cell.");
  338. if (relay_crypt_one_payload(thishop->f_crypto, cell->payload, 1) < 0) {
  339. return -1;
  340. }
  341. thishop = thishop->prev;
  342. } while (thishop != TO_ORIGIN_CIRCUIT(circ)->cpath->prev);
  343. } else { /* incoming cell */
  344. or_circuit_t *or_circ;
  345. if (CIRCUIT_IS_ORIGIN(circ)) {
  346. /* We should never package an _incoming_ cell from the circuit
  347. * origin; that means we messed up somewhere. */
  348. log_warn(LD_BUG,"incoming relay cell at origin circuit. Dropping.");
  349. assert_circuit_ok(circ);
  350. return 0; /* just drop it */
  351. }
  352. or_circ = TO_OR_CIRCUIT(circ);
  353. conn = or_circ->p_conn;
  354. relay_set_digest(or_circ->p_digest, cell);
  355. if (relay_crypt_one_payload(or_circ->p_crypto, cell->payload, 1) < 0)
  356. return -1;
  357. }
  358. ++stats_n_relay_cells_relayed;
  359. append_cell_to_circuit_queue(circ, conn, cell, cell_direction);
  360. return 0;
  361. }
  362. /** If cell's stream_id matches the stream_id of any conn that's
  363. * attached to circ, return that conn, else return NULL.
  364. */
  365. static edge_connection_t *
  366. relay_lookup_conn(circuit_t *circ, cell_t *cell,
  367. cell_direction_t cell_direction, crypt_path_t *layer_hint)
  368. {
  369. edge_connection_t *tmpconn;
  370. relay_header_t rh;
  371. relay_header_unpack(&rh, cell->payload);
  372. if (!rh.stream_id)
  373. return NULL;
  374. /* IN or OUT cells could have come from either direction, now
  375. * that we allow rendezvous *to* an OP.
  376. */
  377. if (CIRCUIT_IS_ORIGIN(circ)) {
  378. for (tmpconn = TO_ORIGIN_CIRCUIT(circ)->p_streams; tmpconn;
  379. tmpconn=tmpconn->next_stream) {
  380. if (rh.stream_id == tmpconn->stream_id &&
  381. !tmpconn->_base.marked_for_close &&
  382. tmpconn->cpath_layer == layer_hint) {
  383. log_debug(LD_APP,"found conn for stream %d.", rh.stream_id);
  384. return tmpconn;
  385. }
  386. }
  387. } else {
  388. for (tmpconn = TO_OR_CIRCUIT(circ)->n_streams; tmpconn;
  389. tmpconn=tmpconn->next_stream) {
  390. if (rh.stream_id == tmpconn->stream_id &&
  391. !tmpconn->_base.marked_for_close) {
  392. log_debug(LD_EXIT,"found conn for stream %d.", rh.stream_id);
  393. if (cell_direction == CELL_DIRECTION_OUT ||
  394. connection_edge_is_rendezvous_stream(tmpconn))
  395. return tmpconn;
  396. }
  397. }
  398. for (tmpconn = TO_OR_CIRCUIT(circ)->resolving_streams; tmpconn;
  399. tmpconn=tmpconn->next_stream) {
  400. if (rh.stream_id == tmpconn->stream_id &&
  401. !tmpconn->_base.marked_for_close) {
  402. log_debug(LD_EXIT,"found conn for stream %d.", rh.stream_id);
  403. return tmpconn;
  404. }
  405. }
  406. }
  407. return NULL; /* probably a begin relay cell */
  408. }
  409. /** Pack the relay_header_t host-order structure <b>src</b> into
  410. * network-order in the buffer <b>dest</b>. See tor-spec.txt for details
  411. * about the wire format.
  412. */
  413. void
  414. relay_header_pack(char *dest, const relay_header_t *src)
  415. {
  416. *(uint8_t*)(dest) = src->command;
  417. set_uint16(dest+1, htons(src->recognized));
  418. set_uint16(dest+3, htons(src->stream_id));
  419. memcpy(dest+5, src->integrity, 4);
  420. set_uint16(dest+9, htons(src->length));
  421. }
  422. /** Unpack the network-order buffer <b>src</b> into a host-order
  423. * relay_header_t structure <b>dest</b>.
  424. */
  425. void
  426. relay_header_unpack(relay_header_t *dest, const char *src)
  427. {
  428. dest->command = *(uint8_t*)(src);
  429. dest->recognized = ntohs(get_uint16(src+1));
  430. dest->stream_id = ntohs(get_uint16(src+3));
  431. memcpy(dest->integrity, src+5, 4);
  432. dest->length = ntohs(get_uint16(src+9));
  433. }
  434. /** Convert the relay <b>command</b> into a human-readable string. */
  435. static const char *
  436. relay_command_to_string(uint8_t command)
  437. {
  438. switch (command) {
  439. case RELAY_COMMAND_BEGIN: return "BEGIN";
  440. case RELAY_COMMAND_DATA: return "DATA";
  441. case RELAY_COMMAND_END: return "END";
  442. case RELAY_COMMAND_CONNECTED: return "CONNECTED";
  443. case RELAY_COMMAND_SENDME: return "SENDME";
  444. case RELAY_COMMAND_EXTEND: return "EXTEND";
  445. case RELAY_COMMAND_EXTENDED: return "EXTENDED";
  446. case RELAY_COMMAND_TRUNCATE: return "TRUNCATE";
  447. case RELAY_COMMAND_TRUNCATED: return "TRUNCATED";
  448. case RELAY_COMMAND_DROP: return "DROP";
  449. case RELAY_COMMAND_RESOLVE: return "RESOLVE";
  450. case RELAY_COMMAND_RESOLVED: return "RESOLVED";
  451. case RELAY_COMMAND_BEGIN_DIR: return "BEGIN_DIR";
  452. case RELAY_COMMAND_ESTABLISH_INTRO: return "ESTABLISH_INTRO";
  453. case RELAY_COMMAND_ESTABLISH_RENDEZVOUS: return "ESTABLISH_RENDEZVOUS";
  454. case RELAY_COMMAND_INTRODUCE1: return "INTRODUCE1";
  455. case RELAY_COMMAND_INTRODUCE2: return "INTRODUCE2";
  456. case RELAY_COMMAND_RENDEZVOUS1: return "RENDEZVOUS1";
  457. case RELAY_COMMAND_RENDEZVOUS2: return "RENDEZVOUS2";
  458. case RELAY_COMMAND_INTRO_ESTABLISHED: return "INTRO_ESTABLISHED";
  459. case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
  460. return "RENDEZVOUS_ESTABLISHED";
  461. case RELAY_COMMAND_INTRODUCE_ACK: return "INTRODUCE_ACK";
  462. default: return "(unrecognized)";
  463. }
  464. }
  465. /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and send
  466. * it onto the open circuit <b>circ</b>. <b>stream_id</b> is the ID on
  467. * <b>circ</b> for the stream that's sending the relay cell, or 0 if it's a
  468. * control cell. <b>cpath_layer</b> is NULL for OR->OP cells, or the
  469. * destination hop for OP->OR cells.
  470. *
  471. * If you can't send the cell, mark the circuit for close and return -1. Else
  472. * return 0.
  473. */
  474. int
  475. relay_send_command_from_edge(uint16_t stream_id, circuit_t *circ,
  476. uint8_t relay_command, const char *payload,
  477. size_t payload_len, crypt_path_t *cpath_layer)
  478. {
  479. cell_t cell;
  480. relay_header_t rh;
  481. cell_direction_t cell_direction;
  482. /* XXXX NM Split this function into a separate versions per circuit type? */
  483. tor_assert(circ);
  484. tor_assert(payload_len <= RELAY_PAYLOAD_SIZE);
  485. memset(&cell, 0, sizeof(cell_t));
  486. cell.command = CELL_RELAY;
  487. if (cpath_layer) {
  488. cell.circ_id = circ->n_circ_id;
  489. cell_direction = CELL_DIRECTION_OUT;
  490. } else if (! CIRCUIT_IS_ORIGIN(circ)) {
  491. cell.circ_id = TO_OR_CIRCUIT(circ)->p_circ_id;
  492. cell_direction = CELL_DIRECTION_IN;
  493. } else {
  494. return -1;
  495. }
  496. memset(&rh, 0, sizeof(rh));
  497. rh.command = relay_command;
  498. rh.stream_id = stream_id;
  499. rh.length = payload_len;
  500. relay_header_pack(cell.payload, &rh);
  501. if (payload_len)
  502. memcpy(cell.payload+RELAY_HEADER_SIZE, payload, payload_len);
  503. log_debug(LD_OR,"delivering %d cell %s.", relay_command,
  504. cell_direction == CELL_DIRECTION_OUT ? "forward" : "backward");
  505. /* If we are sending an END cell and this circuit is used for a tunneled
  506. * directory request, advance its state. */
  507. if (relay_command == RELAY_COMMAND_END && circ->dirreq_id)
  508. geoip_change_dirreq_state(circ->dirreq_id, DIRREQ_TUNNELED,
  509. DIRREQ_END_CELL_SENT);
  510. if (cell_direction == CELL_DIRECTION_OUT && circ->n_conn) {
  511. /* if we're using relaybandwidthrate, this conn wants priority */
  512. circ->n_conn->client_used = approx_time();
  513. }
  514. if (cell_direction == CELL_DIRECTION_OUT) {
  515. origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
  516. if (origin_circ->remaining_relay_early_cells > 0 &&
  517. (relay_command == RELAY_COMMAND_EXTEND ||
  518. (cpath_layer != origin_circ->cpath &&
  519. !CIRCUIT_PURPOSE_IS_ESTABLISHED_REND(circ->purpose)))) {
  520. /* If we've got any relay_early cells left, and we're sending
  521. * an extend cell or (we're not talking to the first hop and we're
  522. * not talking to a rendezvous circuit), use one of them.
  523. * Don't worry about the conn protocol version:
  524. * append_cell_to_circuit_queue will fix it up. */
  525. /* XXX For now, clients don't use RELAY_EARLY cells when sending
  526. * relay cells on rendezvous circuits. See bug 1038. Once no relays
  527. * (and thus no rendezvous points) are running 0.2.1.3-alpha through
  528. * 0.2.1.18, we can take out that exception. -RD */
  529. cell.command = CELL_RELAY_EARLY;
  530. --origin_circ->remaining_relay_early_cells;
  531. log_debug(LD_OR, "Sending a RELAY_EARLY cell; %d remaining.",
  532. (int)origin_circ->remaining_relay_early_cells);
  533. /* Memorize the command that is sent as RELAY_EARLY cell; helps debug
  534. * task 878. */
  535. origin_circ->relay_early_commands[
  536. origin_circ->relay_early_cells_sent++] = relay_command;
  537. } else if (relay_command == RELAY_COMMAND_EXTEND) {
  538. /* If no RELAY_EARLY cells can be sent over this circuit, log which
  539. * commands have been sent as RELAY_EARLY cells before; helps debug
  540. * task 878. */
  541. smartlist_t *commands_list = smartlist_create();
  542. int i = 0;
  543. char *commands = NULL;
  544. for (; i < origin_circ->relay_early_cells_sent; i++)
  545. smartlist_add(commands_list, (char *)
  546. relay_command_to_string(origin_circ->relay_early_commands[i]));
  547. commands = smartlist_join_strings(commands_list, ",", 0, NULL);
  548. log_warn(LD_BUG, "Uh-oh. We're sending a RELAY_COMMAND_EXTEND cell, "
  549. "but we have run out of RELAY_EARLY cells on that circuit. "
  550. "Commands sent before: %s", commands);
  551. tor_free(commands);
  552. smartlist_free(commands_list);
  553. }
  554. }
  555. if (circuit_package_relay_cell(&cell, circ, cell_direction, cpath_layer)
  556. < 0) {
  557. log_warn(LD_BUG,"circuit_package_relay_cell failed. Closing.");
  558. circuit_mark_for_close(circ, END_CIRC_REASON_INTERNAL);
  559. return -1;
  560. }
  561. return 0;
  562. }
  563. /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and
  564. * send it onto the open circuit <b>circ</b>. <b>fromconn</b> is the stream
  565. * that's sending the relay cell, or NULL if it's a control cell.
  566. * <b>cpath_layer</b> is NULL for OR->OP cells, or the destination hop
  567. * for OP->OR cells.
  568. *
  569. * If you can't send the cell, mark the circuit for close and
  570. * return -1. Else return 0.
  571. */
  572. int
  573. connection_edge_send_command(edge_connection_t *fromconn,
  574. uint8_t relay_command, const char *payload,
  575. size_t payload_len)
  576. {
  577. /* XXXX NM Split this function into a separate versions per circuit type? */
  578. circuit_t *circ;
  579. tor_assert(fromconn);
  580. circ = fromconn->on_circuit;
  581. if (fromconn->_base.marked_for_close) {
  582. log_warn(LD_BUG,
  583. "called on conn that's already marked for close at %s:%d.",
  584. fromconn->_base.marked_for_close_file,
  585. fromconn->_base.marked_for_close);
  586. return 0;
  587. }
  588. if (!circ) {
  589. if (fromconn->_base.type == CONN_TYPE_AP) {
  590. log_info(LD_APP,"no circ. Closing conn.");
  591. connection_mark_unattached_ap(fromconn, END_STREAM_REASON_INTERNAL);
  592. } else {
  593. log_info(LD_EXIT,"no circ. Closing conn.");
  594. fromconn->edge_has_sent_end = 1; /* no circ to send to */
  595. fromconn->end_reason = END_STREAM_REASON_INTERNAL;
  596. connection_mark_for_close(TO_CONN(fromconn));
  597. }
  598. return -1;
  599. }
  600. return relay_send_command_from_edge(fromconn->stream_id, circ,
  601. relay_command, payload,
  602. payload_len, fromconn->cpath_layer);
  603. }
  604. /** How many times will I retry a stream that fails due to DNS
  605. * resolve failure or misc error?
  606. */
  607. #define MAX_RESOLVE_FAILURES 3
  608. /** Return 1 if reason is something that you should retry if you
  609. * get the end cell before you've connected; else return 0. */
  610. static int
  611. edge_reason_is_retriable(int reason)
  612. {
  613. return reason == END_STREAM_REASON_HIBERNATING ||
  614. reason == END_STREAM_REASON_RESOURCELIMIT ||
  615. reason == END_STREAM_REASON_EXITPOLICY ||
  616. reason == END_STREAM_REASON_RESOLVEFAILED ||
  617. reason == END_STREAM_REASON_MISC;
  618. }
  619. /** Called when we receive an END cell on a stream that isn't open yet,
  620. * from the client side.
  621. * Arguments are as for connection_edge_process_relay_cell().
  622. */
  623. static int
  624. connection_ap_process_end_not_open(
  625. relay_header_t *rh, cell_t *cell, origin_circuit_t *circ,
  626. edge_connection_t *conn, crypt_path_t *layer_hint)
  627. {
  628. struct in_addr in;
  629. routerinfo_t *exitrouter;
  630. int reason = *(cell->payload+RELAY_HEADER_SIZE);
  631. int control_reason = reason | END_STREAM_REASON_FLAG_REMOTE;
  632. (void) layer_hint; /* unused */
  633. if (rh->length > 0 && edge_reason_is_retriable(reason) &&
  634. !connection_edge_is_rendezvous_stream(conn) /* avoid retry if rend */
  635. ) {
  636. log_info(LD_APP,"Address '%s' refused due to '%s'. Considering retrying.",
  637. safe_str(conn->socks_request->address),
  638. stream_end_reason_to_string(reason));
  639. exitrouter =
  640. router_get_by_digest(circ->build_state->chosen_exit->identity_digest);
  641. switch (reason) {
  642. case END_STREAM_REASON_EXITPOLICY:
  643. if (rh->length >= 5) {
  644. uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+1));
  645. int ttl;
  646. if (!addr) {
  647. log_info(LD_APP,"Address '%s' resolved to 0.0.0.0. Closing,",
  648. safe_str(conn->socks_request->address));
  649. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  650. return 0;
  651. }
  652. if (rh->length >= 9)
  653. ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+5));
  654. else
  655. ttl = -1;
  656. if (get_options()->ClientDNSRejectInternalAddresses &&
  657. is_internal_IP(addr, 0)) {
  658. log_info(LD_APP,"Address '%s' resolved to internal. Closing,",
  659. safe_str(conn->socks_request->address));
  660. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  661. return 0;
  662. }
  663. client_dns_set_addressmap(conn->socks_request->address, addr,
  664. conn->chosen_exit_name, ttl);
  665. }
  666. /* check if he *ought* to have allowed it */
  667. if (exitrouter &&
  668. (rh->length < 5 ||
  669. (tor_inet_aton(conn->socks_request->address, &in) &&
  670. !conn->chosen_exit_name))) {
  671. log_info(LD_APP,
  672. "Exitrouter '%s' seems to be more restrictive than its exit "
  673. "policy. Not using this router as exit for now.",
  674. exitrouter->nickname);
  675. policies_set_router_exitpolicy_to_reject_all(exitrouter);
  676. }
  677. /* rewrite it to an IP if we learned one. */
  678. if (addressmap_rewrite(conn->socks_request->address,
  679. sizeof(conn->socks_request->address),
  680. NULL)) {
  681. control_event_stream_status(conn, STREAM_EVENT_REMAP, 0);
  682. }
  683. if (conn->chosen_exit_optional ||
  684. conn->chosen_exit_retries) {
  685. /* stop wanting a specific exit */
  686. conn->chosen_exit_optional = 0;
  687. /* A non-zero chosen_exit_retries can happen if we set a
  688. * TrackHostExits for this address under a port that the exit
  689. * relay allows, but then try the same address with a different
  690. * port that it doesn't allow to exit. We shouldn't unregister
  691. * the mapping, since it is probably still wanted on the
  692. * original port. But now we give away to the exit relay that
  693. * we probably have a TrackHostExits on it. So be it. */
  694. conn->chosen_exit_retries = 0;
  695. tor_free(conn->chosen_exit_name); /* clears it */
  696. }
  697. if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
  698. return 0;
  699. /* else, conn will get closed below */
  700. break;
  701. case END_STREAM_REASON_CONNECTREFUSED:
  702. if (!conn->chosen_exit_optional)
  703. break; /* break means it'll close, below */
  704. /* Else fall through: expire this circuit, clear the
  705. * chosen_exit_name field, and try again. */
  706. case END_STREAM_REASON_RESOLVEFAILED:
  707. case END_STREAM_REASON_TIMEOUT:
  708. case END_STREAM_REASON_MISC:
  709. if (client_dns_incr_failures(conn->socks_request->address)
  710. < MAX_RESOLVE_FAILURES) {
  711. /* We haven't retried too many times; reattach the connection. */
  712. circuit_log_path(LOG_INFO,LD_APP,circ);
  713. tor_assert(circ->_base.timestamp_dirty);
  714. circ->_base.timestamp_dirty -= get_options()->MaxCircuitDirtiness;
  715. if (conn->chosen_exit_optional) {
  716. /* stop wanting a specific exit */
  717. conn->chosen_exit_optional = 0;
  718. tor_free(conn->chosen_exit_name); /* clears it */
  719. }
  720. if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
  721. return 0;
  722. /* else, conn will get closed below */
  723. } else {
  724. log_notice(LD_APP,
  725. "Have tried resolving or connecting to address '%s' "
  726. "at %d different places. Giving up.",
  727. safe_str(conn->socks_request->address),
  728. MAX_RESOLVE_FAILURES);
  729. /* clear the failures, so it will have a full try next time */
  730. client_dns_clear_failures(conn->socks_request->address);
  731. }
  732. break;
  733. case END_STREAM_REASON_HIBERNATING:
  734. case END_STREAM_REASON_RESOURCELIMIT:
  735. if (exitrouter) {
  736. policies_set_router_exitpolicy_to_reject_all(exitrouter);
  737. }
  738. if (conn->chosen_exit_optional) {
  739. /* stop wanting a specific exit */
  740. conn->chosen_exit_optional = 0;
  741. tor_free(conn->chosen_exit_name); /* clears it */
  742. }
  743. if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
  744. return 0;
  745. /* else, will close below */
  746. break;
  747. } /* end switch */
  748. log_info(LD_APP,"Giving up on retrying; conn can't be handled.");
  749. }
  750. log_info(LD_APP,
  751. "Edge got end (%s) before we're connected. Marking for close.",
  752. stream_end_reason_to_string(rh->length > 0 ? reason : -1));
  753. circuit_log_path(LOG_INFO,LD_APP,circ);
  754. /* need to test because of detach_retriable */
  755. if (!conn->_base.marked_for_close)
  756. connection_mark_unattached_ap(conn, control_reason);
  757. return 0;
  758. }
  759. /** Helper: change the socks_request-&gt;address field on conn to the
  760. * dotted-quad representation of <b>new_addr</b> (given in host order),
  761. * and send an appropriate REMAP event. */
  762. static void
  763. remap_event_helper(edge_connection_t *conn, uint32_t new_addr)
  764. {
  765. struct in_addr in;
  766. in.s_addr = htonl(new_addr);
  767. tor_inet_ntoa(&in, conn->socks_request->address,
  768. sizeof(conn->socks_request->address));
  769. control_event_stream_status(conn, STREAM_EVENT_REMAP,
  770. REMAP_STREAM_SOURCE_EXIT);
  771. }
  772. /** An incoming relay cell has arrived from circuit <b>circ</b> to
  773. * stream <b>conn</b>.
  774. *
  775. * The arguments here are the same as in
  776. * connection_edge_process_relay_cell() below; this function is called
  777. * from there when <b>conn</b> is defined and not in an open state.
  778. */
  779. static int
  780. connection_edge_process_relay_cell_not_open(
  781. relay_header_t *rh, cell_t *cell, circuit_t *circ,
  782. edge_connection_t *conn, crypt_path_t *layer_hint)
  783. {
  784. if (rh->command == RELAY_COMMAND_END) {
  785. if (CIRCUIT_IS_ORIGIN(circ) && conn->_base.type == CONN_TYPE_AP) {
  786. return connection_ap_process_end_not_open(rh, cell,
  787. TO_ORIGIN_CIRCUIT(circ), conn,
  788. layer_hint);
  789. } else {
  790. /* we just got an 'end', don't need to send one */
  791. conn->edge_has_sent_end = 1;
  792. conn->end_reason = *(cell->payload+RELAY_HEADER_SIZE) |
  793. END_STREAM_REASON_FLAG_REMOTE;
  794. connection_mark_for_close(TO_CONN(conn));
  795. return 0;
  796. }
  797. }
  798. if (conn->_base.type == CONN_TYPE_AP &&
  799. rh->command == RELAY_COMMAND_CONNECTED) {
  800. tor_assert(CIRCUIT_IS_ORIGIN(circ));
  801. if (conn->_base.state != AP_CONN_STATE_CONNECT_WAIT) {
  802. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  803. "Got 'connected' while not in state connect_wait. Dropping.");
  804. return 0;
  805. }
  806. conn->_base.state = AP_CONN_STATE_OPEN;
  807. log_info(LD_APP,"'connected' received after %d seconds.",
  808. (int)(time(NULL) - conn->_base.timestamp_lastread));
  809. if (rh->length >= 4) {
  810. uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE));
  811. int ttl;
  812. if (!addr || (get_options()->ClientDNSRejectInternalAddresses &&
  813. is_internal_IP(addr, 0))) {
  814. char buf[INET_NTOA_BUF_LEN];
  815. struct in_addr a;
  816. a.s_addr = htonl(addr);
  817. tor_inet_ntoa(&a, buf, sizeof(buf));
  818. log_info(LD_APP,
  819. "...but it claims the IP address was %s. Closing.", buf);
  820. connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
  821. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  822. return 0;
  823. }
  824. if (rh->length >= 8)
  825. ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+4));
  826. else
  827. ttl = -1;
  828. client_dns_set_addressmap(conn->socks_request->address, addr,
  829. conn->chosen_exit_name, ttl);
  830. remap_event_helper(conn, addr);
  831. }
  832. circuit_log_path(LOG_INFO,LD_APP,TO_ORIGIN_CIRCUIT(circ));
  833. /* don't send a socks reply to transparent conns */
  834. if (!conn->socks_request->has_finished)
  835. connection_ap_handshake_socks_reply(conn, NULL, 0, 0);
  836. /* Was it a linked dir conn? If so, a dir request just started to
  837. * fetch something; this could be a bootstrap status milestone. */
  838. log_debug(LD_APP, "considering");
  839. if (TO_CONN(conn)->linked_conn &&
  840. TO_CONN(conn)->linked_conn->type == CONN_TYPE_DIR) {
  841. connection_t *dirconn = TO_CONN(conn)->linked_conn;
  842. log_debug(LD_APP, "it is! %d", dirconn->purpose);
  843. switch (dirconn->purpose) {
  844. case DIR_PURPOSE_FETCH_CERTIFICATE:
  845. if (consensus_is_waiting_for_certs())
  846. control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_KEYS, 0);
  847. break;
  848. case DIR_PURPOSE_FETCH_CONSENSUS:
  849. control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_STATUS, 0);
  850. break;
  851. case DIR_PURPOSE_FETCH_SERVERDESC:
  852. control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_DESCRIPTORS,
  853. count_loading_descriptors_progress());
  854. break;
  855. }
  856. }
  857. /* handle anything that might have queued */
  858. if (connection_edge_package_raw_inbuf(conn, 1) < 0) {
  859. /* (We already sent an end cell if possible) */
  860. connection_mark_for_close(TO_CONN(conn));
  861. return 0;
  862. }
  863. return 0;
  864. }
  865. if (conn->_base.type == CONN_TYPE_AP &&
  866. rh->command == RELAY_COMMAND_RESOLVED) {
  867. int ttl;
  868. int answer_len;
  869. uint8_t answer_type;
  870. if (conn->_base.state != AP_CONN_STATE_RESOLVE_WAIT) {
  871. log_fn(LOG_PROTOCOL_WARN, LD_APP, "Got a 'resolved' cell while "
  872. "not in state resolve_wait. Dropping.");
  873. return 0;
  874. }
  875. tor_assert(SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command));
  876. answer_len = cell->payload[RELAY_HEADER_SIZE+1];
  877. if (rh->length < 2 || answer_len+2>rh->length) {
  878. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  879. "Dropping malformed 'resolved' cell");
  880. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  881. return 0;
  882. }
  883. answer_type = cell->payload[RELAY_HEADER_SIZE];
  884. if (rh->length >= answer_len+6)
  885. ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+
  886. 2+answer_len));
  887. else
  888. ttl = -1;
  889. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  890. uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+2));
  891. if (get_options()->ClientDNSRejectInternalAddresses &&
  892. is_internal_IP(addr, 0)) {
  893. char buf[INET_NTOA_BUF_LEN];
  894. struct in_addr a;
  895. a.s_addr = htonl(addr);
  896. tor_inet_ntoa(&a, buf, sizeof(buf));
  897. log_info(LD_APP,"Got a resolve with answer %s. Rejecting.", buf);
  898. connection_ap_handshake_socks_resolved(conn,
  899. RESOLVED_TYPE_ERROR_TRANSIENT,
  900. 0, NULL, 0, TIME_MAX);
  901. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  902. return 0;
  903. }
  904. }
  905. connection_ap_handshake_socks_resolved(conn,
  906. answer_type,
  907. cell->payload[RELAY_HEADER_SIZE+1], /*answer_len*/
  908. cell->payload+RELAY_HEADER_SIZE+2, /*answer*/
  909. ttl,
  910. -1);
  911. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  912. uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+2));
  913. remap_event_helper(conn, addr);
  914. }
  915. connection_mark_unattached_ap(conn,
  916. END_STREAM_REASON_DONE |
  917. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  918. return 0;
  919. }
  920. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  921. "Got an unexpected relay command %d, in state %d (%s). Dropping.",
  922. rh->command, conn->_base.state,
  923. conn_state_to_string(conn->_base.type, conn->_base.state));
  924. return 0; /* for forward compatibility, don't kill the circuit */
  925. // connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
  926. // connection_mark_for_close(conn);
  927. // return -1;
  928. }
  929. /** An incoming relay cell has arrived on circuit <b>circ</b>. If
  930. * <b>conn</b> is NULL this is a control cell, else <b>cell</b> is
  931. * destined for <b>conn</b>.
  932. *
  933. * If <b>layer_hint</b> is defined, then we're the origin of the
  934. * circuit, and it specifies the hop that packaged <b>cell</b>.
  935. *
  936. * Return -reason if you want to warn and tear down the circuit, else 0.
  937. */
  938. static int
  939. connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
  940. edge_connection_t *conn,
  941. crypt_path_t *layer_hint)
  942. {
  943. static int num_seen=0;
  944. relay_header_t rh;
  945. unsigned domain = layer_hint?LD_APP:LD_EXIT;
  946. int reason;
  947. tor_assert(cell);
  948. tor_assert(circ);
  949. relay_header_unpack(&rh, cell->payload);
  950. // log_fn(LOG_DEBUG,"command %d stream %d", rh.command, rh.stream_id);
  951. num_seen++;
  952. log_debug(domain, "Now seen %d relay cells here (command %d, stream %d).",
  953. num_seen, rh.command, rh.stream_id);
  954. if (rh.length > RELAY_PAYLOAD_SIZE) {
  955. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  956. "Relay cell length field too long. Closing circuit.");
  957. return - END_CIRC_REASON_TORPROTOCOL;
  958. }
  959. /* either conn is NULL, in which case we've got a control cell, or else
  960. * conn points to the recognized stream. */
  961. if (conn && !connection_state_is_open(TO_CONN(conn)))
  962. return connection_edge_process_relay_cell_not_open(
  963. &rh, cell, circ, conn, layer_hint);
  964. switch (rh.command) {
  965. case RELAY_COMMAND_DROP:
  966. // log_info(domain,"Got a relay-level padding cell. Dropping.");
  967. return 0;
  968. case RELAY_COMMAND_BEGIN:
  969. case RELAY_COMMAND_BEGIN_DIR:
  970. if (layer_hint &&
  971. circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
  972. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  973. "Relay begin request unsupported at AP. Dropping.");
  974. return 0;
  975. }
  976. if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED &&
  977. layer_hint != TO_ORIGIN_CIRCUIT(circ)->cpath->prev) {
  978. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  979. "Relay begin request to Hidden Service "
  980. "from intermediary node. Dropping.");
  981. return 0;
  982. }
  983. if (conn) {
  984. log_fn(LOG_PROTOCOL_WARN, domain,
  985. "Begin cell for known stream. Dropping.");
  986. return 0;
  987. }
  988. if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
  989. /* Assign this circuit and its app-ward OR connection a unique ID,
  990. * so that we can measure download times. The local edge and dir
  991. * connection will be assigned the same ID when they are created
  992. * and linked. */
  993. static uint64_t next_id = 0;
  994. circ->dirreq_id = ++next_id;
  995. TO_CONN(TO_OR_CIRCUIT(circ)->p_conn)->dirreq_id = circ->dirreq_id;
  996. }
  997. return connection_exit_begin_conn(cell, circ);
  998. case RELAY_COMMAND_DATA:
  999. ++stats_n_data_cells_received;
  1000. if (( layer_hint && --layer_hint->deliver_window < 0) ||
  1001. (!layer_hint && --circ->deliver_window < 0)) {
  1002. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1003. "(relay data) circ deliver_window below 0. Killing.");
  1004. connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
  1005. connection_mark_for_close(TO_CONN(conn));
  1006. return -END_CIRC_REASON_TORPROTOCOL;
  1007. }
  1008. log_debug(domain,"circ deliver_window now %d.", layer_hint ?
  1009. layer_hint->deliver_window : circ->deliver_window);
  1010. circuit_consider_sending_sendme(circ, layer_hint);
  1011. if (!conn) {
  1012. log_info(domain,"data cell dropped, unknown stream (streamid %d).",
  1013. rh.stream_id);
  1014. return 0;
  1015. }
  1016. if (--conn->deliver_window < 0) { /* is it below 0 after decrement? */
  1017. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1018. "(relay data) conn deliver_window below 0. Killing.");
  1019. return -END_CIRC_REASON_TORPROTOCOL;
  1020. }
  1021. stats_n_data_bytes_received += rh.length;
  1022. connection_write_to_buf(cell->payload + RELAY_HEADER_SIZE,
  1023. rh.length, TO_CONN(conn));
  1024. connection_edge_consider_sending_sendme(conn);
  1025. return 0;
  1026. case RELAY_COMMAND_END:
  1027. reason = rh.length > 0 ?
  1028. *(uint8_t *)(cell->payload+RELAY_HEADER_SIZE) : END_STREAM_REASON_MISC;
  1029. if (!conn) {
  1030. log_info(domain,"end cell (%s) dropped, unknown stream.",
  1031. stream_end_reason_to_string(reason));
  1032. return 0;
  1033. }
  1034. /* XXX add to this log_fn the exit node's nickname? */
  1035. log_info(domain,"%d: end cell (%s) for stream %d. Removing stream.",
  1036. conn->_base.s,
  1037. stream_end_reason_to_string(reason),
  1038. conn->stream_id);
  1039. if (conn->socks_request && !conn->socks_request->has_finished)
  1040. log_warn(LD_BUG,
  1041. "open stream hasn't sent socks answer yet? Closing.");
  1042. /* We just *got* an end; no reason to send one. */
  1043. conn->edge_has_sent_end = 1;
  1044. if (!conn->end_reason)
  1045. conn->end_reason = reason | END_STREAM_REASON_FLAG_REMOTE;
  1046. if (!conn->_base.marked_for_close) {
  1047. /* only mark it if not already marked. it's possible to
  1048. * get the 'end' right around when the client hangs up on us. */
  1049. connection_mark_for_close(TO_CONN(conn));
  1050. conn->_base.hold_open_until_flushed = 1;
  1051. }
  1052. return 0;
  1053. case RELAY_COMMAND_EXTEND:
  1054. if (conn) {
  1055. log_fn(LOG_PROTOCOL_WARN, domain,
  1056. "'extend' cell received for non-zero stream. Dropping.");
  1057. return 0;
  1058. }
  1059. return circuit_extend(cell, circ);
  1060. case RELAY_COMMAND_EXTENDED:
  1061. if (!layer_hint) {
  1062. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1063. "'extended' unsupported at non-origin. Dropping.");
  1064. return 0;
  1065. }
  1066. log_debug(domain,"Got an extended cell! Yay.");
  1067. if ((reason = circuit_finish_handshake(TO_ORIGIN_CIRCUIT(circ),
  1068. CELL_CREATED,
  1069. cell->payload+RELAY_HEADER_SIZE)) < 0) {
  1070. log_warn(domain,"circuit_finish_handshake failed.");
  1071. return reason;
  1072. }
  1073. if ((reason=circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ)))<0) {
  1074. log_info(domain,"circuit_send_next_onion_skin() failed.");
  1075. return reason;
  1076. }
  1077. return 0;
  1078. case RELAY_COMMAND_TRUNCATE:
  1079. if (layer_hint) {
  1080. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  1081. "'truncate' unsupported at origin. Dropping.");
  1082. return 0;
  1083. }
  1084. if (circ->n_conn) {
  1085. uint8_t trunc_reason = *(uint8_t*)(cell->payload + RELAY_HEADER_SIZE);
  1086. connection_or_send_destroy(circ->n_circ_id, circ->n_conn,
  1087. trunc_reason);
  1088. circuit_set_n_circid_orconn(circ, 0, NULL);
  1089. }
  1090. log_debug(LD_EXIT, "Processed 'truncate', replying.");
  1091. {
  1092. char payload[1];
  1093. payload[0] = (char)END_CIRC_REASON_REQUESTED;
  1094. relay_send_command_from_edge(0, circ, RELAY_COMMAND_TRUNCATED,
  1095. payload, sizeof(payload), NULL);
  1096. }
  1097. return 0;
  1098. case RELAY_COMMAND_TRUNCATED:
  1099. if (!layer_hint) {
  1100. log_fn(LOG_PROTOCOL_WARN, LD_EXIT,
  1101. "'truncated' unsupported at non-origin. Dropping.");
  1102. return 0;
  1103. }
  1104. circuit_truncated(TO_ORIGIN_CIRCUIT(circ), layer_hint);
  1105. return 0;
  1106. case RELAY_COMMAND_CONNECTED:
  1107. if (conn) {
  1108. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1109. "'connected' unsupported while open. Closing circ.");
  1110. return -END_CIRC_REASON_TORPROTOCOL;
  1111. }
  1112. log_info(domain,
  1113. "'connected' received, no conn attached anymore. Ignoring.");
  1114. return 0;
  1115. case RELAY_COMMAND_SENDME:
  1116. if (!conn) {
  1117. if (layer_hint) {
  1118. layer_hint->package_window += CIRCWINDOW_INCREMENT;
  1119. log_debug(LD_APP,"circ-level sendme at origin, packagewindow %d.",
  1120. layer_hint->package_window);
  1121. circuit_resume_edge_reading(circ, layer_hint);
  1122. } else {
  1123. circ->package_window += CIRCWINDOW_INCREMENT;
  1124. log_debug(LD_APP,
  1125. "circ-level sendme at non-origin, packagewindow %d.",
  1126. circ->package_window);
  1127. circuit_resume_edge_reading(circ, layer_hint);
  1128. }
  1129. return 0;
  1130. }
  1131. conn->package_window += STREAMWINDOW_INCREMENT;
  1132. log_debug(domain,"stream-level sendme, packagewindow now %d.",
  1133. conn->package_window);
  1134. connection_start_reading(TO_CONN(conn));
  1135. /* handle whatever might still be on the inbuf */
  1136. if (connection_edge_package_raw_inbuf(conn, 1) < 0) {
  1137. /* (We already sent an end cell if possible) */
  1138. connection_mark_for_close(TO_CONN(conn));
  1139. return 0;
  1140. }
  1141. return 0;
  1142. case RELAY_COMMAND_RESOLVE:
  1143. if (layer_hint) {
  1144. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  1145. "resolve request unsupported at AP; dropping.");
  1146. return 0;
  1147. } else if (conn) {
  1148. log_fn(LOG_PROTOCOL_WARN, domain,
  1149. "resolve request for known stream; dropping.");
  1150. return 0;
  1151. } else if (circ->purpose != CIRCUIT_PURPOSE_OR) {
  1152. log_fn(LOG_PROTOCOL_WARN, domain,
  1153. "resolve request on circ with purpose %d; dropping",
  1154. circ->purpose);
  1155. return 0;
  1156. }
  1157. connection_exit_begin_resolve(cell, TO_OR_CIRCUIT(circ));
  1158. return 0;
  1159. case RELAY_COMMAND_RESOLVED:
  1160. if (conn) {
  1161. log_fn(LOG_PROTOCOL_WARN, domain,
  1162. "'resolved' unsupported while open. Closing circ.");
  1163. return -END_CIRC_REASON_TORPROTOCOL;
  1164. }
  1165. log_info(domain,
  1166. "'resolved' received, no conn attached anymore. Ignoring.");
  1167. return 0;
  1168. case RELAY_COMMAND_ESTABLISH_INTRO:
  1169. case RELAY_COMMAND_ESTABLISH_RENDEZVOUS:
  1170. case RELAY_COMMAND_INTRODUCE1:
  1171. case RELAY_COMMAND_INTRODUCE2:
  1172. case RELAY_COMMAND_INTRODUCE_ACK:
  1173. case RELAY_COMMAND_RENDEZVOUS1:
  1174. case RELAY_COMMAND_RENDEZVOUS2:
  1175. case RELAY_COMMAND_INTRO_ESTABLISHED:
  1176. case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
  1177. rend_process_relay_cell(circ, layer_hint,
  1178. rh.command, rh.length,
  1179. cell->payload+RELAY_HEADER_SIZE);
  1180. return 0;
  1181. }
  1182. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1183. "Received unknown relay command %d. Perhaps the other side is using "
  1184. "a newer version of Tor? Dropping.",
  1185. rh.command);
  1186. return 0; /* for forward compatibility, don't kill the circuit */
  1187. }
  1188. /** How many relay_data cells have we built, ever? */
  1189. uint64_t stats_n_data_cells_packaged = 0;
  1190. /** How many bytes of data have we put in relay_data cells have we built,
  1191. * ever? This would be RELAY_PAYLOAD_SIZE*stats_n_data_cells_packaged if
  1192. * every relay cell we ever sent were completely full of data. */
  1193. uint64_t stats_n_data_bytes_packaged = 0;
  1194. /** How many relay_data cells have we received, ever? */
  1195. uint64_t stats_n_data_cells_received = 0;
  1196. /** How many bytes of data have we received relay_data cells, ever? This would
  1197. * be RELAY_PAYLOAD_SIZE*stats_n_data_cells_packaged if every relay cell we
  1198. * ever received were completely full of data. */
  1199. uint64_t stats_n_data_bytes_received = 0;
  1200. /** While conn->inbuf has an entire relay payload of bytes on it,
  1201. * and the appropriate package windows aren't empty, grab a cell
  1202. * and send it down the circuit.
  1203. *
  1204. * Return -1 (and send a RELAY_COMMAND_END cell if necessary) if conn should
  1205. * be marked for close, else return 0.
  1206. */
  1207. int
  1208. connection_edge_package_raw_inbuf(edge_connection_t *conn, int package_partial)
  1209. {
  1210. size_t amount_to_process, length;
  1211. char payload[CELL_PAYLOAD_SIZE];
  1212. circuit_t *circ;
  1213. unsigned domain = conn->cpath_layer ? LD_APP : LD_EXIT;
  1214. tor_assert(conn);
  1215. if (conn->_base.marked_for_close) {
  1216. log_warn(LD_BUG,
  1217. "called on conn that's already marked for close at %s:%d.",
  1218. conn->_base.marked_for_close_file, conn->_base.marked_for_close);
  1219. return 0;
  1220. }
  1221. repeat_connection_edge_package_raw_inbuf:
  1222. circ = circuit_get_by_edge_conn(conn);
  1223. if (!circ) {
  1224. log_info(domain,"conn has no circuit! Closing.");
  1225. conn->end_reason = END_STREAM_REASON_CANT_ATTACH;
  1226. return -1;
  1227. }
  1228. if (circuit_consider_stop_edge_reading(circ, conn->cpath_layer))
  1229. return 0;
  1230. if (conn->package_window <= 0) {
  1231. log_info(domain,"called with package_window %d. Skipping.",
  1232. conn->package_window);
  1233. connection_stop_reading(TO_CONN(conn));
  1234. return 0;
  1235. }
  1236. amount_to_process = buf_datalen(conn->_base.inbuf);
  1237. if (!amount_to_process)
  1238. return 0;
  1239. if (!package_partial && amount_to_process < RELAY_PAYLOAD_SIZE)
  1240. return 0;
  1241. if (amount_to_process > RELAY_PAYLOAD_SIZE) {
  1242. length = RELAY_PAYLOAD_SIZE;
  1243. } else {
  1244. length = amount_to_process;
  1245. }
  1246. stats_n_data_bytes_packaged += length;
  1247. stats_n_data_cells_packaged += 1;
  1248. connection_fetch_from_buf(payload, length, TO_CONN(conn));
  1249. log_debug(domain,"(%d) Packaging %d bytes (%d waiting).", conn->_base.s,
  1250. (int)length, (int)buf_datalen(conn->_base.inbuf));
  1251. if (connection_edge_send_command(conn, RELAY_COMMAND_DATA,
  1252. payload, length) < 0 )
  1253. /* circuit got marked for close, don't continue, don't need to mark conn */
  1254. return 0;
  1255. if (!conn->cpath_layer) { /* non-rendezvous exit */
  1256. tor_assert(circ->package_window > 0);
  1257. circ->package_window--;
  1258. } else { /* we're an AP, or an exit on a rendezvous circ */
  1259. tor_assert(conn->cpath_layer->package_window > 0);
  1260. conn->cpath_layer->package_window--;
  1261. }
  1262. if (--conn->package_window <= 0) { /* is it 0 after decrement? */
  1263. connection_stop_reading(TO_CONN(conn));
  1264. log_debug(domain,"conn->package_window reached 0.");
  1265. circuit_consider_stop_edge_reading(circ, conn->cpath_layer);
  1266. return 0; /* don't process the inbuf any more */
  1267. }
  1268. log_debug(domain,"conn->package_window is now %d",conn->package_window);
  1269. /* handle more if there's more, or return 0 if there isn't */
  1270. goto repeat_connection_edge_package_raw_inbuf;
  1271. }
  1272. /** Called when we've just received a relay data cell, or when
  1273. * we've just finished flushing all bytes to stream <b>conn</b>.
  1274. *
  1275. * If conn->outbuf is not too full, and our deliver window is
  1276. * low, send back a suitable number of stream-level sendme cells.
  1277. */
  1278. void
  1279. connection_edge_consider_sending_sendme(edge_connection_t *conn)
  1280. {
  1281. circuit_t *circ;
  1282. if (connection_outbuf_too_full(TO_CONN(conn)))
  1283. return;
  1284. circ = circuit_get_by_edge_conn(conn);
  1285. if (!circ) {
  1286. /* this can legitimately happen if the destroy has already
  1287. * arrived and torn down the circuit */
  1288. log_info(LD_APP,"No circuit associated with conn. Skipping.");
  1289. return;
  1290. }
  1291. while (conn->deliver_window <= STREAMWINDOW_START - STREAMWINDOW_INCREMENT) {
  1292. log_debug(conn->cpath_layer?LD_APP:LD_EXIT,
  1293. "Outbuf %d, Queuing stream sendme.",
  1294. (int)conn->_base.outbuf_flushlen);
  1295. conn->deliver_window += STREAMWINDOW_INCREMENT;
  1296. if (connection_edge_send_command(conn, RELAY_COMMAND_SENDME,
  1297. NULL, 0) < 0) {
  1298. log_warn(LD_APP,"connection_edge_send_command failed. Skipping.");
  1299. return; /* the circuit's closed, don't continue */
  1300. }
  1301. }
  1302. }
  1303. /** The circuit <b>circ</b> has received a circuit-level sendme
  1304. * (on hop <b>layer_hint</b>, if we're the OP). Go through all the
  1305. * attached streams and let them resume reading and packaging, if
  1306. * their stream windows allow it.
  1307. */
  1308. static void
  1309. circuit_resume_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
  1310. {
  1311. log_debug(layer_hint?LD_APP:LD_EXIT,"resuming");
  1312. if (CIRCUIT_IS_ORIGIN(circ))
  1313. circuit_resume_edge_reading_helper(TO_ORIGIN_CIRCUIT(circ)->p_streams,
  1314. circ, layer_hint);
  1315. else
  1316. circuit_resume_edge_reading_helper(TO_OR_CIRCUIT(circ)->n_streams,
  1317. circ, layer_hint);
  1318. }
  1319. /** A helper function for circuit_resume_edge_reading() above.
  1320. * The arguments are the same, except that <b>conn</b> is the head
  1321. * of a linked list of edge streams that should each be considered.
  1322. */
  1323. static int
  1324. circuit_resume_edge_reading_helper(edge_connection_t *conn,
  1325. circuit_t *circ,
  1326. crypt_path_t *layer_hint)
  1327. {
  1328. for ( ; conn; conn=conn->next_stream) {
  1329. if (conn->_base.marked_for_close)
  1330. continue;
  1331. if ((!layer_hint && conn->package_window > 0) ||
  1332. (layer_hint && conn->package_window > 0 &&
  1333. conn->cpath_layer == layer_hint)) {
  1334. connection_start_reading(TO_CONN(conn));
  1335. /* handle whatever might still be on the inbuf */
  1336. if (connection_edge_package_raw_inbuf(conn, 1)<0) {
  1337. /* (We already sent an end cell if possible) */
  1338. connection_mark_for_close(TO_CONN(conn));
  1339. continue;
  1340. }
  1341. /* If the circuit won't accept any more data, return without looking
  1342. * at any more of the streams. Any connections that should be stopped
  1343. * have already been stopped by connection_edge_package_raw_inbuf. */
  1344. if (circuit_consider_stop_edge_reading(circ, layer_hint))
  1345. return -1;
  1346. }
  1347. }
  1348. return 0;
  1349. }
  1350. /** Check if the package window for <b>circ</b> is empty (at
  1351. * hop <b>layer_hint</b> if it's defined).
  1352. *
  1353. * If yes, tell edge streams to stop reading and return 1.
  1354. * Else return 0.
  1355. */
  1356. static int
  1357. circuit_consider_stop_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
  1358. {
  1359. edge_connection_t *conn = NULL;
  1360. unsigned domain = layer_hint ? LD_APP : LD_EXIT;
  1361. if (!layer_hint) {
  1362. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  1363. log_debug(domain,"considering circ->package_window %d",
  1364. circ->package_window);
  1365. if (circ->package_window <= 0) {
  1366. log_debug(domain,"yes, not-at-origin. stopped.");
  1367. for (conn = or_circ->n_streams; conn; conn=conn->next_stream)
  1368. connection_stop_reading(TO_CONN(conn));
  1369. return 1;
  1370. }
  1371. return 0;
  1372. }
  1373. /* else, layer hint is defined, use it */
  1374. log_debug(domain,"considering layer_hint->package_window %d",
  1375. layer_hint->package_window);
  1376. if (layer_hint->package_window <= 0) {
  1377. log_debug(domain,"yes, at-origin. stopped.");
  1378. for (conn = TO_ORIGIN_CIRCUIT(circ)->p_streams; conn;
  1379. conn=conn->next_stream)
  1380. if (conn->cpath_layer == layer_hint)
  1381. connection_stop_reading(TO_CONN(conn));
  1382. return 1;
  1383. }
  1384. return 0;
  1385. }
  1386. /** Check if the deliver_window for circuit <b>circ</b> (at hop
  1387. * <b>layer_hint</b> if it's defined) is low enough that we should
  1388. * send a circuit-level sendme back down the circuit. If so, send
  1389. * enough sendmes that the window would be overfull if we sent any
  1390. * more.
  1391. */
  1392. static void
  1393. circuit_consider_sending_sendme(circuit_t *circ, crypt_path_t *layer_hint)
  1394. {
  1395. // log_fn(LOG_INFO,"Considering: layer_hint is %s",
  1396. // layer_hint ? "defined" : "null");
  1397. while ((layer_hint ? layer_hint->deliver_window : circ->deliver_window) <=
  1398. CIRCWINDOW_START - CIRCWINDOW_INCREMENT) {
  1399. log_debug(LD_CIRC,"Queuing circuit sendme.");
  1400. if (layer_hint)
  1401. layer_hint->deliver_window += CIRCWINDOW_INCREMENT;
  1402. else
  1403. circ->deliver_window += CIRCWINDOW_INCREMENT;
  1404. if (relay_send_command_from_edge(0, circ, RELAY_COMMAND_SENDME,
  1405. NULL, 0, layer_hint) < 0) {
  1406. log_warn(LD_CIRC,
  1407. "relay_send_command_from_edge failed. Circuit's closed.");
  1408. return; /* the circuit's closed, don't continue */
  1409. }
  1410. }
  1411. }
  1412. /** Stop reading on edge connections when we have this many cells
  1413. * waiting on the appropriate queue. */
  1414. #define CELL_QUEUE_HIGHWATER_SIZE 256
  1415. /** Start reading from edge connections again when we get down to this many
  1416. * cells. */
  1417. #define CELL_QUEUE_LOWWATER_SIZE 64
  1418. #ifdef ACTIVE_CIRCUITS_PARANOIA
  1419. #define assert_active_circuits_ok_paranoid(conn) \
  1420. assert_active_circuits_ok(conn)
  1421. #else
  1422. #define assert_active_circuits_ok_paranoid(conn)
  1423. #endif
  1424. /** The total number of cells we have allocated from the memory pool. */
  1425. static int total_cells_allocated = 0;
  1426. /** A memory pool to allocate packed_cell_t objects. */
  1427. static mp_pool_t *cell_pool = NULL;
  1428. /** Memory pool to allocate insertion_time_elem_t objects used for cell
  1429. * statistics. */
  1430. static mp_pool_t *it_pool = NULL;
  1431. /** Allocate structures to hold cells. */
  1432. void
  1433. init_cell_pool(void)
  1434. {
  1435. tor_assert(!cell_pool);
  1436. cell_pool = mp_pool_new(sizeof(packed_cell_t), 128*1024);
  1437. }
  1438. /** Free all storage used to hold cells (and insertion times if we measure
  1439. * cell statistics). */
  1440. void
  1441. free_cell_pool(void)
  1442. {
  1443. /* Maybe we haven't called init_cell_pool yet; need to check for it. */
  1444. if (cell_pool) {
  1445. mp_pool_destroy(cell_pool);
  1446. cell_pool = NULL;
  1447. }
  1448. if (it_pool) {
  1449. mp_pool_destroy(it_pool);
  1450. it_pool = NULL;
  1451. }
  1452. }
  1453. /** Free excess storage in cell pool. */
  1454. void
  1455. clean_cell_pool(void)
  1456. {
  1457. tor_assert(cell_pool);
  1458. mp_pool_clean(cell_pool, 0, 1);
  1459. }
  1460. /** Release storage held by <b>cell</b>. */
  1461. static INLINE void
  1462. packed_cell_free_unchecked(packed_cell_t *cell)
  1463. {
  1464. --total_cells_allocated;
  1465. mp_pool_release(cell);
  1466. }
  1467. /** Allocate and return a new packed_cell_t. */
  1468. static INLINE packed_cell_t *
  1469. packed_cell_alloc(void)
  1470. {
  1471. ++total_cells_allocated;
  1472. return mp_pool_get(cell_pool);
  1473. }
  1474. /** Log current statistics for cell pool allocation at log level
  1475. * <b>severity</b>. */
  1476. void
  1477. dump_cell_pool_usage(int severity)
  1478. {
  1479. circuit_t *c;
  1480. int n_circs = 0;
  1481. int n_cells = 0;
  1482. for (c = _circuit_get_global_list(); c; c = c->next) {
  1483. n_cells += c->n_conn_cells.n;
  1484. if (!CIRCUIT_IS_ORIGIN(c))
  1485. n_cells += TO_OR_CIRCUIT(c)->p_conn_cells.n;
  1486. ++n_circs;
  1487. }
  1488. log(severity, LD_MM, "%d cells allocated on %d circuits. %d cells leaked.",
  1489. n_cells, n_circs, total_cells_allocated - n_cells);
  1490. mp_pool_log_status(cell_pool, severity);
  1491. }
  1492. /** Allocate a new copy of packed <b>cell</b>. */
  1493. static INLINE packed_cell_t *
  1494. packed_cell_copy(const cell_t *cell)
  1495. {
  1496. packed_cell_t *c = packed_cell_alloc();
  1497. cell_pack(c, cell);
  1498. c->next = NULL;
  1499. return c;
  1500. }
  1501. /** Append <b>cell</b> to the end of <b>queue</b>. */
  1502. void
  1503. cell_queue_append(cell_queue_t *queue, packed_cell_t *cell)
  1504. {
  1505. if (queue->tail) {
  1506. tor_assert(!queue->tail->next);
  1507. queue->tail->next = cell;
  1508. } else {
  1509. queue->head = cell;
  1510. }
  1511. queue->tail = cell;
  1512. cell->next = NULL;
  1513. ++queue->n;
  1514. }
  1515. /** Append a newly allocated copy of <b>cell</b> to the end of <b>queue</b> */
  1516. void
  1517. cell_queue_append_packed_copy(cell_queue_t *queue, const cell_t *cell)
  1518. {
  1519. packed_cell_t *copy = packed_cell_copy(cell);
  1520. /* Remember the time when this cell was put in the queue. */
  1521. if (get_options()->CellStatistics) {
  1522. struct timeval now;
  1523. uint32_t added;
  1524. insertion_time_queue_t *it_queue = queue->insertion_times;
  1525. if (!it_pool)
  1526. it_pool = mp_pool_new(sizeof(insertion_time_elem_t), 1024);
  1527. tor_gettimeofday_cached(&now);
  1528. #define SECONDS_IN_A_DAY 86400L
  1529. added = (uint32_t)(((now.tv_sec % SECONDS_IN_A_DAY) * 100L)
  1530. + ((uint32_t)now.tv_usec / (uint32_t)10000L));
  1531. if (!it_queue) {
  1532. it_queue = tor_malloc_zero(sizeof(insertion_time_queue_t));
  1533. queue->insertion_times = it_queue;
  1534. }
  1535. if (it_queue->last && it_queue->last->insertion_time == added) {
  1536. it_queue->last->counter++;
  1537. } else {
  1538. insertion_time_elem_t *elem = mp_pool_get(it_pool);
  1539. elem->next = NULL;
  1540. elem->insertion_time = added;
  1541. elem->counter = 1;
  1542. if (it_queue->last) {
  1543. it_queue->last->next = elem;
  1544. it_queue->last = elem;
  1545. } else {
  1546. it_queue->first = it_queue->last = elem;
  1547. }
  1548. }
  1549. }
  1550. cell_queue_append(queue, copy);
  1551. }
  1552. /** Remove and free every cell in <b>queue</b>. */
  1553. void
  1554. cell_queue_clear(cell_queue_t *queue)
  1555. {
  1556. packed_cell_t *cell, *next;
  1557. cell = queue->head;
  1558. while (cell) {
  1559. next = cell->next;
  1560. packed_cell_free_unchecked(cell);
  1561. cell = next;
  1562. }
  1563. queue->head = queue->tail = NULL;
  1564. queue->n = 0;
  1565. if (queue->insertion_times) {
  1566. while (queue->insertion_times->first) {
  1567. insertion_time_elem_t *elem = queue->insertion_times->first;
  1568. queue->insertion_times->first = elem->next;
  1569. mp_pool_release(elem);
  1570. }
  1571. tor_free(queue->insertion_times);
  1572. }
  1573. }
  1574. /** Extract and return the cell at the head of <b>queue</b>; return NULL if
  1575. * <b>queue</b> is empty. */
  1576. static INLINE packed_cell_t *
  1577. cell_queue_pop(cell_queue_t *queue)
  1578. {
  1579. packed_cell_t *cell = queue->head;
  1580. if (!cell)
  1581. return NULL;
  1582. queue->head = cell->next;
  1583. if (cell == queue->tail) {
  1584. tor_assert(!queue->head);
  1585. queue->tail = NULL;
  1586. }
  1587. --queue->n;
  1588. return cell;
  1589. }
  1590. /** Return a pointer to the "next_active_on_{n,p}_conn" pointer of <b>circ</b>,
  1591. * depending on whether <b>conn</b> matches n_conn or p_conn. */
  1592. static INLINE circuit_t **
  1593. next_circ_on_conn_p(circuit_t *circ, or_connection_t *conn)
  1594. {
  1595. tor_assert(circ);
  1596. tor_assert(conn);
  1597. if (conn == circ->n_conn) {
  1598. return &circ->next_active_on_n_conn;
  1599. } else {
  1600. or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
  1601. tor_assert(conn == orcirc->p_conn);
  1602. return &orcirc->next_active_on_p_conn;
  1603. }
  1604. }
  1605. /** Return a pointer to the "prev_active_on_{n,p}_conn" pointer of <b>circ</b>,
  1606. * depending on whether <b>conn</b> matches n_conn or p_conn. */
  1607. static INLINE circuit_t **
  1608. prev_circ_on_conn_p(circuit_t *circ, or_connection_t *conn)
  1609. {
  1610. tor_assert(circ);
  1611. tor_assert(conn);
  1612. if (conn == circ->n_conn) {
  1613. return &circ->prev_active_on_n_conn;
  1614. } else {
  1615. or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
  1616. tor_assert(conn == orcirc->p_conn);
  1617. return &orcirc->prev_active_on_p_conn;
  1618. }
  1619. }
  1620. /** Helper for sorting cell_ewma_t values in their priority queue. */
  1621. static int
  1622. compare_cell_ewma_counts(const void *p1, const void *p2)
  1623. {
  1624. const cell_ewma_t *e1=p1, *e2=p2;
  1625. if (e1->cell_count < e2->cell_count)
  1626. return -1;
  1627. else if (e1->cell_count > e2->cell_count)
  1628. return 1;
  1629. else
  1630. return 0;
  1631. }
  1632. /** Given a cell_ewma_t, return a pointer to the circuit containing it. */
  1633. static circuit_t *
  1634. cell_ewma_to_circuit(cell_ewma_t *ewma)
  1635. {
  1636. if (ewma->is_for_p_conn) {
  1637. /* This is an or_circuit_t's p_cell_ewma. */
  1638. or_circuit_t *orcirc = SUBTYPE_P(ewma, or_circuit_t, p_cell_ewma);
  1639. return TO_CIRCUIT(orcirc);
  1640. } else {
  1641. /* This is some circuit's n_cell_ewma. */
  1642. return SUBTYPE_P(ewma, circuit_t, n_cell_ewma);
  1643. }
  1644. }
  1645. /* ==== Functions for scaling cell_ewma_t ====
  1646. When choosing which cells to relay first, we favor circuits that have been
  1647. quiet recently. This gives better latency on connections that aren't
  1648. pushing lots of data, and makes the network feel more interactive.
  1649. Conceptually, we take an exponentially weighted mean average of the number
  1650. of cells a circuit has sent, and allow active circuits (those with cells to
  1651. relay) to send cells in reverse order of their exponentially-weighted mean
  1652. average (EWMA) cell count. [That is, a cell sent N seconds ago 'counts'
  1653. F^N times as much as a cell sent now, for 0<F<1.0, and we favor the
  1654. circuit that has sent the fewest cells]
  1655. If 'double' had infinite precision, we could do this simply by counting a
  1656. cell sent at startup as having weight 1.0, and a cell sent N seconds later
  1657. as having weight F^-N. This way, we would never need to re-scale
  1658. any already-sent cells.
  1659. To prevent double from overflowing, we could count a cell sent now as
  1660. having weight 1.0 and a cell sent N seconds ago as having weight F^N.
  1661. This, however, would mean we'd need to re-scale *ALL* old circuits every
  1662. time we wanted to send a cell.
  1663. So as a compromise, we divide time into 'ticks' (currently, 10-second
  1664. increments) and say that a cell sent at the start of a current tick is
  1665. worth 1.0, a cell sent N seconds before the start of the current tick is
  1666. worth F^N, and a cell sent N seconds after the start of the current tick is
  1667. worth F^-N. This way we don't overflow, and we don't need to constantly
  1668. rescale.
  1669. */
  1670. /** How long does a tick last (seconds)? */
  1671. #define EWMA_TICK_LEN 10
  1672. /** The default per-tick scale factor, if it hasn't been overridden by a
  1673. * consensus or a configuration setting. zero means "disabled". */
  1674. #define EWMA_DEFAULT_HALFLIFE 0.0
  1675. /** Given a timeval <b>now</b>, compute the cell_ewma tick in which it occurs
  1676. * and the fraction of the tick that has elapsed between the start of the tick
  1677. * and <b>now</b>. Return the former and store the latter in
  1678. * *<b>remainder_out</b>.
  1679. *
  1680. * These tick values are not meant to be shared between Tor instances, or used
  1681. * for other purposes. */
  1682. static unsigned
  1683. cell_ewma_tick_from_timeval(const struct timeval *now,
  1684. double *remainder_out)
  1685. {
  1686. unsigned res = (unsigned) (now->tv_sec / EWMA_TICK_LEN);
  1687. /* rem */
  1688. double rem = (now->tv_sec % EWMA_TICK_LEN) +
  1689. ((double)(now->tv_usec)) / 1.0e6;
  1690. *remainder_out = rem / EWMA_TICK_LEN;
  1691. return res;
  1692. }
  1693. /** Compute and return the current cell_ewma tick. */
  1694. unsigned
  1695. cell_ewma_get_tick(void)
  1696. {
  1697. return ((unsigned)approx_time() / EWMA_TICK_LEN);
  1698. }
  1699. /** The per-tick scale factor to be used when computing cell-count EWMA
  1700. * values. (A cell sent N ticks before the start of the current tick
  1701. * has value ewma_scale_factor ** N.)
  1702. */
  1703. static double ewma_scale_factor = 0.1;
  1704. static int ewma_enabled = 0;
  1705. #define EPSILON 0.00001
  1706. #define LOG_ONEHALF -0.69314718055994529
  1707. /** Adjust the global cell scale factor based on <b>options</b> */
  1708. void
  1709. cell_ewma_set_scale_factor(or_options_t *options, networkstatus_t *consensus)
  1710. {
  1711. int32_t halflife_ms;
  1712. double halflife;
  1713. const char *source;
  1714. if (options && options->CircuitPriorityHalflife >= -EPSILON) {
  1715. halflife = options->CircuitPriorityHalflife;
  1716. source = "CircuitPriorityHalflife in configuration";
  1717. } else if (consensus &&
  1718. (halflife_ms = networkstatus_get_param(
  1719. consensus, "CircuitPriorityHalflifeMsec", -1)) >= 0) {
  1720. halflife = ((double)halflife_ms)/1000.0;
  1721. source = "CircuitPriorityHalflifeMsec in consensus";
  1722. } else {
  1723. halflife = EWMA_DEFAULT_HALFLIFE;
  1724. source = "Default value";
  1725. }
  1726. if (halflife <= EPSILON) {
  1727. /* The cell EWMA algorithm is disabled. */
  1728. ewma_scale_factor = 0.1;
  1729. ewma_enabled = 0;
  1730. log_info(LD_OR,
  1731. "Disabled cell_ewma algorithm because of value in %s",
  1732. source);
  1733. } else {
  1734. /* convert halflife into halflife-per-tick. */
  1735. halflife /= EWMA_TICK_LEN;
  1736. /* compute per-tick scale factor. */
  1737. ewma_scale_factor = exp( LOG_ONEHALF / halflife );
  1738. ewma_enabled = 1;
  1739. log_info(LD_OR,
  1740. "Enabled cell_ewma algorithm because of value in %s; "
  1741. "scale factor is %lf per %d seconds",
  1742. source, ewma_scale_factor, EWMA_TICK_LEN);
  1743. }
  1744. }
  1745. /** Return the multiplier necessary to convert the value of a cell sent in
  1746. * 'from_tick' to one sent in 'to_tick'. */
  1747. static INLINE double
  1748. get_scale_factor(unsigned from_tick, unsigned to_tick)
  1749. {
  1750. /* This math can wrap around, but that's okay: unsigned overflow is
  1751. well-defined */
  1752. int diff = (int)(to_tick - from_tick);
  1753. return pow(ewma_scale_factor, diff);
  1754. }
  1755. /** Adjust the cell count of <b>ewma</b> so that it is scaled with respect to
  1756. * <b>cur_tick</b> */
  1757. static void
  1758. scale_single_cell_ewma(cell_ewma_t *ewma, unsigned cur_tick)
  1759. {
  1760. double factor = get_scale_factor(ewma->last_adjusted_tick, cur_tick);
  1761. ewma->cell_count *= factor;
  1762. ewma->last_adjusted_tick = cur_tick;
  1763. }
  1764. /** Adjust the cell count of every active circuit on <b>conn</b> so
  1765. * that they are scaled with respect to <b>cur_tick</b> */
  1766. static void
  1767. scale_active_circuits(or_connection_t *conn, unsigned cur_tick)
  1768. {
  1769. double factor = get_scale_factor(
  1770. conn->active_circuit_pqueue_last_recalibrated,
  1771. cur_tick);
  1772. /** Ordinarily it isn't okay to change the value of an element in a heap,
  1773. * but it's okay here, since we are preserving the order. */
  1774. SMARTLIST_FOREACH(conn->active_circuit_pqueue, cell_ewma_t *, e, {
  1775. tor_assert(e->last_adjusted_tick ==
  1776. conn->active_circuit_pqueue_last_recalibrated);
  1777. e->cell_count *= factor;
  1778. e->last_adjusted_tick = cur_tick;
  1779. });
  1780. conn->active_circuit_pqueue_last_recalibrated = cur_tick;
  1781. }
  1782. /** Rescale <b>ewma</b> to the same scale as <b>conn</b>, and add it to
  1783. * <b>conn</b>'s priority queue of active circuits */
  1784. static void
  1785. add_cell_ewma_to_conn(or_connection_t *conn, cell_ewma_t *ewma)
  1786. {
  1787. tor_assert(ewma->heap_index == -1);
  1788. scale_single_cell_ewma(ewma,
  1789. conn->active_circuit_pqueue_last_recalibrated);
  1790. smartlist_pqueue_add(conn->active_circuit_pqueue,
  1791. compare_cell_ewma_counts,
  1792. STRUCT_OFFSET(cell_ewma_t, heap_index),
  1793. ewma);
  1794. }
  1795. /** Remove <b>ewma</b> from <b>conn</b>'s priority queue of active circuits */
  1796. static void
  1797. remove_cell_ewma_from_conn(or_connection_t *conn, cell_ewma_t *ewma)
  1798. {
  1799. tor_assert(ewma->heap_index != -1);
  1800. smartlist_pqueue_remove(conn->active_circuit_pqueue,
  1801. compare_cell_ewma_counts,
  1802. STRUCT_OFFSET(cell_ewma_t, heap_index),
  1803. ewma);
  1804. }
  1805. /** Remove and return the first cell_ewma_t from conn's priority queue of
  1806. * active circuits. Requires that the priority queue is nonempty. */
  1807. static cell_ewma_t *
  1808. pop_first_cell_ewma_from_conn(or_connection_t *conn)
  1809. {
  1810. return smartlist_pqueue_pop(conn->active_circuit_pqueue,
  1811. compare_cell_ewma_counts,
  1812. STRUCT_OFFSET(cell_ewma_t, heap_index));
  1813. }
  1814. /** Add <b>circ</b> to the list of circuits with pending cells on
  1815. * <b>conn</b>. No effect if <b>circ</b> is already linked. */
  1816. void
  1817. make_circuit_active_on_conn(circuit_t *circ, or_connection_t *conn)
  1818. {
  1819. circuit_t **nextp = next_circ_on_conn_p(circ, conn);
  1820. circuit_t **prevp = prev_circ_on_conn_p(circ, conn);
  1821. if (*nextp && *prevp) {
  1822. /* Already active. */
  1823. return;
  1824. }
  1825. assert_active_circuits_ok_paranoid(conn);
  1826. if (! conn->active_circuits) {
  1827. conn->active_circuits = circ;
  1828. *prevp = *nextp = circ;
  1829. } else {
  1830. circuit_t *head = conn->active_circuits;
  1831. circuit_t *old_tail = *prev_circ_on_conn_p(head, conn);
  1832. *next_circ_on_conn_p(old_tail, conn) = circ;
  1833. *nextp = head;
  1834. *prev_circ_on_conn_p(head, conn) = circ;
  1835. *prevp = old_tail;
  1836. }
  1837. if (circ->n_conn == conn) {
  1838. add_cell_ewma_to_conn(conn, &circ->n_cell_ewma);
  1839. } else {
  1840. or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
  1841. tor_assert(conn == orcirc->p_conn);
  1842. add_cell_ewma_to_conn(conn, &orcirc->p_cell_ewma);
  1843. }
  1844. assert_active_circuits_ok_paranoid(conn);
  1845. }
  1846. /** Remove <b>circ</b> from the list of circuits with pending cells on
  1847. * <b>conn</b>. No effect if <b>circ</b> is already unlinked. */
  1848. void
  1849. make_circuit_inactive_on_conn(circuit_t *circ, or_connection_t *conn)
  1850. {
  1851. circuit_t **nextp = next_circ_on_conn_p(circ, conn);
  1852. circuit_t **prevp = prev_circ_on_conn_p(circ, conn);
  1853. circuit_t *next = *nextp, *prev = *prevp;
  1854. if (!next && !prev) {
  1855. /* Already inactive. */
  1856. return;
  1857. }
  1858. assert_active_circuits_ok_paranoid(conn);
  1859. tor_assert(next && prev);
  1860. tor_assert(*prev_circ_on_conn_p(next, conn) == circ);
  1861. tor_assert(*next_circ_on_conn_p(prev, conn) == circ);
  1862. if (next == circ) {
  1863. conn->active_circuits = NULL;
  1864. } else {
  1865. *prev_circ_on_conn_p(next, conn) = prev;
  1866. *next_circ_on_conn_p(prev, conn) = next;
  1867. if (conn->active_circuits == circ)
  1868. conn->active_circuits = next;
  1869. }
  1870. *prevp = *nextp = NULL;
  1871. if (circ->n_conn == conn) {
  1872. remove_cell_ewma_from_conn(conn, &circ->n_cell_ewma);
  1873. } else {
  1874. or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
  1875. tor_assert(conn == orcirc->p_conn);
  1876. remove_cell_ewma_from_conn(conn, &orcirc->p_cell_ewma);
  1877. }
  1878. assert_active_circuits_ok_paranoid(conn);
  1879. }
  1880. /** Remove all circuits from the list of circuits with pending cells on
  1881. * <b>conn</b>. */
  1882. void
  1883. connection_or_unlink_all_active_circs(or_connection_t *orconn)
  1884. {
  1885. circuit_t *head = orconn->active_circuits;
  1886. circuit_t *cur = head;
  1887. if (! head)
  1888. return;
  1889. do {
  1890. circuit_t *next = *next_circ_on_conn_p(cur, orconn);
  1891. *prev_circ_on_conn_p(cur, orconn) = NULL;
  1892. *next_circ_on_conn_p(cur, orconn) = NULL;
  1893. cur = next;
  1894. } while (cur != head);
  1895. orconn->active_circuits = NULL;
  1896. SMARTLIST_FOREACH(orconn->active_circuit_pqueue, cell_ewma_t *, e,
  1897. e->heap_index = -1);
  1898. smartlist_clear(orconn->active_circuit_pqueue);
  1899. }
  1900. /** Block (if <b>block</b> is true) or unblock (if <b>block</b> is false)
  1901. * every edge connection that is using <b>circ</b> to write to <b>orconn</b>,
  1902. * and start or stop reading as appropriate. */
  1903. static void
  1904. set_streams_blocked_on_circ(circuit_t *circ, or_connection_t *orconn,
  1905. int block)
  1906. {
  1907. edge_connection_t *edge = NULL;
  1908. if (circ->n_conn == orconn) {
  1909. circ->streams_blocked_on_n_conn = block;
  1910. if (CIRCUIT_IS_ORIGIN(circ))
  1911. edge = TO_ORIGIN_CIRCUIT(circ)->p_streams;
  1912. } else {
  1913. circ->streams_blocked_on_p_conn = block;
  1914. tor_assert(!CIRCUIT_IS_ORIGIN(circ));
  1915. edge = TO_OR_CIRCUIT(circ)->n_streams;
  1916. }
  1917. for (; edge; edge = edge->next_stream) {
  1918. connection_t *conn = TO_CONN(edge);
  1919. edge->edge_blocked_on_circ = block;
  1920. if (!conn->read_event) {
  1921. /* This connection is a placeholder for something; probably a DNS
  1922. * request. It can't actually stop or start reading.*/
  1923. continue;
  1924. }
  1925. if (block) {
  1926. if (connection_is_reading(conn))
  1927. connection_stop_reading(conn);
  1928. } else {
  1929. /* Is this right? */
  1930. if (!connection_is_reading(conn))
  1931. connection_start_reading(conn);
  1932. }
  1933. }
  1934. }
  1935. /** Pull as many cells as possible (but no more than <b>max</b>) from the
  1936. * queue of the first active circuit on <b>conn</b>, and write them to
  1937. * <b>conn</b>-&gt;outbuf. Return the number of cells written. Advance
  1938. * the active circuit pointer to the next active circuit in the ring. */
  1939. int
  1940. connection_or_flush_from_first_active_circuit(or_connection_t *conn, int max,
  1941. time_t now)
  1942. {
  1943. int n_flushed;
  1944. cell_queue_t *queue;
  1945. circuit_t *circ;
  1946. int streams_blocked;
  1947. /* The current (hi-res) time */
  1948. struct timeval now_hires;
  1949. /* The EWMA cell counter for the circuit we're flushing. */
  1950. cell_ewma_t *cell_ewma = NULL;
  1951. double ewma_increment = -1;
  1952. circ = conn->active_circuits;
  1953. if (!circ) return 0;
  1954. assert_active_circuits_ok_paranoid(conn);
  1955. /* See if we're doing the ewma circuit selection algorithm. */
  1956. if (ewma_enabled) {
  1957. unsigned tick;
  1958. double fractional_tick;
  1959. tor_gettimeofday_cached(&now_hires);
  1960. tick = cell_ewma_tick_from_timeval(&now_hires, &fractional_tick);
  1961. if (tick != conn->active_circuit_pqueue_last_recalibrated) {
  1962. scale_active_circuits(conn, tick);
  1963. }
  1964. ewma_increment = pow(ewma_scale_factor, -fractional_tick);
  1965. cell_ewma = smartlist_get(conn->active_circuit_pqueue, 0);
  1966. circ = cell_ewma_to_circuit(cell_ewma);
  1967. }
  1968. if (circ->n_conn == conn) {
  1969. queue = &circ->n_conn_cells;
  1970. streams_blocked = circ->streams_blocked_on_n_conn;
  1971. } else {
  1972. queue = &TO_OR_CIRCUIT(circ)->p_conn_cells;
  1973. streams_blocked = circ->streams_blocked_on_p_conn;
  1974. }
  1975. tor_assert(*next_circ_on_conn_p(circ,conn));
  1976. for (n_flushed = 0; n_flushed < max && queue->head; ) {
  1977. packed_cell_t *cell = cell_queue_pop(queue);
  1978. tor_assert(*next_circ_on_conn_p(circ,conn));
  1979. /* Calculate the exact time that this cell has spent in the queue. */
  1980. if (get_options()->CellStatistics && !CIRCUIT_IS_ORIGIN(circ)) {
  1981. struct timeval now;
  1982. uint32_t flushed;
  1983. uint32_t cell_waiting_time;
  1984. insertion_time_queue_t *it_queue = queue->insertion_times;
  1985. tor_gettimeofday_cached(&now);
  1986. flushed = (uint32_t)((now.tv_sec % SECONDS_IN_A_DAY) * 100L +
  1987. (uint32_t)now.tv_usec / (uint32_t)10000L);
  1988. if (!it_queue || !it_queue->first) {
  1989. log_warn(LD_BUG, "Cannot determine insertion time of cell.");
  1990. } else {
  1991. or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
  1992. insertion_time_elem_t *elem = it_queue->first;
  1993. cell_waiting_time =
  1994. (uint32_t)((flushed * 10L + SECONDS_IN_A_DAY * 1000L -
  1995. elem->insertion_time * 10L) %
  1996. (SECONDS_IN_A_DAY * 1000L));
  1997. #undef SECONDS_IN_A_DAY
  1998. elem->counter--;
  1999. if (elem->counter < 1) {
  2000. it_queue->first = elem->next;
  2001. if (elem == it_queue->last)
  2002. it_queue->last = NULL;
  2003. mp_pool_release(elem);
  2004. }
  2005. orcirc->total_cell_waiting_time += cell_waiting_time;
  2006. orcirc->processed_cells++;
  2007. }
  2008. }
  2009. /* If we just flushed our queue and this circuit is used for a
  2010. * tunneled directory request, possibly advance its state. */
  2011. if (queue->n == 0 && TO_CONN(conn)->dirreq_id)
  2012. geoip_change_dirreq_state(TO_CONN(conn)->dirreq_id,
  2013. DIRREQ_TUNNELED,
  2014. DIRREQ_CIRC_QUEUE_FLUSHED);
  2015. connection_write_to_buf(cell->body, CELL_NETWORK_SIZE, TO_CONN(conn));
  2016. packed_cell_free_unchecked(cell);
  2017. ++n_flushed;
  2018. if (cell_ewma) {
  2019. cell_ewma_t *tmp;
  2020. cell_ewma->cell_count += ewma_increment;
  2021. /* We pop and re-add the cell_ewma_t here, not above, since we need to
  2022. * re-add it immediately to keep the priority queue consistent with
  2023. * the linked-list implementation */
  2024. tmp = pop_first_cell_ewma_from_conn(conn);
  2025. tor_assert(tmp == cell_ewma);
  2026. add_cell_ewma_to_conn(conn, cell_ewma);
  2027. }
  2028. if (circ != conn->active_circuits) {
  2029. /* If this happens, the current circuit just got made inactive by
  2030. * a call in connection_write_to_buf(). That's nothing to worry about:
  2031. * circuit_make_inactive_on_conn() already advanced conn->active_circuits
  2032. * for us.
  2033. */
  2034. assert_active_circuits_ok_paranoid(conn);
  2035. goto done;
  2036. }
  2037. }
  2038. tor_assert(*next_circ_on_conn_p(circ,conn));
  2039. assert_active_circuits_ok_paranoid(conn);
  2040. conn->active_circuits = *next_circ_on_conn_p(circ, conn);
  2041. /* Is the cell queue low enough to unblock all the streams that are waiting
  2042. * to write to this circuit? */
  2043. if (streams_blocked && queue->n <= CELL_QUEUE_LOWWATER_SIZE)
  2044. set_streams_blocked_on_circ(circ, conn, 0); /* unblock streams */
  2045. /* Did we just run out of cells on this circuit's queue? */
  2046. if (queue->n == 0) {
  2047. log_debug(LD_GENERAL, "Made a circuit inactive.");
  2048. make_circuit_inactive_on_conn(circ, conn);
  2049. }
  2050. done:
  2051. if (n_flushed)
  2052. conn->timestamp_last_added_nonpadding = now;
  2053. return n_flushed;
  2054. }
  2055. /** Add <b>cell</b> to the queue of <b>circ</b> writing to <b>orconn</b>
  2056. * transmitting in <b>direction</b>. */
  2057. void
  2058. append_cell_to_circuit_queue(circuit_t *circ, or_connection_t *orconn,
  2059. cell_t *cell, cell_direction_t direction)
  2060. {
  2061. cell_queue_t *queue;
  2062. int streams_blocked;
  2063. if (direction == CELL_DIRECTION_OUT) {
  2064. queue = &circ->n_conn_cells;
  2065. streams_blocked = circ->streams_blocked_on_n_conn;
  2066. } else {
  2067. or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
  2068. queue = &orcirc->p_conn_cells;
  2069. streams_blocked = circ->streams_blocked_on_p_conn;
  2070. }
  2071. if (cell->command == CELL_RELAY_EARLY && orconn->link_proto < 2) {
  2072. /* V1 connections don't understand RELAY_EARLY. */
  2073. cell->command = CELL_RELAY;
  2074. }
  2075. cell_queue_append_packed_copy(queue, cell);
  2076. /* If we have too many cells on the circuit, we should stop reading from
  2077. * the edge streams for a while. */
  2078. if (!streams_blocked && queue->n >= CELL_QUEUE_HIGHWATER_SIZE)
  2079. set_streams_blocked_on_circ(circ, orconn, 1); /* block streams */
  2080. if (queue->n == 1) {
  2081. /* This was the first cell added to the queue. We need to make this
  2082. * circuit active. */
  2083. log_debug(LD_GENERAL, "Made a circuit active.");
  2084. make_circuit_active_on_conn(circ, orconn);
  2085. }
  2086. if (! buf_datalen(orconn->_base.outbuf)) {
  2087. /* There is no data at all waiting to be sent on the outbuf. Add a
  2088. * cell, so that we can notice when it gets flushed, flushed_some can
  2089. * get called, and we can start putting more data onto the buffer then.
  2090. */
  2091. log_debug(LD_GENERAL, "Primed a buffer.");
  2092. connection_or_flush_from_first_active_circuit(orconn, 1, approx_time());
  2093. }
  2094. }
  2095. /** Append an encoded value of <b>addr</b> to <b>payload_out</b>, which must
  2096. * have at least 18 bytes of free space. The encoding is, as specified in
  2097. * tor-spec.txt:
  2098. * RESOLVED_TYPE_IPV4 or RESOLVED_TYPE_IPV6 [1 byte]
  2099. * LENGTH [1 byte]
  2100. * ADDRESS [length bytes]
  2101. * Return the number of bytes added, or -1 on error */
  2102. int
  2103. append_address_to_payload(char *payload_out, const tor_addr_t *addr)
  2104. {
  2105. uint32_t a;
  2106. switch (tor_addr_family(addr)) {
  2107. case AF_INET:
  2108. payload_out[0] = RESOLVED_TYPE_IPV4;
  2109. payload_out[1] = 4;
  2110. a = tor_addr_to_ipv4n(addr);
  2111. memcpy(payload_out+2, &a, 4);
  2112. return 6;
  2113. case AF_INET6:
  2114. payload_out[0] = RESOLVED_TYPE_IPV6;
  2115. payload_out[1] = 16;
  2116. memcpy(payload_out+2, tor_addr_to_in6_addr8(addr), 16);
  2117. return 18;
  2118. case AF_UNSPEC:
  2119. default:
  2120. return -1;
  2121. }
  2122. }
  2123. /** Given <b>payload_len</b> bytes at <b>payload</b>, starting with an address
  2124. * encoded as by append_address_to_payload(), try to decode the address into
  2125. * *<b>addr_out</b>. Return the next byte in the payload after the address on
  2126. * success, or NULL on failure. */
  2127. const char *
  2128. decode_address_from_payload(tor_addr_t *addr_out, const char *payload,
  2129. int payload_len)
  2130. {
  2131. if (payload_len < 2)
  2132. return NULL;
  2133. if (payload_len < 2+(uint8_t)payload[1])
  2134. return NULL;
  2135. switch (payload[0]) {
  2136. case RESOLVED_TYPE_IPV4:
  2137. if (payload[1] != 4)
  2138. return NULL;
  2139. tor_addr_from_ipv4n(addr_out, get_uint32(payload+2));
  2140. break;
  2141. case RESOLVED_TYPE_IPV6:
  2142. if (payload[1] != 16)
  2143. return NULL;
  2144. tor_addr_from_ipv6_bytes(addr_out, payload+2);
  2145. break;
  2146. default:
  2147. tor_addr_make_unspec(addr_out);
  2148. break;
  2149. }
  2150. return payload + 2 + (uint8_t)payload[1];
  2151. }
  2152. /** Fail with an assert if the active circuits ring on <b>orconn</b> is
  2153. * corrupt. */
  2154. void
  2155. assert_active_circuits_ok(or_connection_t *orconn)
  2156. {
  2157. circuit_t *head = orconn->active_circuits;
  2158. circuit_t *cur = head;
  2159. int n = 0;
  2160. if (! head)
  2161. return;
  2162. do {
  2163. circuit_t *next = *next_circ_on_conn_p(cur, orconn);
  2164. circuit_t *prev = *prev_circ_on_conn_p(cur, orconn);
  2165. cell_ewma_t *ewma;
  2166. tor_assert(next);
  2167. tor_assert(prev);
  2168. tor_assert(*next_circ_on_conn_p(prev, orconn) == cur);
  2169. tor_assert(*prev_circ_on_conn_p(next, orconn) == cur);
  2170. if (orconn == cur->n_conn) {
  2171. ewma = &cur->n_cell_ewma;
  2172. tor_assert(!ewma->is_for_p_conn);
  2173. } else {
  2174. ewma = &TO_OR_CIRCUIT(cur)->p_cell_ewma;
  2175. tor_assert(ewma->is_for_p_conn);
  2176. }
  2177. tor_assert(ewma->heap_index != -1);
  2178. tor_assert(ewma == smartlist_get(orconn->active_circuit_pqueue,
  2179. ewma->heap_index));
  2180. n++;
  2181. cur = next;
  2182. } while (cur != head);
  2183. tor_assert(n == smartlist_len(orconn->active_circuit_pqueue));
  2184. }