relay.c 63 KB

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