relay.c 65 KB

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