relay.c 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963
  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, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /* $Id$ */
  7. const char relay_c_id[] =
  8. "$Id$";
  9. /**
  10. * \file relay.c
  11. * \brief Handle relay cell encryption/decryption, plus packaging and
  12. * receiving from circuits, plus queueing on circuits.
  13. **/
  14. #include "or.h"
  15. #include "mempool.h"
  16. static int relay_crypt(circuit_t *circ, cell_t *cell, int cell_direction,
  17. crypt_path_t **layer_hint, char *recognized);
  18. static edge_connection_t *relay_lookup_conn(circuit_t *circ, cell_t *cell,
  19. int cell_direction,
  20. crypt_path_t *layer_hint);
  21. static int
  22. connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
  23. edge_connection_t *conn,
  24. crypt_path_t *layer_hint);
  25. static void
  26. circuit_consider_sending_sendme(circuit_t *circ, crypt_path_t *layer_hint);
  27. static void
  28. circuit_resume_edge_reading(circuit_t *circ, crypt_path_t *layer_hint);
  29. static int
  30. circuit_resume_edge_reading_helper(edge_connection_t *conn,
  31. circuit_t *circ,
  32. crypt_path_t *layer_hint);
  33. static int
  34. circuit_consider_stop_edge_reading(circuit_t *circ, crypt_path_t *layer_hint);
  35. /** Stats: how many relay cells have originated at this hop, or have
  36. * been relayed onward (not recognized at this hop)?
  37. */
  38. uint64_t stats_n_relay_cells_relayed = 0;
  39. /** Stats: how many relay cells have been delivered to streams at this
  40. * hop?
  41. */
  42. uint64_t stats_n_relay_cells_delivered = 0;
  43. /** Update digest from the payload of cell. Assign integrity part to
  44. * cell.
  45. */
  46. static void
  47. relay_set_digest(crypto_digest_env_t *digest, cell_t *cell)
  48. {
  49. char integrity[4];
  50. relay_header_t rh;
  51. crypto_digest_add_bytes(digest, cell->payload, CELL_PAYLOAD_SIZE);
  52. crypto_digest_get_digest(digest, integrity, 4);
  53. // log_fn(LOG_DEBUG,"Putting digest of %u %u %u %u into relay cell.",
  54. // integrity[0], integrity[1], integrity[2], integrity[3]);
  55. relay_header_unpack(&rh, cell->payload);
  56. memcpy(rh.integrity, integrity, 4);
  57. relay_header_pack(cell->payload, &rh);
  58. }
  59. /** Does the digest for this circuit indicate that this cell is for us?
  60. *
  61. * Update digest from the payload of cell (with the integrity part set
  62. * to 0). If the integrity part is valid, return 1, else restore digest
  63. * and cell to their original state and return 0.
  64. */
  65. static int
  66. relay_digest_matches(crypto_digest_env_t *digest, cell_t *cell)
  67. {
  68. char received_integrity[4], calculated_integrity[4];
  69. relay_header_t rh;
  70. crypto_digest_env_t *backup_digest=NULL;
  71. backup_digest = crypto_digest_dup(digest);
  72. relay_header_unpack(&rh, cell->payload);
  73. memcpy(received_integrity, rh.integrity, 4);
  74. memset(rh.integrity, 0, 4);
  75. relay_header_pack(cell->payload, &rh);
  76. // log_fn(LOG_DEBUG,"Reading digest of %u %u %u %u from relay cell.",
  77. // received_integrity[0], received_integrity[1],
  78. // received_integrity[2], received_integrity[3]);
  79. crypto_digest_add_bytes(digest, cell->payload, CELL_PAYLOAD_SIZE);
  80. crypto_digest_get_digest(digest, calculated_integrity, 4);
  81. if (memcmp(received_integrity, calculated_integrity, 4)) {
  82. // log_fn(LOG_INFO,"Recognized=0 but bad digest. Not recognizing.");
  83. // (%d vs %d).", received_integrity, calculated_integrity);
  84. /* restore digest to its old form */
  85. crypto_digest_assign(digest, backup_digest);
  86. /* restore the relay header */
  87. memcpy(rh.integrity, received_integrity, 4);
  88. relay_header_pack(cell->payload, &rh);
  89. crypto_free_digest_env(backup_digest);
  90. return 0;
  91. }
  92. crypto_free_digest_env(backup_digest);
  93. return 1;
  94. }
  95. /** Apply <b>cipher</b> to CELL_PAYLOAD_SIZE bytes of <b>in</b>
  96. * (in place).
  97. *
  98. * If <b>encrypt_mode</b> is 1 then encrypt, else decrypt.
  99. *
  100. * Return -1 if the crypto fails, else return 0.
  101. */
  102. static int
  103. relay_crypt_one_payload(crypto_cipher_env_t *cipher, char *in,
  104. int encrypt_mode)
  105. {
  106. char out[CELL_PAYLOAD_SIZE]; /* 'in' must be this size too */
  107. int r;
  108. if (encrypt_mode)
  109. r = crypto_cipher_encrypt(cipher, out, in, CELL_PAYLOAD_SIZE);
  110. else
  111. r = crypto_cipher_decrypt(cipher, out, in, CELL_PAYLOAD_SIZE);
  112. if (r) {
  113. log_warn(LD_BUG,"Error during relay encryption");
  114. return -1;
  115. }
  116. memcpy(in,out,CELL_PAYLOAD_SIZE);
  117. return 0;
  118. }
  119. /** Receive a relay cell:
  120. * - Crypt it (encrypt if headed toward the origin or if we <b>are</b> the
  121. * origin; decrypt if we're headed toward the exit).
  122. * - Check if recognized (if exitward).
  123. * - If recognized and the digest checks out, then find if there's a stream
  124. * that the cell is intended for, and deliver it to the right
  125. * connection_edge.
  126. * - If not recognized, then we need to relay it: append it to the appropriate
  127. * cell_queue on <b>circ</b>.
  128. *
  129. * Return -<b>reason</b> on failure.
  130. */
  131. int
  132. circuit_receive_relay_cell(cell_t *cell, circuit_t *circ, int cell_direction)
  133. {
  134. or_connection_t *or_conn=NULL;
  135. crypt_path_t *layer_hint=NULL;
  136. char recognized=0;
  137. int reason;
  138. tor_assert(cell);
  139. tor_assert(circ);
  140. tor_assert(cell_direction == CELL_DIRECTION_OUT ||
  141. cell_direction == CELL_DIRECTION_IN);
  142. if (circ->marked_for_close)
  143. return 0;
  144. if (relay_crypt(circ, cell, cell_direction, &layer_hint, &recognized) < 0) {
  145. log_warn(LD_BUG,"relay crypt failed. Dropping connection.");
  146. return -END_CIRC_REASON_INTERNAL;
  147. }
  148. if (recognized) {
  149. edge_connection_t *conn = relay_lookup_conn(circ, cell, cell_direction,
  150. layer_hint);
  151. if (cell_direction == CELL_DIRECTION_OUT) {
  152. ++stats_n_relay_cells_delivered;
  153. log_debug(LD_OR,"Sending away from origin.");
  154. if ((reason=connection_edge_process_relay_cell(cell, circ, conn, NULL))
  155. < 0) {
  156. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  157. "connection_edge_process_relay_cell (away from origin) "
  158. "failed.");
  159. return reason;
  160. }
  161. }
  162. if (cell_direction == CELL_DIRECTION_IN) {
  163. ++stats_n_relay_cells_delivered;
  164. log_debug(LD_OR,"Sending to origin.");
  165. if ((reason = connection_edge_process_relay_cell(cell, circ, conn,
  166. layer_hint)) < 0) {
  167. log_warn(LD_OR,
  168. "connection_edge_process_relay_cell (at origin) failed.");
  169. return reason;
  170. }
  171. }
  172. return 0;
  173. }
  174. /* not recognized. pass it on. */
  175. if (cell_direction == CELL_DIRECTION_OUT) {
  176. cell->circ_id = circ->n_circ_id; /* switch it */
  177. or_conn = circ->n_conn;
  178. } else if (! CIRCUIT_IS_ORIGIN(circ)) {
  179. cell->circ_id = TO_OR_CIRCUIT(circ)->p_circ_id; /* switch it */
  180. or_conn = TO_OR_CIRCUIT(circ)->p_conn;
  181. } else {
  182. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  183. "Dropping unrecognized inbound cell on origin circuit.");
  184. return 0;
  185. }
  186. if (!or_conn) {
  187. // XXXX Can this splice stuff be done more cleanly?
  188. if (! CIRCUIT_IS_ORIGIN(circ) &&
  189. TO_OR_CIRCUIT(circ)->rend_splice &&
  190. cell_direction == CELL_DIRECTION_OUT) {
  191. or_circuit_t *splice = TO_OR_CIRCUIT(circ)->rend_splice;
  192. tor_assert(circ->purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED);
  193. tor_assert(splice->_base.purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED);
  194. cell->circ_id = splice->p_circ_id;
  195. if ((reason = circuit_receive_relay_cell(cell, TO_CIRCUIT(splice),
  196. CELL_DIRECTION_IN)) < 0) {
  197. log_warn(LD_REND, "Error relaying cell across rendezvous; closing "
  198. "circuits");
  199. /* XXXX Do this here, or just return -1? */
  200. circuit_mark_for_close(circ, -reason);
  201. return reason;
  202. }
  203. return 0;
  204. }
  205. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  206. "Didn't recognize cell, but circ stops here! Closing circ.");
  207. return -END_CIRC_REASON_TORPROTOCOL;
  208. }
  209. log_debug(LD_OR,"Passing on unrecognized cell.");
  210. ++stats_n_relay_cells_relayed; /* XXXX no longer quite accurate {cells}
  211. * we might kill the circ before we relay
  212. * the cells. */
  213. append_cell_to_circuit_queue(circ, or_conn, cell, cell_direction);
  214. return 0;
  215. }
  216. /** Do the appropriate en/decryptions for <b>cell</b> arriving on
  217. * <b>circ</b> in direction <b>cell_direction</b>.
  218. *
  219. * If cell_direction == CELL_DIRECTION_IN:
  220. * - If we're at the origin (we're the OP), for hops 1..N,
  221. * decrypt cell. If recognized, stop.
  222. * - Else (we're not the OP), encrypt one hop. Cell is not recognized.
  223. *
  224. * If cell_direction == CELL_DIRECTION_OUT:
  225. * - decrypt one hop. Check if recognized.
  226. *
  227. * If cell is recognized, set *recognized to 1, and set
  228. * *layer_hint to the hop that recognized it.
  229. *
  230. * Return -1 to indicate that we should mark the circuit for close,
  231. * else return 0.
  232. */
  233. static int
  234. relay_crypt(circuit_t *circ, cell_t *cell, int cell_direction,
  235. crypt_path_t **layer_hint, char *recognized)
  236. {
  237. relay_header_t rh;
  238. tor_assert(circ);
  239. tor_assert(cell);
  240. tor_assert(recognized);
  241. tor_assert(cell_direction == CELL_DIRECTION_IN ||
  242. cell_direction == CELL_DIRECTION_OUT);
  243. if (cell_direction == CELL_DIRECTION_IN) {
  244. if (CIRCUIT_IS_ORIGIN(circ)) { /* We're at the beginning of the circuit.
  245. * We'll want to do layered decrypts. */
  246. crypt_path_t *thishop, *cpath = TO_ORIGIN_CIRCUIT(circ)->cpath;
  247. thishop = cpath;
  248. if (thishop->state != CPATH_STATE_OPEN) {
  249. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  250. "Relay cell before first created cell? Closing.");
  251. return -1;
  252. }
  253. do { /* Remember: cpath is in forward order, that is, first hop first. */
  254. tor_assert(thishop);
  255. if (relay_crypt_one_payload(thishop->b_crypto, cell->payload, 0) < 0)
  256. return -1;
  257. relay_header_unpack(&rh, cell->payload);
  258. if (rh.recognized == 0) {
  259. /* it's possibly recognized. have to check digest to be sure. */
  260. if (relay_digest_matches(thishop->b_digest, cell)) {
  261. *recognized = 1;
  262. *layer_hint = thishop;
  263. return 0;
  264. }
  265. }
  266. thishop = thishop->next;
  267. } while (thishop != cpath && thishop->state == CPATH_STATE_OPEN);
  268. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  269. "Incoming cell at client not recognized. Closing.");
  270. return -1;
  271. } else { /* we're in the middle. Just one crypt. */
  272. if (relay_crypt_one_payload(TO_OR_CIRCUIT(circ)->p_crypto,
  273. cell->payload, 1) < 0)
  274. return -1;
  275. // log_fn(LOG_DEBUG,"Skipping recognized check, because we're not "
  276. // "the client.");
  277. }
  278. } else /* cell_direction == CELL_DIRECTION_OUT */ {
  279. /* we're in the middle. Just one crypt. */
  280. if (relay_crypt_one_payload(TO_OR_CIRCUIT(circ)->n_crypto,
  281. cell->payload, 0) < 0)
  282. return -1;
  283. relay_header_unpack(&rh, cell->payload);
  284. if (rh.recognized == 0) {
  285. /* it's possibly recognized. have to check digest to be sure. */
  286. if (relay_digest_matches(TO_OR_CIRCUIT(circ)->n_digest, cell)) {
  287. *recognized = 1;
  288. return 0;
  289. }
  290. }
  291. }
  292. return 0;
  293. }
  294. /** Package a relay cell from an edge:
  295. * - Encrypt it to the right layer
  296. * - Append it to the appropriate cell_queue on <b>circ</b>.
  297. */
  298. static int
  299. circuit_package_relay_cell(cell_t *cell, circuit_t *circ,
  300. int cell_direction,
  301. crypt_path_t *layer_hint)
  302. {
  303. or_connection_t *conn; /* where to send the cell */
  304. if (cell_direction == CELL_DIRECTION_OUT) {
  305. crypt_path_t *thishop; /* counter for repeated crypts */
  306. conn = circ->n_conn;
  307. if (!CIRCUIT_IS_ORIGIN(circ) || !conn) {
  308. log_warn(LD_BUG,"outgoing relay cell has n_conn==NULL. Dropping.");
  309. return 0; /* just drop it */
  310. }
  311. relay_set_digest(layer_hint->f_digest, cell);
  312. thishop = layer_hint;
  313. /* moving from farthest to nearest hop */
  314. do {
  315. tor_assert(thishop);
  316. /* XXXX RD This is a bug, right? */
  317. log_debug(LD_OR,"crypting a layer of the relay cell.");
  318. if (relay_crypt_one_payload(thishop->f_crypto, cell->payload, 1) < 0) {
  319. return -1;
  320. }
  321. thishop = thishop->prev;
  322. } while (thishop != TO_ORIGIN_CIRCUIT(circ)->cpath->prev);
  323. } else { /* incoming cell */
  324. or_circuit_t *or_circ;
  325. if (CIRCUIT_IS_ORIGIN(circ)) {
  326. /* We should never package an _incoming_ cell from the circuit
  327. * origin; that means we messed up somewhere. */
  328. log_warn(LD_BUG,"incoming relay cell at origin circuit. Dropping.");
  329. assert_circuit_ok(circ);
  330. return 0; /* just drop it */
  331. }
  332. or_circ = TO_OR_CIRCUIT(circ);
  333. conn = or_circ->p_conn;
  334. relay_set_digest(or_circ->p_digest, cell);
  335. if (relay_crypt_one_payload(or_circ->p_crypto, cell->payload, 1) < 0)
  336. return -1;
  337. }
  338. ++stats_n_relay_cells_relayed;
  339. append_cell_to_circuit_queue(circ, conn, cell, cell_direction);
  340. return 0;
  341. }
  342. /** If cell's stream_id matches the stream_id of any conn that's
  343. * attached to circ, return that conn, else return NULL.
  344. */
  345. static edge_connection_t *
  346. relay_lookup_conn(circuit_t *circ, cell_t *cell, int cell_direction,
  347. crypt_path_t *layer_hint)
  348. {
  349. edge_connection_t *tmpconn;
  350. relay_header_t rh;
  351. relay_header_unpack(&rh, cell->payload);
  352. if (!rh.stream_id)
  353. return NULL;
  354. /* IN or OUT cells could have come from either direction, now
  355. * that we allow rendezvous *to* an OP.
  356. */
  357. if (CIRCUIT_IS_ORIGIN(circ)) {
  358. for (tmpconn = TO_ORIGIN_CIRCUIT(circ)->p_streams; tmpconn;
  359. tmpconn=tmpconn->next_stream) {
  360. if (rh.stream_id == tmpconn->stream_id &&
  361. !tmpconn->_base.marked_for_close &&
  362. tmpconn->cpath_layer == layer_hint) {
  363. log_debug(LD_APP,"found conn for stream %d.", rh.stream_id);
  364. return tmpconn;
  365. }
  366. }
  367. } else {
  368. for (tmpconn = TO_OR_CIRCUIT(circ)->n_streams; tmpconn;
  369. tmpconn=tmpconn->next_stream) {
  370. if (rh.stream_id == tmpconn->stream_id &&
  371. !tmpconn->_base.marked_for_close) {
  372. log_debug(LD_EXIT,"found conn for stream %d.", rh.stream_id);
  373. if (cell_direction == CELL_DIRECTION_OUT ||
  374. connection_edge_is_rendezvous_stream(tmpconn))
  375. return tmpconn;
  376. }
  377. }
  378. for (tmpconn = TO_OR_CIRCUIT(circ)->resolving_streams; tmpconn;
  379. tmpconn=tmpconn->next_stream) {
  380. if (rh.stream_id == tmpconn->stream_id &&
  381. !tmpconn->_base.marked_for_close) {
  382. log_debug(LD_EXIT,"found conn for stream %d.", rh.stream_id);
  383. return tmpconn;
  384. }
  385. }
  386. }
  387. return NULL; /* probably a begin relay cell */
  388. }
  389. /** Pack the relay_header_t host-order structure <b>src</b> into
  390. * network-order in the buffer <b>dest</b>. See tor-spec.txt for details
  391. * about the wire format.
  392. */
  393. void
  394. relay_header_pack(char *dest, const relay_header_t *src)
  395. {
  396. *(uint8_t*)(dest) = src->command;
  397. set_uint16(dest+1, htons(src->recognized));
  398. set_uint16(dest+3, htons(src->stream_id));
  399. memcpy(dest+5, src->integrity, 4);
  400. set_uint16(dest+9, htons(src->length));
  401. }
  402. /** Unpack the network-order buffer <b>src</b> into a host-order
  403. * relay_header_t structure <b>dest</b>.
  404. */
  405. void
  406. relay_header_unpack(relay_header_t *dest, const char *src)
  407. {
  408. dest->command = *(uint8_t*)(src);
  409. dest->recognized = ntohs(get_uint16(src+1));
  410. dest->stream_id = ntohs(get_uint16(src+3));
  411. memcpy(dest->integrity, src+5, 4);
  412. dest->length = ntohs(get_uint16(src+9));
  413. }
  414. /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and send
  415. * it onto the open circuit <b>circ</b>. <b>stream_id</b> is the ID on
  416. * <b>circ</b> for the stream that's sending the relay cell, or 0 if it's a
  417. * control cell. <b>cpath_layer</b> is NULL for OR->OP cells, or the
  418. * destination hop for OP->OR cells.
  419. *
  420. * If you can't send the cell, mark the circuit for close and return -1. Else
  421. * return 0.
  422. */
  423. int
  424. relay_send_command_from_edge(uint16_t stream_id, circuit_t *circ,
  425. int relay_command, const char *payload,
  426. size_t payload_len, crypt_path_t *cpath_layer)
  427. {
  428. cell_t cell;
  429. relay_header_t rh;
  430. int cell_direction;
  431. /* XXXX NM Split this function into a separate versions per circuit type? */
  432. tor_assert(circ);
  433. memset(&cell, 0, sizeof(cell_t));
  434. cell.command = CELL_RELAY;
  435. if (cpath_layer) {
  436. cell.circ_id = circ->n_circ_id;
  437. cell_direction = CELL_DIRECTION_OUT;
  438. } else if (! CIRCUIT_IS_ORIGIN(circ)) {
  439. cell.circ_id = TO_OR_CIRCUIT(circ)->p_circ_id;
  440. cell_direction = CELL_DIRECTION_IN;
  441. } else {
  442. return -1;
  443. }
  444. memset(&rh, 0, sizeof(rh));
  445. rh.command = relay_command;
  446. rh.stream_id = stream_id;
  447. rh.length = payload_len;
  448. relay_header_pack(cell.payload, &rh);
  449. if (payload_len) {
  450. tor_assert(payload_len <= RELAY_PAYLOAD_SIZE);
  451. memcpy(cell.payload+RELAY_HEADER_SIZE, payload, payload_len);
  452. }
  453. log_debug(LD_OR,"delivering %d cell %s.", relay_command,
  454. cell_direction == CELL_DIRECTION_OUT ? "forward" : "backward");
  455. if (cell_direction == CELL_DIRECTION_OUT && circ->n_conn) {
  456. /* if we're using relaybandwidthrate, this conn wants priority */
  457. /* XXXX020 the call to time() seems little too frequent */
  458. circ->n_conn->client_used = time(NULL);
  459. }
  460. if (circuit_package_relay_cell(&cell, circ, cell_direction, cpath_layer)
  461. < 0) {
  462. log_warn(LD_BUG,"circuit_package_relay_cell failed. Closing.");
  463. circuit_mark_for_close(circ, END_CIRC_REASON_INTERNAL);
  464. return -1;
  465. }
  466. return 0;
  467. }
  468. /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and
  469. * send it onto the open circuit <b>circ</b>. <b>fromconn</b> is the stream
  470. * that's sending the relay cell, or NULL if it's a control cell.
  471. * <b>cpath_layer</b> is NULL for OR->OP cells, or the destination hop
  472. * for OP->OR cells.
  473. *
  474. * If you can't send the cell, mark the circuit for close and
  475. * return -1. Else return 0.
  476. */
  477. int
  478. connection_edge_send_command(edge_connection_t *fromconn,
  479. int relay_command, const char *payload,
  480. size_t payload_len)
  481. {
  482. /* XXXX NM Split this function into a separate versions per circuit type? */
  483. circuit_t *circ;
  484. tor_assert(fromconn);
  485. circ = fromconn->on_circuit;
  486. if (fromconn->_base.marked_for_close) {
  487. log_warn(LD_BUG,
  488. "called on conn that's already marked for close at %s:%d.",
  489. fromconn->_base.marked_for_close_file,
  490. fromconn->_base.marked_for_close);
  491. return 0;
  492. }
  493. if (!circ) {
  494. if (fromconn->_base.type == CONN_TYPE_AP) {
  495. log_info(LD_APP,"no circ. Closing conn.");
  496. connection_mark_unattached_ap(fromconn, END_STREAM_REASON_INTERNAL);
  497. } else {
  498. log_info(LD_EXIT,"no circ. Closing conn.");
  499. fromconn->_base.edge_has_sent_end = 1; /* no circ to send to */
  500. fromconn->end_reason = END_STREAM_REASON_INTERNAL;
  501. connection_mark_for_close(TO_CONN(fromconn));
  502. }
  503. return -1;
  504. }
  505. return relay_send_command_from_edge(fromconn->stream_id, circ,
  506. relay_command, payload,
  507. payload_len, fromconn->cpath_layer);
  508. }
  509. /** Translate <b>reason</b>, which came from a relay 'end' cell,
  510. * into a static const string describing why the stream is closing.
  511. * <b>reason</b> is -1 if no reason was provided.
  512. */
  513. static const char *
  514. connection_edge_end_reason_str(int reason)
  515. {
  516. switch (reason) {
  517. case -1:
  518. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  519. "End cell arrived with length 0. Should be at least 1.");
  520. return "MALFORMED";
  521. case END_STREAM_REASON_MISC: return "misc error";
  522. case END_STREAM_REASON_RESOLVEFAILED: return "resolve failed";
  523. case END_STREAM_REASON_CONNECTREFUSED: return "connection refused";
  524. case END_STREAM_REASON_EXITPOLICY: return "exit policy failed";
  525. case END_STREAM_REASON_DESTROY: return "destroyed";
  526. case END_STREAM_REASON_DONE: return "closed normally";
  527. case END_STREAM_REASON_TIMEOUT: return "gave up (timeout)";
  528. case END_STREAM_REASON_HIBERNATING: return "server is hibernating";
  529. case END_STREAM_REASON_INTERNAL: return "internal error at server";
  530. case END_STREAM_REASON_RESOURCELIMIT: return "server out of resources";
  531. case END_STREAM_REASON_CONNRESET: return "connection reset";
  532. case END_STREAM_REASON_TORPROTOCOL: return "Tor protocol error";
  533. case END_STREAM_REASON_NOTDIRECTORY: return "not a directory";
  534. default:
  535. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  536. "Reason for ending (%d) not recognized.",reason);
  537. return "unknown";
  538. }
  539. }
  540. /** Translate <b>reason</b> (as from a relay 'end' cell) into an
  541. * appropriate SOCKS5 reply code.
  542. * DODCDOC 0
  543. */
  544. socks5_reply_status_t
  545. connection_edge_end_reason_socks5_response(int reason)
  546. {
  547. switch (reason & END_STREAM_REASON_MASK) {
  548. case 0:
  549. return SOCKS5_SUCCEEDED;
  550. case END_STREAM_REASON_MISC:
  551. return SOCKS5_GENERAL_ERROR;
  552. case END_STREAM_REASON_RESOLVEFAILED:
  553. return SOCKS5_HOST_UNREACHABLE;
  554. case END_STREAM_REASON_CONNECTREFUSED:
  555. return SOCKS5_CONNECTION_REFUSED;
  556. case END_STREAM_REASON_EXITPOLICY:
  557. return SOCKS5_NOT_ALLOWED;
  558. case END_STREAM_REASON_DESTROY:
  559. return SOCKS5_GENERAL_ERROR;
  560. case END_STREAM_REASON_DONE:
  561. return SOCKS5_SUCCEEDED;
  562. case END_STREAM_REASON_TIMEOUT:
  563. return SOCKS5_TTL_EXPIRED;
  564. case END_STREAM_REASON_RESOURCELIMIT:
  565. return SOCKS5_GENERAL_ERROR;
  566. case END_STREAM_REASON_HIBERNATING:
  567. return SOCKS5_GENERAL_ERROR;
  568. case END_STREAM_REASON_INTERNAL:
  569. return SOCKS5_GENERAL_ERROR;
  570. case END_STREAM_REASON_CONNRESET:
  571. return SOCKS5_CONNECTION_REFUSED;
  572. case END_STREAM_REASON_TORPROTOCOL:
  573. return SOCKS5_GENERAL_ERROR;
  574. case END_STREAM_REASON_CANT_ATTACH:
  575. return SOCKS5_GENERAL_ERROR;
  576. case END_STREAM_REASON_NET_UNREACHABLE:
  577. return SOCKS5_NET_UNREACHABLE;
  578. case END_STREAM_REASON_SOCKSPROTOCOL:
  579. return SOCKS5_GENERAL_ERROR;
  580. default:
  581. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  582. "Reason for ending (%d) not recognized; "
  583. "sending generic socks error.", reason);
  584. return SOCKS5_GENERAL_ERROR;
  585. }
  586. }
  587. /* We need to use a few macros to deal with the fact that Windows
  588. * decided that their sockets interface should be a permakludge.
  589. * E_CASE is for errors where windows has both a EFOO and a WSAEFOO
  590. * version, and S_CASE is for errors where windows has only a WSAEFOO
  591. * version. (The E is for 'error', the S is for 'socket'). */
  592. #ifdef MS_WINDOWS
  593. #define E_CASE(s) case s: case WSA ## s
  594. #define S_CASE(s) case WSA ## s
  595. #else
  596. #define E_CASE(s) case s
  597. #define S_CASE(s) case s
  598. #endif
  599. /** Given an errno from a failed exit connection, return a reason code
  600. * appropriate for use in a RELAY END cell.
  601. */
  602. int
  603. errno_to_end_reason(int e)
  604. {
  605. switch (e) {
  606. case EPIPE:
  607. return END_STREAM_REASON_DONE;
  608. E_CASE(EBADF):
  609. E_CASE(EFAULT):
  610. E_CASE(EINVAL):
  611. S_CASE(EISCONN):
  612. S_CASE(ENOTSOCK):
  613. S_CASE(EPROTONOSUPPORT):
  614. S_CASE(EAFNOSUPPORT):
  615. E_CASE(EACCES):
  616. S_CASE(ENOTCONN):
  617. S_CASE(ENETUNREACH):
  618. return END_STREAM_REASON_INTERNAL;
  619. S_CASE(ECONNREFUSED):
  620. return END_STREAM_REASON_CONNECTREFUSED;
  621. S_CASE(ECONNRESET):
  622. return END_STREAM_REASON_CONNRESET;
  623. S_CASE(ETIMEDOUT):
  624. return END_STREAM_REASON_TIMEOUT;
  625. S_CASE(ENOBUFS):
  626. case ENOMEM:
  627. case ENFILE:
  628. E_CASE(EMFILE):
  629. return END_STREAM_REASON_RESOURCELIMIT;
  630. default:
  631. log_info(LD_EXIT, "Didn't recognize errno %d (%s); telling the client "
  632. "that we are ending a stream for 'misc' reason.",
  633. e, tor_socket_strerror(e));
  634. return END_STREAM_REASON_MISC;
  635. }
  636. }
  637. /** How many times will I retry a stream that fails due to DNS
  638. * resolve failure or misc error?
  639. */
  640. #define MAX_RESOLVE_FAILURES 3
  641. /** Return 1 if reason is something that you should retry if you
  642. * get the end cell before you've connected; else return 0. */
  643. static int
  644. edge_reason_is_retriable(int reason)
  645. {
  646. return reason == END_STREAM_REASON_HIBERNATING ||
  647. reason == END_STREAM_REASON_RESOURCELIMIT ||
  648. reason == END_STREAM_REASON_EXITPOLICY ||
  649. reason == END_STREAM_REASON_RESOLVEFAILED ||
  650. reason == END_STREAM_REASON_MISC;
  651. }
  652. /** Called when we receive an END cell on a stream that isn't open yet.
  653. * Arguments are as for connection_edge_process_relay_cell().
  654. */
  655. static int
  656. connection_edge_process_end_not_open(
  657. relay_header_t *rh, cell_t *cell, origin_circuit_t *circ,
  658. edge_connection_t *conn, crypt_path_t *layer_hint)
  659. {
  660. struct in_addr in;
  661. routerinfo_t *exitrouter;
  662. int reason = *(cell->payload+RELAY_HEADER_SIZE);
  663. int control_reason = reason | END_STREAM_REASON_FLAG_REMOTE;
  664. (void) layer_hint; /* unused */
  665. if (rh->length > 0 && edge_reason_is_retriable(reason) &&
  666. conn->_base.type == CONN_TYPE_AP) {
  667. log_info(LD_APP,"Address '%s' refused due to '%s'. Considering retrying.",
  668. safe_str(conn->socks_request->address),
  669. connection_edge_end_reason_str(reason));
  670. exitrouter =
  671. router_get_by_digest(circ->build_state->chosen_exit->identity_digest);
  672. switch (reason) {
  673. case END_STREAM_REASON_EXITPOLICY:
  674. if (rh->length >= 5) {
  675. uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+1));
  676. int ttl;
  677. if (!addr) {
  678. log_info(LD_APP,"Address '%s' resolved to 0.0.0.0. Closing,",
  679. safe_str(conn->socks_request->address));
  680. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  681. return 0;
  682. }
  683. if (rh->length >= 9)
  684. ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+5));
  685. else
  686. ttl = -1;
  687. client_dns_set_addressmap(conn->socks_request->address, addr,
  688. conn->chosen_exit_name, ttl);
  689. }
  690. /* check if he *ought* to have allowed it */
  691. if (exitrouter &&
  692. (rh->length < 5 ||
  693. (tor_inet_aton(conn->socks_request->address, &in) &&
  694. !conn->chosen_exit_name))) {
  695. log_notice(LD_APP,
  696. "Exitrouter '%s' seems to be more restrictive than its exit "
  697. "policy. Not using this router as exit for now.",
  698. exitrouter->nickname);
  699. addr_policy_free(exitrouter->exit_policy);
  700. exitrouter->exit_policy =
  701. router_parse_addr_policy_from_string("reject *:*", -1);
  702. }
  703. /* rewrite it to an IP if we learned one. */
  704. if (addressmap_rewrite(conn->socks_request->address,
  705. sizeof(conn->socks_request->address),
  706. NULL)) {
  707. control_event_stream_status(conn, STREAM_EVENT_REMAP, 0);
  708. }
  709. if (conn->_base.chosen_exit_optional) {
  710. /* stop wanting a specific exit */
  711. conn->_base.chosen_exit_optional = 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->_base.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. if (client_dns_incr_failures(conn->socks_request->address)
  727. < MAX_RESOLVE_FAILURES) {
  728. /* We haven't retried too many times; reattach the connection. */
  729. circuit_log_path(LOG_INFO,LD_APP,circ);
  730. tor_assert(circ->_base.timestamp_dirty);
  731. circ->_base.timestamp_dirty -= get_options()->MaxCircuitDirtiness;
  732. if (conn->_base.chosen_exit_optional) {
  733. /* stop wanting a specific exit */
  734. conn->_base.chosen_exit_optional = 0;
  735. tor_free(conn->chosen_exit_name); /* clears it */
  736. }
  737. if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
  738. return 0;
  739. /* else, conn will get closed below */
  740. } else {
  741. log_notice(LD_APP,
  742. "Have tried resolving or connecting to address '%s' "
  743. "at %d different places. Giving up.",
  744. safe_str(conn->socks_request->address),
  745. MAX_RESOLVE_FAILURES);
  746. /* clear the failures, so it will have a full try next time */
  747. client_dns_clear_failures(conn->socks_request->address);
  748. }
  749. break;
  750. case END_STREAM_REASON_HIBERNATING:
  751. case END_STREAM_REASON_RESOURCELIMIT:
  752. if (exitrouter) {
  753. addr_policy_free(exitrouter->exit_policy);
  754. exitrouter->exit_policy =
  755. router_parse_addr_policy_from_string("reject *:*", -1);
  756. }
  757. if (conn->_base.chosen_exit_optional) {
  758. /* stop wanting a specific exit */
  759. conn->_base.chosen_exit_optional = 0;
  760. tor_free(conn->chosen_exit_name); /* clears it */
  761. }
  762. if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
  763. return 0;
  764. /* else, will close below */
  765. break;
  766. } /* end switch */
  767. log_info(LD_APP,"Giving up on retrying; conn can't be handled.");
  768. }
  769. log_info(LD_APP,
  770. "Edge got end (%s) before we're connected. Marking for close.",
  771. connection_edge_end_reason_str(rh->length > 0 ? reason : -1));
  772. if (conn->_base.type == CONN_TYPE_AP) {
  773. circuit_log_path(LOG_INFO,LD_APP,circ);
  774. connection_mark_unattached_ap(conn, control_reason);
  775. } else {
  776. /* we just got an 'end', don't need to send one */
  777. conn->_base.edge_has_sent_end = 1;
  778. conn->end_reason = control_reason;
  779. connection_mark_for_close(TO_CONN(conn));
  780. }
  781. return 0;
  782. }
  783. /** Helper: change the socks_request-&gt;address field on conn to the
  784. * dotted-quad representation of <b>new_addr</b> (given in host order),
  785. * and send an appropriate REMAP event. */
  786. static void
  787. remap_event_helper(edge_connection_t *conn, uint32_t new_addr)
  788. {
  789. struct in_addr in;
  790. in.s_addr = htonl(new_addr);
  791. tor_inet_ntoa(&in, conn->socks_request->address,
  792. sizeof(conn->socks_request->address));
  793. control_event_stream_status(conn, STREAM_EVENT_REMAP,
  794. REMAP_STREAM_SOURCE_EXIT);
  795. }
  796. /** An incoming relay cell has arrived from circuit <b>circ</b> to
  797. * stream <b>conn</b>.
  798. *
  799. * The arguments here are the same as in
  800. * connection_edge_process_relay_cell() below; this function is called
  801. * from there when <b>conn</b> is defined and not in an open state.
  802. */
  803. static int
  804. connection_edge_process_relay_cell_not_open(
  805. relay_header_t *rh, cell_t *cell, circuit_t *circ,
  806. edge_connection_t *conn, crypt_path_t *layer_hint)
  807. {
  808. if (rh->command == RELAY_COMMAND_END) {
  809. if (CIRCUIT_IS_ORIGIN(circ))
  810. return connection_edge_process_end_not_open(rh, cell,
  811. TO_ORIGIN_CIRCUIT(circ), conn,
  812. layer_hint);
  813. else
  814. return 0;
  815. }
  816. if (conn->_base.type == CONN_TYPE_AP &&
  817. rh->command == RELAY_COMMAND_CONNECTED) {
  818. tor_assert(CIRCUIT_IS_ORIGIN(circ));
  819. if (conn->_base.state != AP_CONN_STATE_CONNECT_WAIT) {
  820. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  821. "Got 'connected' while not in state connect_wait. Dropping.");
  822. return 0;
  823. }
  824. conn->_base.state = AP_CONN_STATE_OPEN;
  825. log_info(LD_APP,"'connected' received after %d seconds.",
  826. (int)(time(NULL) - conn->_base.timestamp_lastread));
  827. if (rh->length >= 4) {
  828. uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE));
  829. int ttl;
  830. if (!addr || (get_options()->ClientDNSRejectInternalAddresses &&
  831. is_internal_IP(addr, 0))) {
  832. char buf[INET_NTOA_BUF_LEN];
  833. struct in_addr a;
  834. a.s_addr = htonl(addr);
  835. tor_inet_ntoa(&a, buf, sizeof(buf));
  836. log_info(LD_APP,
  837. "...but it claims the IP address was %s. Closing.", buf);
  838. connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
  839. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  840. return 0;
  841. }
  842. if (rh->length >= 8)
  843. ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+4));
  844. else
  845. ttl = -1;
  846. client_dns_set_addressmap(conn->socks_request->address, addr,
  847. conn->chosen_exit_name, ttl);
  848. remap_event_helper(conn, addr);
  849. }
  850. circuit_log_path(LOG_INFO,LD_APP,TO_ORIGIN_CIRCUIT(circ));
  851. /* don't send a socks reply to transparent conns */
  852. if (!conn->socks_request->has_finished)
  853. connection_ap_handshake_socks_reply(conn, NULL, 0, 0);
  854. /* handle anything that might have queued */
  855. if (connection_edge_package_raw_inbuf(conn, 1) < 0) {
  856. /* (We already sent an end cell if possible) */
  857. connection_mark_for_close(TO_CONN(conn));
  858. return 0;
  859. }
  860. return 0;
  861. }
  862. if (conn->_base.type == CONN_TYPE_AP &&
  863. rh->command == RELAY_COMMAND_RESOLVED) {
  864. int ttl;
  865. int answer_len;
  866. uint8_t answer_type;
  867. if (conn->_base.state != AP_CONN_STATE_RESOLVE_WAIT) {
  868. log_fn(LOG_PROTOCOL_WARN, LD_APP, "Got a 'resolved' cell while "
  869. "not in state resolve_wait. Dropping.");
  870. return 0;
  871. }
  872. tor_assert(SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command));
  873. answer_len = cell->payload[RELAY_HEADER_SIZE+1];
  874. if (rh->length < 2 || answer_len+2>rh->length) {
  875. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  876. "Dropping malformed 'resolved' cell");
  877. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  878. return 0;
  879. }
  880. answer_type = cell->payload[RELAY_HEADER_SIZE];
  881. if (rh->length >= answer_len+6)
  882. ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+
  883. 2+answer_len));
  884. else
  885. ttl = -1;
  886. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len >= 4) {
  887. uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+2));
  888. if (get_options()->ClientDNSRejectInternalAddresses &&
  889. is_internal_IP(addr, 0)) {
  890. char buf[INET_NTOA_BUF_LEN];
  891. struct in_addr a;
  892. a.s_addr = htonl(addr);
  893. tor_inet_ntoa(&a, buf, sizeof(buf));
  894. log_info(LD_APP,"Got a resolve with answer %s. Rejecting.", buf);
  895. connection_ap_handshake_socks_resolved(conn,
  896. RESOLVED_TYPE_ERROR_TRANSIENT,
  897. 0, NULL, 0, TIME_MAX);
  898. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  899. return 0;
  900. }
  901. }
  902. connection_ap_handshake_socks_resolved(conn,
  903. answer_type,
  904. cell->payload[RELAY_HEADER_SIZE+1], /*answer_len*/
  905. cell->payload+RELAY_HEADER_SIZE+2, /*answer*/
  906. ttl,
  907. -1);
  908. if (answer_type == RESOLVED_TYPE_IPV4) {
  909. uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+2));
  910. remap_event_helper(conn, addr);
  911. }
  912. connection_mark_unattached_ap(conn,
  913. END_STREAM_REASON_DONE |
  914. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  915. return 0;
  916. }
  917. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  918. "Got an unexpected relay command %d, in state %d (%s). Dropping.",
  919. rh->command, conn->_base.state,
  920. conn_state_to_string(conn->_base.type, conn->_base.state));
  921. return 0; /* for forward compatibility, don't kill the circuit */
  922. // connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
  923. // connection_mark_for_close(conn);
  924. // return -1;
  925. }
  926. /** An incoming relay cell has arrived on circuit <b>circ</b>. If
  927. * <b>conn</b> is NULL this is a control cell, else <b>cell</b> is
  928. * destined for <b>conn</b>.
  929. *
  930. * If <b>layer_hint</b> is defined, then we're the origin of the
  931. * circuit, and it specifies the hop that packaged <b>cell</b>.
  932. *
  933. * Return -reason if you want to warn and tear down the circuit, else 0.
  934. */
  935. static int
  936. connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
  937. edge_connection_t *conn,
  938. crypt_path_t *layer_hint)
  939. {
  940. static int num_seen=0;
  941. relay_header_t rh;
  942. unsigned domain = layer_hint?LD_APP:LD_EXIT;
  943. int reason;
  944. tor_assert(cell);
  945. tor_assert(circ);
  946. relay_header_unpack(&rh, cell->payload);
  947. // log_fn(LOG_DEBUG,"command %d stream %d", rh.command, rh.stream_id);
  948. num_seen++;
  949. log_debug(domain, "Now seen %d relay cells here.", num_seen);
  950. if (rh.length > RELAY_PAYLOAD_SIZE) {
  951. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  952. "Relay cell length field too long. Closing circuit.");
  953. return - END_CIRC_REASON_TORPROTOCOL;
  954. }
  955. /* either conn is NULL, in which case we've got a control cell, or else
  956. * conn points to the recognized stream. */
  957. if (conn && !connection_state_is_open(TO_CONN(conn)))
  958. return connection_edge_process_relay_cell_not_open(
  959. &rh, cell, circ, conn, layer_hint);
  960. switch (rh.command) {
  961. case RELAY_COMMAND_DROP:
  962. // log_info(domain,"Got a relay-level padding cell. Dropping.");
  963. return 0;
  964. case RELAY_COMMAND_BEGIN:
  965. case RELAY_COMMAND_BEGIN_DIR:
  966. if (layer_hint &&
  967. circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
  968. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  969. "Relay begin request unsupported at AP. Dropping.");
  970. return 0;
  971. }
  972. if (conn) {
  973. log_fn(LOG_PROTOCOL_WARN, domain,
  974. "Begin cell for known stream. Dropping.");
  975. return 0;
  976. }
  977. return connection_exit_begin_conn(cell, circ);
  978. case RELAY_COMMAND_DATA:
  979. ++stats_n_data_cells_received;
  980. if (( layer_hint && --layer_hint->deliver_window < 0) ||
  981. (!layer_hint && --circ->deliver_window < 0)) {
  982. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  983. "(relay data) circ deliver_window below 0. Killing.");
  984. connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
  985. connection_mark_for_close(TO_CONN(conn));
  986. return -END_CIRC_REASON_TORPROTOCOL;
  987. }
  988. log_debug(domain,"circ deliver_window now %d.", layer_hint ?
  989. layer_hint->deliver_window : circ->deliver_window);
  990. circuit_consider_sending_sendme(circ, layer_hint);
  991. if (!conn) {
  992. log_info(domain,"data cell dropped, unknown stream.");
  993. return 0;
  994. }
  995. if (--conn->deliver_window < 0) { /* is it below 0 after decrement? */
  996. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  997. "(relay data) conn deliver_window below 0. Killing.");
  998. return -END_CIRC_REASON_TORPROTOCOL;
  999. }
  1000. stats_n_data_bytes_received += rh.length;
  1001. connection_write_to_buf(cell->payload + RELAY_HEADER_SIZE,
  1002. rh.length, TO_CONN(conn));
  1003. connection_edge_consider_sending_sendme(conn);
  1004. return 0;
  1005. case RELAY_COMMAND_END:
  1006. reason = rh.length > 0 ?
  1007. *(uint8_t *)(cell->payload+RELAY_HEADER_SIZE) : END_STREAM_REASON_MISC;
  1008. if (!conn) {
  1009. log_info(domain,"end cell (%s) dropped, unknown stream.",
  1010. connection_edge_end_reason_str(reason));
  1011. return 0;
  1012. }
  1013. /* XXX add to this log_fn the exit node's nickname? */
  1014. log_info(domain,"%d: end cell (%s) for stream %d. Removing stream.",
  1015. conn->_base.s,
  1016. connection_edge_end_reason_str(reason),
  1017. conn->stream_id);
  1018. if (conn->socks_request && !conn->socks_request->has_finished)
  1019. log_warn(LD_BUG,
  1020. "open stream hasn't sent socks answer yet? Closing.");
  1021. /* We just *got* an end; no reason to send one. */
  1022. conn->_base.edge_has_sent_end = 1;
  1023. if (!conn->end_reason)
  1024. conn->end_reason = reason | END_STREAM_REASON_FLAG_REMOTE;
  1025. if (!conn->_base.marked_for_close) {
  1026. /* only mark it if not already marked. it's possible to
  1027. * get the 'end' right around when the client hangs up on us. */
  1028. connection_mark_for_close(TO_CONN(conn));
  1029. conn->_base.hold_open_until_flushed = 1;
  1030. }
  1031. return 0;
  1032. case RELAY_COMMAND_EXTEND:
  1033. if (conn) {
  1034. log_fn(LOG_PROTOCOL_WARN, domain,
  1035. "'extend' cell received for non-zero stream. Dropping.");
  1036. return 0;
  1037. }
  1038. return circuit_extend(cell, circ);
  1039. case RELAY_COMMAND_EXTENDED:
  1040. if (!layer_hint) {
  1041. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1042. "'extended' unsupported at non-origin. Dropping.");
  1043. return 0;
  1044. }
  1045. log_debug(domain,"Got an extended cell! Yay.");
  1046. if ((reason = circuit_finish_handshake(TO_ORIGIN_CIRCUIT(circ),
  1047. CELL_CREATED,
  1048. cell->payload+RELAY_HEADER_SIZE)) < 0) {
  1049. log_warn(domain,"circuit_finish_handshake failed.");
  1050. return reason;
  1051. }
  1052. if ((reason=circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ)))<0) {
  1053. log_info(domain,"circuit_send_next_onion_skin() failed.");
  1054. return reason;
  1055. }
  1056. return 0;
  1057. case RELAY_COMMAND_TRUNCATE:
  1058. if (layer_hint) {
  1059. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  1060. "'truncate' unsupported at origin. Dropping.");
  1061. return 0;
  1062. }
  1063. if (circ->n_conn) {
  1064. uint8_t trunc_reason = *(uint8_t*)(cell->payload + RELAY_HEADER_SIZE);
  1065. connection_or_send_destroy(circ->n_circ_id, circ->n_conn,
  1066. trunc_reason);
  1067. circuit_set_n_circid_orconn(circ, 0, NULL);
  1068. }
  1069. log_debug(LD_EXIT, "Processed 'truncate', replying.");
  1070. {
  1071. char payload[1];
  1072. payload[0] = (char)END_CIRC_REASON_REQUESTED;
  1073. relay_send_command_from_edge(0, circ, RELAY_COMMAND_TRUNCATED,
  1074. payload, sizeof(payload), NULL);
  1075. }
  1076. return 0;
  1077. case RELAY_COMMAND_TRUNCATED:
  1078. if (!layer_hint) {
  1079. log_fn(LOG_PROTOCOL_WARN, LD_EXIT,
  1080. "'truncated' unsupported at non-origin. Dropping.");
  1081. return 0;
  1082. }
  1083. circuit_truncated(TO_ORIGIN_CIRCUIT(circ), layer_hint);
  1084. return 0;
  1085. case RELAY_COMMAND_CONNECTED:
  1086. if (conn) {
  1087. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1088. "'connected' unsupported while open. Closing circ.");
  1089. return -END_CIRC_REASON_TORPROTOCOL;
  1090. }
  1091. log_info(domain,
  1092. "'connected' received, no conn attached anymore. Ignoring.");
  1093. return 0;
  1094. case RELAY_COMMAND_SENDME:
  1095. if (!conn) {
  1096. if (layer_hint) {
  1097. layer_hint->package_window += CIRCWINDOW_INCREMENT;
  1098. log_debug(LD_APP,"circ-level sendme at origin, packagewindow %d.",
  1099. layer_hint->package_window);
  1100. circuit_resume_edge_reading(circ, layer_hint);
  1101. } else {
  1102. circ->package_window += CIRCWINDOW_INCREMENT;
  1103. log_debug(LD_APP,
  1104. "circ-level sendme at non-origin, packagewindow %d.",
  1105. circ->package_window);
  1106. circuit_resume_edge_reading(circ, layer_hint);
  1107. }
  1108. return 0;
  1109. }
  1110. conn->package_window += STREAMWINDOW_INCREMENT;
  1111. log_debug(domain,"stream-level sendme, packagewindow now %d.",
  1112. conn->package_window);
  1113. connection_start_reading(TO_CONN(conn));
  1114. /* handle whatever might still be on the inbuf */
  1115. if (connection_edge_package_raw_inbuf(conn, 1) < 0) {
  1116. /* (We already sent an end cell if possible) */
  1117. connection_mark_for_close(TO_CONN(conn));
  1118. return 0;
  1119. }
  1120. return 0;
  1121. case RELAY_COMMAND_RESOLVE:
  1122. if (layer_hint) {
  1123. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  1124. "resolve request unsupported at AP; dropping.");
  1125. return 0;
  1126. } else if (conn) {
  1127. log_fn(LOG_PROTOCOL_WARN, domain,
  1128. "resolve request for known stream; dropping.");
  1129. return 0;
  1130. } else if (circ->purpose != CIRCUIT_PURPOSE_OR) {
  1131. log_fn(LOG_PROTOCOL_WARN, domain,
  1132. "resolve request on circ with purpose %d; dropping",
  1133. circ->purpose);
  1134. return 0;
  1135. }
  1136. connection_exit_begin_resolve(cell, TO_OR_CIRCUIT(circ));
  1137. return 0;
  1138. case RELAY_COMMAND_RESOLVED:
  1139. if (conn) {
  1140. log_fn(LOG_PROTOCOL_WARN, domain,
  1141. "'resolved' unsupported while open. Closing circ.");
  1142. return -END_CIRC_REASON_TORPROTOCOL;
  1143. }
  1144. log_info(domain,
  1145. "'resolved' received, no conn attached anymore. Ignoring.");
  1146. return 0;
  1147. case RELAY_COMMAND_ESTABLISH_INTRO:
  1148. case RELAY_COMMAND_ESTABLISH_RENDEZVOUS:
  1149. case RELAY_COMMAND_INTRODUCE1:
  1150. case RELAY_COMMAND_INTRODUCE2:
  1151. case RELAY_COMMAND_INTRODUCE_ACK:
  1152. case RELAY_COMMAND_RENDEZVOUS1:
  1153. case RELAY_COMMAND_RENDEZVOUS2:
  1154. case RELAY_COMMAND_INTRO_ESTABLISHED:
  1155. case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
  1156. rend_process_relay_cell(circ, rh.command, rh.length,
  1157. cell->payload+RELAY_HEADER_SIZE);
  1158. return 0;
  1159. }
  1160. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1161. "Received unknown relay command %d. Perhaps the other side is using "
  1162. "a newer version of Tor? Dropping.",
  1163. rh.command);
  1164. return 0; /* for forward compatibility, don't kill the circuit */
  1165. }
  1166. uint64_t stats_n_data_cells_packaged = 0;
  1167. uint64_t stats_n_data_bytes_packaged = 0;
  1168. uint64_t stats_n_data_cells_received = 0;
  1169. uint64_t stats_n_data_bytes_received = 0;
  1170. /** While conn->inbuf has an entire relay payload of bytes on it,
  1171. * and the appropriate package windows aren't empty, grab a cell
  1172. * and send it down the circuit.
  1173. *
  1174. * Return -1 (and send a RELAY_END cell if necessary) if conn should
  1175. * be marked for close, else return 0.
  1176. */
  1177. int
  1178. connection_edge_package_raw_inbuf(edge_connection_t *conn, int package_partial)
  1179. {
  1180. size_t amount_to_process, length;
  1181. char payload[CELL_PAYLOAD_SIZE];
  1182. circuit_t *circ;
  1183. unsigned domain = conn->cpath_layer ? LD_APP : LD_EXIT;
  1184. tor_assert(conn);
  1185. if (conn->_base.marked_for_close) {
  1186. log_warn(LD_BUG,
  1187. "called on conn that's already marked for close at %s:%d.",
  1188. conn->_base.marked_for_close_file, conn->_base.marked_for_close);
  1189. return 0;
  1190. }
  1191. repeat_connection_edge_package_raw_inbuf:
  1192. circ = circuit_get_by_edge_conn(conn);
  1193. if (!circ) {
  1194. log_info(domain,"conn has no circuit! Closing.");
  1195. conn->end_reason = END_STREAM_REASON_CANT_ATTACH;
  1196. return -1;
  1197. }
  1198. if (circuit_consider_stop_edge_reading(circ, conn->cpath_layer))
  1199. return 0;
  1200. if (conn->package_window <= 0) {
  1201. log_info(domain,"called with package_window %d. Skipping.",
  1202. conn->package_window);
  1203. connection_stop_reading(TO_CONN(conn));
  1204. return 0;
  1205. }
  1206. amount_to_process = buf_datalen(conn->_base.inbuf);
  1207. if (!amount_to_process)
  1208. return 0;
  1209. if (!package_partial && amount_to_process < RELAY_PAYLOAD_SIZE)
  1210. return 0;
  1211. if (amount_to_process > RELAY_PAYLOAD_SIZE) {
  1212. length = RELAY_PAYLOAD_SIZE;
  1213. } else {
  1214. length = amount_to_process;
  1215. }
  1216. stats_n_data_bytes_packaged += length;
  1217. stats_n_data_cells_packaged += 1;
  1218. connection_fetch_from_buf(payload, length, TO_CONN(conn));
  1219. log_debug(domain,"(%d) Packaging %d bytes (%d waiting).", conn->_base.s,
  1220. (int)length, (int)buf_datalen(conn->_base.inbuf));
  1221. if (connection_edge_send_command(conn, RELAY_COMMAND_DATA,
  1222. payload, length) < 0 )
  1223. /* circuit got marked for close, don't continue, don't need to mark conn */
  1224. return 0;
  1225. if (!conn->cpath_layer) { /* non-rendezvous exit */
  1226. tor_assert(circ->package_window > 0);
  1227. circ->package_window--;
  1228. } else { /* we're an AP, or an exit on a rendezvous circ */
  1229. tor_assert(conn->cpath_layer->package_window > 0);
  1230. conn->cpath_layer->package_window--;
  1231. }
  1232. if (--conn->package_window <= 0) { /* is it 0 after decrement? */
  1233. connection_stop_reading(TO_CONN(conn));
  1234. log_debug(domain,"conn->package_window reached 0.");
  1235. circuit_consider_stop_edge_reading(circ, conn->cpath_layer);
  1236. return 0; /* don't process the inbuf any more */
  1237. }
  1238. log_debug(domain,"conn->package_window is now %d",conn->package_window);
  1239. /* handle more if there's more, or return 0 if there isn't */
  1240. goto repeat_connection_edge_package_raw_inbuf;
  1241. }
  1242. /** Called when we've just received a relay data cell, or when
  1243. * we've just finished flushing all bytes to stream <b>conn</b>.
  1244. *
  1245. * If conn->outbuf is not too full, and our deliver window is
  1246. * low, send back a suitable number of stream-level sendme cells.
  1247. */
  1248. void
  1249. connection_edge_consider_sending_sendme(edge_connection_t *conn)
  1250. {
  1251. circuit_t *circ;
  1252. if (connection_outbuf_too_full(TO_CONN(conn)))
  1253. return;
  1254. circ = circuit_get_by_edge_conn(conn);
  1255. if (!circ) {
  1256. /* this can legitimately happen if the destroy has already
  1257. * arrived and torn down the circuit */
  1258. log_info(LD_APP,"No circuit associated with conn. Skipping.");
  1259. return;
  1260. }
  1261. while (conn->deliver_window < STREAMWINDOW_START - STREAMWINDOW_INCREMENT) {
  1262. log_debug(conn->cpath_layer?LD_APP:LD_EXIT,
  1263. "Outbuf %d, Queueing stream sendme.",
  1264. (int)conn->_base.outbuf_flushlen);
  1265. conn->deliver_window += STREAMWINDOW_INCREMENT;
  1266. if (connection_edge_send_command(conn, RELAY_COMMAND_SENDME,
  1267. NULL, 0) < 0) {
  1268. log_warn(LD_APP,"connection_edge_send_command failed. Returning.");
  1269. return; /* the circuit's closed, don't continue */
  1270. }
  1271. }
  1272. }
  1273. /** The circuit <b>circ</b> has received a circuit-level sendme
  1274. * (on hop <b>layer_hint</b>, if we're the OP). Go through all the
  1275. * attached streams and let them resume reading and packaging, if
  1276. * their stream windows allow it.
  1277. */
  1278. static void
  1279. circuit_resume_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
  1280. {
  1281. log_debug(layer_hint?LD_APP:LD_EXIT,"resuming");
  1282. if (CIRCUIT_IS_ORIGIN(circ))
  1283. circuit_resume_edge_reading_helper(TO_ORIGIN_CIRCUIT(circ)->p_streams,
  1284. circ, layer_hint);
  1285. else
  1286. circuit_resume_edge_reading_helper(TO_OR_CIRCUIT(circ)->n_streams,
  1287. circ, layer_hint);
  1288. }
  1289. /** A helper function for circuit_resume_edge_reading() above.
  1290. * The arguments are the same, except that <b>conn</b> is the head
  1291. * of a linked list of edge streams that should each be considered.
  1292. */
  1293. static int
  1294. circuit_resume_edge_reading_helper(edge_connection_t *conn,
  1295. circuit_t *circ,
  1296. crypt_path_t *layer_hint)
  1297. {
  1298. for ( ; conn; conn=conn->next_stream) {
  1299. if (conn->_base.marked_for_close)
  1300. continue;
  1301. if ((!layer_hint && conn->package_window > 0) ||
  1302. (layer_hint && conn->package_window > 0 &&
  1303. conn->cpath_layer == layer_hint)) {
  1304. connection_start_reading(TO_CONN(conn));
  1305. /* handle whatever might still be on the inbuf */
  1306. if (connection_edge_package_raw_inbuf(conn, 1)<0) {
  1307. /* (We already sent an end cell if possible) */
  1308. connection_mark_for_close(TO_CONN(conn));
  1309. continue;
  1310. }
  1311. /* If the circuit won't accept any more data, return without looking
  1312. * at any more of the streams. Any connections that should be stopped
  1313. * have already been stopped by connection_edge_package_raw_inbuf. */
  1314. if (circuit_consider_stop_edge_reading(circ, layer_hint))
  1315. return -1;
  1316. }
  1317. }
  1318. return 0;
  1319. }
  1320. /** Check if the package window for <b>circ</b> is empty (at
  1321. * hop <b>layer_hint</b> if it's defined).
  1322. *
  1323. * If yes, tell edge streams to stop reading and return 1.
  1324. * Else return 0.
  1325. */
  1326. static int
  1327. circuit_consider_stop_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
  1328. {
  1329. edge_connection_t *conn = NULL;
  1330. unsigned domain = layer_hint ? LD_APP : LD_EXIT;
  1331. if (!layer_hint) {
  1332. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  1333. log_debug(domain,"considering circ->package_window %d",
  1334. circ->package_window);
  1335. if (circ->package_window <= 0) {
  1336. log_debug(domain,"yes, not-at-origin. stopped.");
  1337. for (conn = or_circ->n_streams; conn; conn=conn->next_stream)
  1338. connection_stop_reading(TO_CONN(conn));
  1339. return 1;
  1340. }
  1341. return 0;
  1342. }
  1343. /* else, layer hint is defined, use it */
  1344. log_debug(domain,"considering layer_hint->package_window %d",
  1345. layer_hint->package_window);
  1346. if (layer_hint->package_window <= 0) {
  1347. log_debug(domain,"yes, at-origin. stopped.");
  1348. for (conn = TO_ORIGIN_CIRCUIT(circ)->p_streams; conn;
  1349. conn=conn->next_stream)
  1350. if (conn->cpath_layer == layer_hint)
  1351. connection_stop_reading(TO_CONN(conn));
  1352. return 1;
  1353. }
  1354. return 0;
  1355. }
  1356. /** Check if the deliver_window for circuit <b>circ</b> (at hop
  1357. * <b>layer_hint</b> if it's defined) is low enough that we should
  1358. * send a circuit-level sendme back down the circuit. If so, send
  1359. * enough sendmes that the window would be overfull if we sent any
  1360. * more.
  1361. */
  1362. static void
  1363. circuit_consider_sending_sendme(circuit_t *circ, crypt_path_t *layer_hint)
  1364. {
  1365. // log_fn(LOG_INFO,"Considering: layer_hint is %s",
  1366. // layer_hint ? "defined" : "null");
  1367. while ((layer_hint ? layer_hint->deliver_window : circ->deliver_window) <
  1368. CIRCWINDOW_START - CIRCWINDOW_INCREMENT) {
  1369. log_debug(LD_CIRC,"Queueing circuit sendme.");
  1370. if (layer_hint)
  1371. layer_hint->deliver_window += CIRCWINDOW_INCREMENT;
  1372. else
  1373. circ->deliver_window += CIRCWINDOW_INCREMENT;
  1374. if (relay_send_command_from_edge(0, circ, RELAY_COMMAND_SENDME,
  1375. NULL, 0, layer_hint) < 0) {
  1376. log_warn(LD_CIRC,
  1377. "connection_edge_send_command failed. Circuit's closed.");
  1378. return; /* the circuit's closed, don't continue */
  1379. }
  1380. }
  1381. }
  1382. /** Stop reading on edge connections when we have this many cells
  1383. * waiting on the appropriate queue. */
  1384. #define CELL_QUEUE_HIGHWATER_SIZE 256
  1385. /** Start reading from edge connections again when we get down to this many
  1386. * cells. */
  1387. #define CELL_QUEUE_LOWWATER_SIZE 64
  1388. #ifdef ACTIVE_CIRCUITS_PARANOIA
  1389. #define assert_active_circuits_ok_paranoid(conn) \
  1390. assert_active_circuits_ok(conn)
  1391. #else
  1392. #define assert_active_circuits_ok_paranoid(conn)
  1393. #endif
  1394. /** The total number of cells we have allocated from the memory pool. */
  1395. static int total_cells_allocated = 0;
  1396. #ifdef ENABLE_CELL_POOL /* Defined in ./configure. True by default. */
  1397. /* XXX020 make cell pools the only option once we know they work? -RD */
  1398. static mp_pool_t *cell_pool = NULL;
  1399. /** Allocate structures to hold cells. */
  1400. void
  1401. init_cell_pool(void)
  1402. {
  1403. tor_assert(!cell_pool);
  1404. cell_pool = mp_pool_new(sizeof(packed_cell_t), 1<<19);
  1405. }
  1406. /** Free all storage used to hold cells. */
  1407. void
  1408. free_cell_pool(void)
  1409. {
  1410. /* Maybe we haven't called init_cell_pool yet; need to check for it. */
  1411. if (cell_pool) {
  1412. mp_pool_destroy(cell_pool);
  1413. cell_pool = NULL;
  1414. }
  1415. }
  1416. /** Free excess storage in cell pool. */
  1417. void
  1418. clean_cell_pool(void)
  1419. {
  1420. tor_assert(cell_pool);
  1421. mp_pool_clean(cell_pool, -1);
  1422. }
  1423. /** Release storage held by <b>cell</b>. */
  1424. static INLINE void
  1425. packed_cell_free(packed_cell_t *cell)
  1426. {
  1427. --total_cells_allocated;
  1428. mp_pool_release(cell);
  1429. }
  1430. /** Allocate and return a new packed_cell_t. */
  1431. static INLINE packed_cell_t *
  1432. packed_cell_alloc(void)
  1433. {
  1434. ++total_cells_allocated;
  1435. return mp_pool_get(cell_pool);
  1436. }
  1437. void
  1438. dump_cell_pool_usage(int severity)
  1439. {
  1440. circuit_t *c;
  1441. int n_circs = 0;
  1442. int n_cells = 0;
  1443. for (c = _circuit_get_global_list(); c; c = c->next) {
  1444. n_cells += c->n_conn_cells.n;
  1445. if (!CIRCUIT_IS_ORIGIN(c))
  1446. n_cells += TO_OR_CIRCUIT(c)->p_conn_cells.n;
  1447. ++n_circs;
  1448. }
  1449. log(severity, LD_MM, "%d cells allocated on %d circuits. %d cells leaked.",
  1450. n_cells, n_circs, total_cells_allocated - n_cells);
  1451. mp_pool_log_status(cell_pool, severity);
  1452. }
  1453. #else
  1454. /* ENABLE_CELL_POOL isn't defined: here are some stubs to use tor_malloc()
  1455. * and tor_free() instead. */
  1456. void
  1457. init_cell_pool(void)
  1458. {
  1459. }
  1460. void
  1461. free_cell_pool(void)
  1462. {
  1463. }
  1464. void
  1465. clean_cell_pool(void)
  1466. {
  1467. }
  1468. static INLINE void
  1469. packed_cell_free(packed_cell_t *cell)
  1470. {
  1471. --total_cells_allocated;
  1472. tor_free(cell);
  1473. }
  1474. static INLINE packed_cell_t *
  1475. packed_cell_alloc(void)
  1476. {
  1477. ++total_cells_allocated;
  1478. return tor_malloc(sizeof(packed_cell_t));
  1479. }
  1480. void
  1481. dump_cell_pool_usage(int severity)
  1482. {
  1483. (void) severity;
  1484. }
  1485. #endif
  1486. /** Allocate a new copy of packed <b>cell</b>. */
  1487. static INLINE packed_cell_t *
  1488. packed_cell_copy(const cell_t *cell)
  1489. {
  1490. packed_cell_t *c = packed_cell_alloc();
  1491. cell_pack(c, cell);
  1492. c->next = NULL;
  1493. return c;
  1494. }
  1495. /** Append <b>cell</b> to the end of <b>queue</b>. */
  1496. void
  1497. cell_queue_append(cell_queue_t *queue, packed_cell_t *cell)
  1498. {
  1499. if (queue->tail) {
  1500. tor_assert(!queue->tail->next);
  1501. queue->tail->next = cell;
  1502. } else {
  1503. queue->head = cell;
  1504. }
  1505. queue->tail = cell;
  1506. cell->next = NULL;
  1507. ++queue->n;
  1508. }
  1509. /** Append a newly allocated copy of <b>cell</b> to the end of <b>queue</b> */
  1510. void
  1511. cell_queue_append_packed_copy(cell_queue_t *queue, const cell_t *cell)
  1512. {
  1513. cell_queue_append(queue, packed_cell_copy(cell));
  1514. }
  1515. /** Remove and free every cell in <b>queue</b>. */
  1516. void
  1517. cell_queue_clear(cell_queue_t *queue)
  1518. {
  1519. packed_cell_t *cell, *next;
  1520. cell = queue->head;
  1521. while (cell) {
  1522. next = cell->next;
  1523. packed_cell_free(cell);
  1524. cell = next;
  1525. }
  1526. queue->head = queue->tail = NULL;
  1527. queue->n = 0;
  1528. }
  1529. /** Extract and return the cell at the head of <b>queue</b>; return NULL if
  1530. * <b>queue</b> is empty. */
  1531. static INLINE packed_cell_t *
  1532. cell_queue_pop(cell_queue_t *queue)
  1533. {
  1534. packed_cell_t *cell = queue->head;
  1535. if (!cell)
  1536. return NULL;
  1537. queue->head = cell->next;
  1538. if (cell == queue->tail) {
  1539. tor_assert(!queue->head);
  1540. queue->tail = NULL;
  1541. }
  1542. --queue->n;
  1543. return cell;
  1544. }
  1545. /** Return a pointer to the "next_active_on_{n,p}_conn" pointer of <b>circ</b>,
  1546. * depending on whether <b>conn</b> matches n_conn or p_conn. */
  1547. static INLINE circuit_t **
  1548. next_circ_on_conn_p(circuit_t *circ, or_connection_t *conn)
  1549. {
  1550. tor_assert(circ);
  1551. tor_assert(conn);
  1552. if (conn == circ->n_conn) {
  1553. return &circ->next_active_on_n_conn;
  1554. } else {
  1555. or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
  1556. tor_assert(conn == orcirc->p_conn);
  1557. return &orcirc->next_active_on_p_conn;
  1558. }
  1559. }
  1560. /** Return a pointer to the "prev_active_on_{n,p}_conn" pointer of <b>circ</b>,
  1561. * depending on whether <b>conn</b> matches n_conn or p_conn. */
  1562. static INLINE circuit_t **
  1563. prev_circ_on_conn_p(circuit_t *circ, or_connection_t *conn)
  1564. {
  1565. tor_assert(circ);
  1566. tor_assert(conn);
  1567. if (conn == circ->n_conn) {
  1568. return &circ->prev_active_on_n_conn;
  1569. } else {
  1570. or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
  1571. tor_assert(conn == orcirc->p_conn);
  1572. return &orcirc->prev_active_on_p_conn;
  1573. }
  1574. }
  1575. /** Add <b>circ</b> to the list of circuits with pending cells on
  1576. * <b>conn</b>. No effect if <b>circ</b> is already unlinked. */
  1577. void
  1578. make_circuit_active_on_conn(circuit_t *circ, or_connection_t *conn)
  1579. {
  1580. circuit_t **nextp = next_circ_on_conn_p(circ, conn);
  1581. circuit_t **prevp = prev_circ_on_conn_p(circ, conn);
  1582. if (*nextp && *prevp) {
  1583. /* Already active. */
  1584. return;
  1585. }
  1586. if (! conn->active_circuits) {
  1587. conn->active_circuits = circ;
  1588. *prevp = *nextp = circ;
  1589. } else {
  1590. circuit_t *head = conn->active_circuits;
  1591. circuit_t *old_tail = *prev_circ_on_conn_p(head, conn);
  1592. *next_circ_on_conn_p(old_tail, conn) = circ;
  1593. *nextp = head;
  1594. *prev_circ_on_conn_p(head, conn) = circ;
  1595. *prevp = old_tail;
  1596. }
  1597. assert_active_circuits_ok_paranoid(conn);
  1598. }
  1599. /** Remove <b>circ</b> to the list of circuits with pending cells on
  1600. * <b>conn</b>. No effect if <b>circ</b> is already unlinked. */
  1601. void
  1602. make_circuit_inactive_on_conn(circuit_t *circ, or_connection_t *conn)
  1603. {
  1604. circuit_t **nextp = next_circ_on_conn_p(circ, conn);
  1605. circuit_t **prevp = prev_circ_on_conn_p(circ, conn);
  1606. circuit_t *next = *nextp, *prev = *prevp;
  1607. if (!next && !prev) {
  1608. /* Already inactive. */
  1609. return;
  1610. }
  1611. tor_assert(next && prev);
  1612. tor_assert(*prev_circ_on_conn_p(next, conn) == circ);
  1613. tor_assert(*next_circ_on_conn_p(prev, conn) == circ);
  1614. if (next == circ) {
  1615. conn->active_circuits = NULL;
  1616. } else {
  1617. *prev_circ_on_conn_p(next, conn) = prev;
  1618. *next_circ_on_conn_p(prev, conn) = next;
  1619. if (conn->active_circuits == circ)
  1620. conn->active_circuits = next;
  1621. }
  1622. *prevp = *nextp = NULL;
  1623. assert_active_circuits_ok_paranoid(conn);
  1624. }
  1625. /** Remove all circuits from the list of circuits with pending cells on
  1626. * <b>conn</b>. */
  1627. void
  1628. connection_or_unlink_all_active_circs(or_connection_t *orconn)
  1629. {
  1630. circuit_t *head = orconn->active_circuits;
  1631. circuit_t *cur = head;
  1632. if (! head)
  1633. return;
  1634. do {
  1635. circuit_t *next = *next_circ_on_conn_p(cur, orconn);
  1636. *prev_circ_on_conn_p(cur, orconn) = NULL;
  1637. *next_circ_on_conn_p(cur, orconn) = NULL;
  1638. cur = next;
  1639. } while (cur != head);
  1640. orconn->active_circuits = NULL;
  1641. }
  1642. /** Block (if <b>block</b> is true) or unblock (if <b>block</b> is false)
  1643. * every edge connection that is using <b>circ</b> to write to <b>orconn</b>,
  1644. * and start or stop reading as appropriate. */
  1645. static void
  1646. set_streams_blocked_on_circ(circuit_t *circ, or_connection_t *orconn,
  1647. int block)
  1648. {
  1649. edge_connection_t *edge = NULL;
  1650. if (circ->n_conn == orconn) {
  1651. circ->streams_blocked_on_n_conn = block;
  1652. if (CIRCUIT_IS_ORIGIN(circ))
  1653. edge = TO_ORIGIN_CIRCUIT(circ)->p_streams;
  1654. } else {
  1655. circ->streams_blocked_on_p_conn = block;
  1656. tor_assert(!CIRCUIT_IS_ORIGIN(circ));
  1657. edge = TO_OR_CIRCUIT(circ)->n_streams;
  1658. }
  1659. for (; edge; edge = edge->next_stream) {
  1660. connection_t *conn = TO_CONN(edge);
  1661. conn->edge_blocked_on_circ = block;
  1662. if (block) {
  1663. if (connection_is_reading(conn))
  1664. connection_stop_reading(conn);
  1665. } else {
  1666. /* Is this right? */
  1667. if (!connection_is_reading(conn))
  1668. connection_start_reading(conn);
  1669. }
  1670. }
  1671. }
  1672. /** Pull as many cells as possible (but no more than <b>max</b>) from the
  1673. * queue of the first active circuit on <b>conn</b>, and write then to
  1674. * <b>conn</b>-&gt;outbuf. Return the number of cells written. Advance
  1675. * the active circuit pointer to the next active circuit in the ring. */
  1676. int
  1677. connection_or_flush_from_first_active_circuit(or_connection_t *conn, int max)
  1678. {
  1679. int n_flushed;
  1680. cell_queue_t *queue;
  1681. circuit_t *circ;
  1682. int streams_blocked;
  1683. circ = conn->active_circuits;
  1684. if (!circ) return 0;
  1685. assert_active_circuits_ok_paranoid(conn);
  1686. if (circ->n_conn == conn) {
  1687. queue = &circ->n_conn_cells;
  1688. streams_blocked = circ->streams_blocked_on_n_conn;
  1689. } else {
  1690. queue = &TO_OR_CIRCUIT(circ)->p_conn_cells;
  1691. streams_blocked = circ->streams_blocked_on_p_conn;
  1692. }
  1693. tor_assert(*next_circ_on_conn_p(circ,conn));
  1694. for (n_flushed = 0; n_flushed < max && queue->head; ) {
  1695. packed_cell_t *cell = cell_queue_pop(queue);
  1696. tor_assert(*next_circ_on_conn_p(circ,conn));
  1697. connection_write_to_buf(cell->body, CELL_NETWORK_SIZE, TO_CONN(conn));
  1698. packed_cell_free(cell);
  1699. ++n_flushed;
  1700. if (circ != conn->active_circuits) {
  1701. /* If this happens, the current circuit just got made inactive by
  1702. * a call in connection_write_to_buf(). That's nothing to worry about:
  1703. * circuit_make_inactive_on_conn() already advanced conn->active_circuits
  1704. * for us.
  1705. */
  1706. assert_active_circuits_ok_paranoid(conn);
  1707. return n_flushed;
  1708. }
  1709. }
  1710. tor_assert(*next_circ_on_conn_p(circ,conn));
  1711. assert_active_circuits_ok_paranoid(conn);
  1712. conn->active_circuits = *next_circ_on_conn_p(circ, conn);
  1713. /* Is the cell queue low enough to unblock all the streams that are waiting
  1714. * to write to this circuit? */
  1715. if (streams_blocked && queue->n <= CELL_QUEUE_LOWWATER_SIZE)
  1716. set_streams_blocked_on_circ(circ, conn, 0); /* unblock streams */
  1717. /* Did we just ran out of cells on this queue? */
  1718. if (queue->n == 0) {
  1719. log_debug(LD_GENERAL, "Made a circuit inactive.");
  1720. make_circuit_inactive_on_conn(circ, conn);
  1721. }
  1722. return n_flushed;
  1723. }
  1724. /** Add <b>cell</b> to the queue of <b>circ</b> writing to <b>orconn</b>
  1725. * transmitting in <b>direction</b>. */
  1726. void
  1727. append_cell_to_circuit_queue(circuit_t *circ, or_connection_t *orconn,
  1728. cell_t *cell, int direction)
  1729. {
  1730. cell_queue_t *queue;
  1731. int streams_blocked;
  1732. if (direction == CELL_DIRECTION_OUT) {
  1733. queue = &circ->n_conn_cells;
  1734. streams_blocked = circ->streams_blocked_on_n_conn;
  1735. } else {
  1736. or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
  1737. queue = &orcirc->p_conn_cells;
  1738. streams_blocked = circ->streams_blocked_on_p_conn;
  1739. }
  1740. if (cell->command == CELL_RELAY_EARLY && orconn->link_proto < 2) {
  1741. /* V1 connections don't understand RELAY_EARLY. */
  1742. cell->command = CELL_RELAY;
  1743. }
  1744. cell_queue_append_packed_copy(queue, cell);
  1745. /* If we have too many cells on the circuit, we should stop reading from
  1746. * the edge streams for a while. */
  1747. if (!streams_blocked && queue->n >= CELL_QUEUE_HIGHWATER_SIZE)
  1748. set_streams_blocked_on_circ(circ, orconn, 1); /* block streams */
  1749. if (queue->n == 1) {
  1750. /* This was the first cell added to the queue. We need to make this
  1751. * circuit active. */
  1752. log_debug(LD_GENERAL, "Made a circuit active.");
  1753. make_circuit_active_on_conn(circ, orconn);
  1754. }
  1755. if (! buf_datalen(orconn->_base.outbuf)) {
  1756. /* There is no data at all waiting to be sent on the outbuf. Add a
  1757. * cell, so that we can notice when it gets flushed, flushed_some can
  1758. * get called, and we can start putting more data onto the buffer then.
  1759. */
  1760. log_debug(LD_GENERAL, "Primed a buffer.");
  1761. connection_or_flush_from_first_active_circuit(orconn, 1);
  1762. }
  1763. }
  1764. /** Remove all the cells queued on <b>circ</b> for <b>orconn</b>. */
  1765. void
  1766. circuit_clear_cell_queue(circuit_t *circ, or_connection_t *orconn)
  1767. {
  1768. cell_queue_t *queue;
  1769. // int streams_blocked; // XXXX020 use this for something, or remove it.
  1770. if (circ->n_conn == orconn) {
  1771. queue = &circ->n_conn_cells;
  1772. // streams_blocked = circ->streams_blocked_on_n_conn;
  1773. } else {
  1774. or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
  1775. queue = &orcirc->p_conn_cells;
  1776. // streams_blocked = circ->streams_blocked_on_p_conn;
  1777. }
  1778. if (queue->n)
  1779. make_circuit_inactive_on_conn(circ,orconn);
  1780. cell_queue_clear(queue);
  1781. }
  1782. /** Fail with an assert if the active circuits ring on <b>orconn</b> is
  1783. * corrupt. */
  1784. void
  1785. assert_active_circuits_ok(or_connection_t *orconn)
  1786. {
  1787. circuit_t *head = orconn->active_circuits;
  1788. circuit_t *cur = head;
  1789. if (! head)
  1790. return;
  1791. do {
  1792. circuit_t *next = *next_circ_on_conn_p(cur, orconn);
  1793. circuit_t *prev = *prev_circ_on_conn_p(cur, orconn);
  1794. tor_assert(next);
  1795. tor_assert(prev);
  1796. tor_assert(*next_circ_on_conn_p(prev, orconn) == cur);
  1797. tor_assert(*prev_circ_on_conn_p(next, orconn) == cur);
  1798. cur = next;
  1799. } while (cur != head);
  1800. }