relay.c 87 KB

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