relay.c 88 KB

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