relay.c 65 KB

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