relay.c 66 KB

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