relay.c 64 KB

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