relay.c 66 KB

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