relay.c 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208
  1. /* Copyright 2001 Matej Pfajfar.
  2. * Copyright 2001-2004 Roger Dingledine.
  3. * Copyright 2004-2005 Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char relay_c_id[] = "$Id$";
  7. /**
  8. * \file relay.c
  9. * \brief Handle relay cell encryption/decryption, plus packaging and
  10. * receiving from circuits.
  11. **/
  12. #include "or.h"
  13. static int relay_crypt(circuit_t *circ, cell_t *cell, int cell_direction,
  14. crypt_path_t **layer_hint, char *recognized);
  15. static connection_t *relay_lookup_conn(circuit_t *circ, cell_t *cell, int cell_direction);
  16. static int
  17. connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
  18. connection_t *conn,
  19. crypt_path_t *layer_hint);
  20. static void
  21. circuit_consider_sending_sendme(circuit_t *circ, crypt_path_t *layer_hint);
  22. static void
  23. circuit_resume_edge_reading(circuit_t *circ, crypt_path_t *layer_hint);
  24. static int
  25. circuit_resume_edge_reading_helper(connection_t *conn,
  26. circuit_t *circ,
  27. crypt_path_t *layer_hint);
  28. static int
  29. circuit_consider_stop_edge_reading(circuit_t *circ, crypt_path_t *layer_hint);
  30. /** Stats: how many relay cells have originated at this hop, or have
  31. * been relayed onward (not recognized at this hop)?
  32. */
  33. unsigned long stats_n_relay_cells_relayed = 0;
  34. /** Stats: how many relay cells have been delivered to streams at this
  35. * hop?
  36. */
  37. unsigned long stats_n_relay_cells_delivered = 0;
  38. /** Update digest from the payload of cell. Assign integrity part to
  39. * cell.
  40. */
  41. static void relay_set_digest(crypto_digest_env_t *digest, cell_t *cell) {
  42. char integrity[4];
  43. relay_header_t rh;
  44. crypto_digest_add_bytes(digest, cell->payload, CELL_PAYLOAD_SIZE);
  45. crypto_digest_get_digest(digest, integrity, 4);
  46. // log_fn(LOG_DEBUG,"Putting digest of %u %u %u %u into relay cell.",
  47. // integrity[0], integrity[1], integrity[2], integrity[3]);
  48. relay_header_unpack(&rh, cell->payload);
  49. memcpy(rh.integrity, integrity, 4);
  50. relay_header_pack(cell->payload, &rh);
  51. }
  52. /** Does the digest for this circuit indicate that this cell is for us?
  53. *
  54. * Update digest from the payload of cell (with the integrity part set
  55. * to 0). If the integrity part is valid, return 1, else restore digest
  56. * and cell to their original state and return 0.
  57. */
  58. static int relay_digest_matches(crypto_digest_env_t *digest, cell_t *cell) {
  59. char received_integrity[4], calculated_integrity[4];
  60. relay_header_t rh;
  61. crypto_digest_env_t *backup_digest=NULL;
  62. backup_digest = crypto_digest_dup(digest);
  63. relay_header_unpack(&rh, cell->payload);
  64. memcpy(received_integrity, rh.integrity, 4);
  65. memset(rh.integrity, 0, 4);
  66. relay_header_pack(cell->payload, &rh);
  67. // log_fn(LOG_DEBUG,"Reading digest of %u %u %u %u from relay cell.",
  68. // received_integrity[0], received_integrity[1],
  69. // received_integrity[2], received_integrity[3]);
  70. crypto_digest_add_bytes(digest, cell->payload, CELL_PAYLOAD_SIZE);
  71. crypto_digest_get_digest(digest, calculated_integrity, 4);
  72. if (memcmp(received_integrity, calculated_integrity, 4)) {
  73. // log_fn(LOG_INFO,"Recognized=0 but bad digest. Not recognizing.");
  74. // (%d vs %d).", received_integrity, calculated_integrity);
  75. /* restore digest to its old form */
  76. crypto_digest_assign(digest, backup_digest);
  77. /* restore the relay header */
  78. memcpy(rh.integrity, received_integrity, 4);
  79. relay_header_pack(cell->payload, &rh);
  80. crypto_free_digest_env(backup_digest);
  81. return 0;
  82. }
  83. crypto_free_digest_env(backup_digest);
  84. return 1;
  85. }
  86. /** Apply <b>cipher</b> to CELL_PAYLOAD_SIZE bytes of <b>in</b>
  87. * (in place).
  88. *
  89. * If <b>encrypt_mode</b> is 1 then encrypt, else decrypt.
  90. *
  91. * Return -1 if the crypto fails, else return 0.
  92. */
  93. static int relay_crypt_one_payload(crypto_cipher_env_t *cipher, char *in,
  94. int encrypt_mode) {
  95. char out[CELL_PAYLOAD_SIZE]; /* 'in' must be this size too */
  96. if (( encrypt_mode && crypto_cipher_encrypt(cipher, out, in, CELL_PAYLOAD_SIZE)) ||
  97. (!encrypt_mode && crypto_cipher_decrypt(cipher, out, in, CELL_PAYLOAD_SIZE))) {
  98. log_fn(LOG_WARN,"Error during relay encryption");
  99. return -1;
  100. }
  101. memcpy(in,out,CELL_PAYLOAD_SIZE);
  102. return 0;
  103. }
  104. /** Receive a relay cell:
  105. * - Crypt it (encrypt APward, decrypt at AP, decrypt exitward).
  106. * - Check if recognized (if exitward).
  107. * - If recognized and the digest checks out, then find if there's
  108. * a conn that the cell is intended for, and deliver it to·
  109. * connection_edge.
  110. * - Else connection_or_write_cell_to_buf to the conn on the other
  111. * side of the circuit.
  112. */
  113. int circuit_receive_relay_cell(cell_t *cell, circuit_t *circ,
  114. int cell_direction) {
  115. connection_t *conn=NULL;
  116. crypt_path_t *layer_hint=NULL;
  117. char recognized=0;
  118. tor_assert(cell);
  119. tor_assert(circ);
  120. tor_assert(cell_direction == CELL_DIRECTION_OUT ||
  121. cell_direction == CELL_DIRECTION_IN);
  122. if (circ->marked_for_close)
  123. return 0;
  124. if (relay_crypt(circ, cell, cell_direction, &layer_hint, &recognized) < 0) {
  125. log_fn(LOG_WARN,"relay crypt failed. Dropping connection.");
  126. return -1;
  127. }
  128. if (recognized) {
  129. conn = relay_lookup_conn(circ, cell, cell_direction);
  130. if (cell_direction == CELL_DIRECTION_OUT) {
  131. ++stats_n_relay_cells_delivered;
  132. log_fn(LOG_DEBUG,"Sending away from origin.");
  133. if (connection_edge_process_relay_cell(cell, circ, conn, NULL) < 0) {
  134. log_fn(LOG_WARN,"connection_edge_process_relay_cell (away from origin) failed.");
  135. return -1;
  136. }
  137. }
  138. if (cell_direction == CELL_DIRECTION_IN) {
  139. ++stats_n_relay_cells_delivered;
  140. log_fn(LOG_DEBUG,"Sending to origin.");
  141. if (connection_edge_process_relay_cell(cell, circ, conn, layer_hint) < 0) {
  142. log_fn(LOG_WARN,"connection_edge_process_relay_cell (at origin) failed.");
  143. return -1;
  144. }
  145. }
  146. return 0;
  147. }
  148. /* not recognized. pass it on. */
  149. if (cell_direction == CELL_DIRECTION_OUT) {
  150. cell->circ_id = circ->n_circ_id; /* switch it */
  151. conn = circ->n_conn;
  152. } else {
  153. cell->circ_id = circ->p_circ_id; /* switch it */
  154. conn = circ->p_conn;
  155. }
  156. if (!conn) {
  157. if (circ->rend_splice && cell_direction == CELL_DIRECTION_OUT) {
  158. tor_assert(circ->purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED);
  159. tor_assert(circ->rend_splice->purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED);
  160. cell->circ_id = circ->rend_splice->p_circ_id;
  161. if (circuit_receive_relay_cell(cell, circ->rend_splice, CELL_DIRECTION_IN)<0) {
  162. log_fn(LOG_WARN, "Error relaying cell across rendezvous; closing circuits");
  163. circuit_mark_for_close(circ); /* XXXX Do this here, or just return -1? */
  164. return -1;
  165. }
  166. return 0;
  167. }
  168. log_fn(LOG_WARN,"Didn't recognize cell, but circ stops here! Closing circ.");
  169. return -1;
  170. }
  171. log_fn(LOG_DEBUG,"Passing on unrecognized cell.");
  172. ++stats_n_relay_cells_relayed;
  173. connection_or_write_cell_to_buf(cell, conn);
  174. return 0;
  175. }
  176. /** Do the appropriate en/decryptions for <b>cell</b> arriving on
  177. * <b>circ</b> in direction <b>cell_direction</b>.
  178. *
  179. * If cell_direction == CELL_DIRECTION_IN:
  180. * - If we're at the origin (we're the OP), for hops 1..N,
  181. * decrypt cell. If recognized, stop.
  182. * - Else (we're not the OP), encrypt one hop. Cell is not recognized.
  183. *
  184. * If cell_direction == CELL_DIRECTION_OUT:
  185. * - decrypt one hop. Check if recognized.
  186. *
  187. * If cell is recognized, set *recognized to 1, and set
  188. * *layer_hint to the hop that recognized it.
  189. *
  190. * Return -1 to indicate that we should mark the circuit for close,
  191. * else return 0.
  192. */
  193. /* wrap this into receive_relay_cell one day */
  194. static int relay_crypt(circuit_t *circ, cell_t *cell, int cell_direction,
  195. crypt_path_t **layer_hint, char *recognized) {
  196. crypt_path_t *thishop;
  197. relay_header_t rh;
  198. tor_assert(circ);
  199. tor_assert(cell);
  200. tor_assert(recognized);
  201. tor_assert(cell_direction == CELL_DIRECTION_IN ||
  202. cell_direction == CELL_DIRECTION_OUT);
  203. if (cell_direction == CELL_DIRECTION_IN) {
  204. if (CIRCUIT_IS_ORIGIN(circ)) { /* We're at the beginning of the circuit.
  205. We'll want to do layered decrypts. */
  206. tor_assert(circ->cpath);
  207. thishop = circ->cpath;
  208. if (thishop->state != CPATH_STATE_OPEN) {
  209. log_fn(LOG_WARN,"Relay cell before first created cell? Closing.");
  210. return -1;
  211. }
  212. do { /* Remember: cpath is in forward order, that is, first hop first. */
  213. tor_assert(thishop);
  214. if (relay_crypt_one_payload(thishop->b_crypto, cell->payload, 0) < 0)
  215. return -1;
  216. relay_header_unpack(&rh, cell->payload);
  217. if (rh.recognized == 0) {
  218. /* it's possibly recognized. have to check digest to be sure. */
  219. if (relay_digest_matches(thishop->b_digest, cell)) {
  220. *recognized = 1;
  221. *layer_hint = thishop;
  222. return 0;
  223. }
  224. }
  225. thishop = thishop->next;
  226. } while (thishop != circ->cpath && thishop->state == CPATH_STATE_OPEN);
  227. log_fn(LOG_WARN,"in-cell at OP not recognized. Closing.");
  228. return -1;
  229. } else { /* we're in the middle. Just one crypt. */
  230. if (relay_crypt_one_payload(circ->p_crypto, cell->payload, 1) < 0)
  231. return -1;
  232. // log_fn(LOG_DEBUG,"Skipping recognized check, because we're not the OP.");
  233. }
  234. } else /* cell_direction == CELL_DIRECTION_OUT */ {
  235. /* we're in the middle. Just one crypt. */
  236. if (relay_crypt_one_payload(circ->n_crypto, cell->payload, 0) < 0)
  237. return -1;
  238. relay_header_unpack(&rh, cell->payload);
  239. if (rh.recognized == 0) {
  240. /* it's possibly recognized. have to check digest to be sure. */
  241. if (relay_digest_matches(circ->n_digest, cell)) {
  242. *recognized = 1;
  243. return 0;
  244. }
  245. }
  246. }
  247. return 0;
  248. }
  249. /** Package a relay cell:
  250. * - Encrypt it to the right layer
  251. * - connection_or_write_cell_to_buf to the right conn
  252. */
  253. static int
  254. circuit_package_relay_cell(cell_t *cell, circuit_t *circ,
  255. int cell_direction,
  256. crypt_path_t *layer_hint)
  257. {
  258. connection_t *conn; /* where to send the cell */
  259. crypt_path_t *thishop; /* counter for repeated crypts */
  260. if (cell_direction == CELL_DIRECTION_OUT) {
  261. conn = circ->n_conn;
  262. if (!conn) {
  263. log_fn(LOG_WARN,"outgoing relay cell has n_conn==NULL. Dropping.");
  264. return 0; /* just drop it */
  265. }
  266. relay_set_digest(layer_hint->f_digest, cell);
  267. thishop = layer_hint;
  268. /* moving from farthest to nearest hop */
  269. do {
  270. tor_assert(thishop);
  271. log_fn(LOG_DEBUG,"crypting a layer of the relay cell.");
  272. if (relay_crypt_one_payload(thishop->f_crypto, cell->payload, 1) < 0) {
  273. return -1;
  274. }
  275. thishop = thishop->prev;
  276. } while (thishop != circ->cpath->prev);
  277. } else { /* incoming cell */
  278. conn = circ->p_conn;
  279. if (!conn) {
  280. log_fn(LOG_WARN,"incoming relay cell has p_conn==NULL. Dropping.");
  281. return 0; /* just drop it */
  282. }
  283. relay_set_digest(circ->p_digest, cell);
  284. if (relay_crypt_one_payload(circ->p_crypto, cell->payload, 1) < 0)
  285. return -1;
  286. }
  287. ++stats_n_relay_cells_relayed;
  288. connection_or_write_cell_to_buf(cell, conn);
  289. return 0;
  290. }
  291. /** If cell's stream_id matches the stream_id of any conn that's
  292. * attached to circ, return that conn, else return NULL.
  293. */
  294. static connection_t *
  295. relay_lookup_conn(circuit_t *circ, cell_t *cell, int cell_direction)
  296. {
  297. connection_t *tmpconn;
  298. relay_header_t rh;
  299. relay_header_unpack(&rh, cell->payload);
  300. if (!rh.stream_id)
  301. return NULL;
  302. /* IN or OUT cells could have come from either direction, now
  303. * that we allow rendezvous *to* an OP.
  304. */
  305. for (tmpconn = circ->n_streams; tmpconn; tmpconn=tmpconn->next_stream) {
  306. if (rh.stream_id == tmpconn->stream_id && !tmpconn->marked_for_close) {
  307. log_fn(LOG_DEBUG,"found conn for stream %d.", rh.stream_id);
  308. if (cell_direction == CELL_DIRECTION_OUT ||
  309. connection_edge_is_rendezvous_stream(tmpconn))
  310. return tmpconn;
  311. }
  312. }
  313. for (tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream) {
  314. if (rh.stream_id == tmpconn->stream_id && !tmpconn->marked_for_close) {
  315. log_fn(LOG_DEBUG,"found conn for stream %d.", rh.stream_id);
  316. return tmpconn;
  317. }
  318. }
  319. for (tmpconn = circ->resolving_streams; tmpconn; tmpconn=tmpconn->next_stream) {
  320. if (rh.stream_id == tmpconn->stream_id && !tmpconn->marked_for_close) {
  321. log_fn(LOG_DEBUG,"found conn for stream %d.", rh.stream_id);
  322. return tmpconn;
  323. }
  324. }
  325. return NULL; /* probably a begin relay cell */
  326. }
  327. /** Pack the relay_header_t host-order structure <b>src</b> into
  328. * network-order in the buffer <b>dest</b>. See tor-spec.txt for details
  329. * about the wire format.
  330. */
  331. void relay_header_pack(char *dest, const relay_header_t *src) {
  332. *(uint8_t*)(dest) = src->command;
  333. set_uint16(dest+1, htons(src->recognized));
  334. set_uint16(dest+3, htons(src->stream_id));
  335. memcpy(dest+5, src->integrity, 4);
  336. set_uint16(dest+9, htons(src->length));
  337. }
  338. /** Unpack the network-order buffer <b>src</b> into a host-order
  339. * relay_header_t structure <b>dest</b>.
  340. */
  341. void relay_header_unpack(relay_header_t *dest, const char *src) {
  342. dest->command = *(uint8_t*)(src);
  343. dest->recognized = ntohs(get_uint16(src+1));
  344. dest->stream_id = ntohs(get_uint16(src+3));
  345. memcpy(dest->integrity, src+5, 4);
  346. dest->length = ntohs(get_uint16(src+9));
  347. }
  348. /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and
  349. * send it onto the open circuit <b>circ</b>. <b>fromconn</b> is the stream
  350. * that's sending the relay cell, or NULL if it's a control cell.
  351. * <b>cpath_layer</b> is NULL for OR->OP cells, or the destination hop
  352. * for OP->OR cells.
  353. *
  354. * If you can't send the cell, mark the circuit for close and
  355. * return -1. Else return 0.
  356. */
  357. int connection_edge_send_command(connection_t *fromconn, circuit_t *circ,
  358. int relay_command, const char *payload,
  359. size_t payload_len, crypt_path_t *cpath_layer) {
  360. cell_t cell;
  361. relay_header_t rh;
  362. int cell_direction;
  363. if (fromconn && fromconn->marked_for_close) {
  364. log_fn(LOG_WARN,"Bug: called on conn that's already marked for close at %s:%d.",
  365. fromconn->marked_for_close_file, fromconn->marked_for_close);
  366. return 0;
  367. }
  368. if (!circ) {
  369. log_fn(LOG_WARN,"no circ. Closing conn.");
  370. tor_assert(fromconn);
  371. if (fromconn->type == CONN_TYPE_AP) {
  372. connection_close_unattached_ap(fromconn, END_STREAM_REASON_INTERNAL);
  373. } else {
  374. fromconn->has_sent_end = 1; /* no circ to send to */
  375. connection_mark_for_close(fromconn);
  376. }
  377. return -1;
  378. }
  379. memset(&cell, 0, sizeof(cell_t));
  380. cell.command = CELL_RELAY;
  381. if (cpath_layer) {
  382. cell.circ_id = circ->n_circ_id;
  383. cell_direction = CELL_DIRECTION_OUT;
  384. } else {
  385. cell.circ_id = circ->p_circ_id;
  386. cell_direction = CELL_DIRECTION_IN;
  387. }
  388. memset(&rh, 0, sizeof(rh));
  389. rh.command = relay_command;
  390. if (fromconn)
  391. rh.stream_id = fromconn->stream_id; /* else it's 0 */
  392. rh.length = payload_len;
  393. relay_header_pack(cell.payload, &rh);
  394. if (payload_len) {
  395. tor_assert(payload_len <= RELAY_PAYLOAD_SIZE);
  396. memcpy(cell.payload+RELAY_HEADER_SIZE, payload, payload_len);
  397. }
  398. log_fn(LOG_DEBUG,"delivering %d cell %s.", relay_command,
  399. cell_direction == CELL_DIRECTION_OUT ? "forward" : "backward");
  400. if (circuit_package_relay_cell(&cell, circ, cell_direction, cpath_layer) < 0) {
  401. log_fn(LOG_WARN,"circuit_package_relay_cell failed. Closing.");
  402. circuit_mark_for_close(circ);
  403. return -1;
  404. }
  405. return 0;
  406. }
  407. /** Translate the <b>payload</b> of length <b>length</b>, which
  408. * came from a relay 'end' cell, into a static const string describing
  409. * why the stream is closing.
  410. */
  411. static const char *
  412. connection_edge_end_reason_str(char *payload, uint16_t length) {
  413. if (length < 1) {
  414. log_fn(LOG_WARN,"End cell arrived with length 0. Should be at least 1.");
  415. return "MALFORMED";
  416. }
  417. switch (*payload) {
  418. case END_STREAM_REASON_MISC: return "misc error";
  419. case END_STREAM_REASON_RESOLVEFAILED: return "resolve failed";
  420. case END_STREAM_REASON_CONNECTREFUSED: return "connection refused";
  421. case END_STREAM_REASON_EXITPOLICY: return "exit policy failed";
  422. case END_STREAM_REASON_DESTROY: return "destroyed";
  423. case END_STREAM_REASON_DONE: return "closed normally";
  424. case END_STREAM_REASON_TIMEOUT: return "gave up (timeout)";
  425. case END_STREAM_REASON_HIBERNATING: return "server is hibernating";
  426. case END_STREAM_REASON_INTERNAL: return "internal error at server";
  427. case END_STREAM_REASON_RESOURCELIMIT: return "server out of resources";
  428. case END_STREAM_REASON_CONNRESET: return "connection reset";
  429. case END_STREAM_REASON_TORPROTOCOL: return "Tor protocol error";
  430. default:
  431. log_fn(LOG_WARN,"Reason for ending (%d) not recognized.",*payload);
  432. return "unknown";
  433. }
  434. }
  435. /** Translate <b>reason</b> (as from a relay 'end' cell) into an
  436. * appropriate SOCKS5 reply code.
  437. */
  438. socks5_reply_status_t
  439. connection_edge_end_reason_socks5_response(int reason)
  440. {
  441. switch (reason) {
  442. case END_STREAM_REASON_MISC:
  443. return SOCKS5_GENERAL_ERROR;
  444. case END_STREAM_REASON_RESOLVEFAILED:
  445. return SOCKS5_HOST_UNREACHABLE;
  446. case END_STREAM_REASON_CONNECTREFUSED:
  447. return SOCKS5_CONNECTION_REFUSED;
  448. case END_STREAM_REASON_EXITPOLICY:
  449. return SOCKS5_NOT_ALLOWED;
  450. case END_STREAM_REASON_DESTROY:
  451. return SOCKS5_GENERAL_ERROR;
  452. case END_STREAM_REASON_DONE:
  453. return SOCKS5_SUCCEEDED;
  454. case END_STREAM_REASON_TIMEOUT:
  455. return SOCKS5_TTL_EXPIRED;
  456. case END_STREAM_REASON_RESOURCELIMIT:
  457. return SOCKS5_GENERAL_ERROR;
  458. case END_STREAM_REASON_HIBERNATING:
  459. return SOCKS5_GENERAL_ERROR;
  460. case END_STREAM_REASON_INTERNAL:
  461. return SOCKS5_GENERAL_ERROR;
  462. case END_STREAM_REASON_CONNRESET:
  463. return SOCKS5_CONNECTION_REFUSED;
  464. case END_STREAM_REASON_TORPROTOCOL:
  465. return SOCKS5_GENERAL_ERROR;
  466. case END_STREAM_REASON_ALREADY_SOCKS_REPLIED:
  467. return SOCKS5_SUCCEEDED; /* never used */
  468. case END_STREAM_REASON_CANT_ATTACH:
  469. return SOCKS5_GENERAL_ERROR;
  470. case END_STREAM_REASON_NET_UNREACHABLE:
  471. return SOCKS5_NET_UNREACHABLE;
  472. default:
  473. log_fn(LOG_WARN,"Reason for ending (%d) not recognized.",reason);
  474. return SOCKS5_GENERAL_ERROR;
  475. }
  476. }
  477. /* We need to use a few macros to deal with the fact that Windows
  478. * decided that their sockets interface should be a permakludge.
  479. * E_CASE is for errors where windows has both a EFOO and a WSAEFOO
  480. * version, and S_CASE is for errors where windows has only a WSAEFOO
  481. * version. (The E is for 'error', the S is for 'socket'). */
  482. #ifdef MS_WINDOWS
  483. #define E_CASE(s) case s: case WSA ## s
  484. #define S_CASE(s) case WSA ## s
  485. #else
  486. #define E_CASE(s) case s
  487. #define S_CASE(s) case s
  488. #endif
  489. int
  490. errno_to_end_reason(int e)
  491. {
  492. switch (e) {
  493. case EPIPE:
  494. return END_STREAM_REASON_DONE;
  495. E_CASE(EBADF):
  496. E_CASE(EFAULT):
  497. E_CASE(EINVAL):
  498. S_CASE(EISCONN):
  499. S_CASE(ENOTSOCK):
  500. S_CASE(EPROTONOSUPPORT):
  501. S_CASE(EAFNOSUPPORT):
  502. E_CASE(EACCES):
  503. S_CASE(ENOTCONN):
  504. S_CASE(ENETUNREACH):
  505. return END_STREAM_REASON_INTERNAL;
  506. S_CASE(ECONNREFUSED):
  507. return END_STREAM_REASON_CONNECTREFUSED;
  508. S_CASE(ECONNRESET):
  509. return END_STREAM_REASON_CONNRESET;
  510. S_CASE(ETIMEDOUT):
  511. return END_STREAM_REASON_TIMEOUT;
  512. S_CASE(ENOBUFS):
  513. case ENOMEM:
  514. case ENFILE:
  515. E_CASE(EMFILE):
  516. return END_STREAM_REASON_RESOURCELIMIT;
  517. default:
  518. log_fn(LOG_INFO, "Didn't recognize errno %d (%s); telling the OP that we are ending a stream for 'misc' reason.",
  519. e, tor_socket_strerror(e));
  520. return END_STREAM_REASON_MISC;
  521. }
  522. }
  523. /** How many times will I retry a stream that fails due to DNS
  524. * resolve failure?
  525. */
  526. #define MAX_RESOLVE_FAILURES 3
  527. /** An incoming relay cell has arrived from circuit <b>circ</b> to
  528. * stream <b>conn</b>.
  529. *
  530. * The arguments here are the same as in
  531. * connection_edge_process_relay_cell() below; this function is called
  532. * from there when <b>conn</b> is defined and not in an open state.
  533. */
  534. static int
  535. connection_edge_process_relay_cell_not_open(
  536. relay_header_t *rh, cell_t *cell, circuit_t *circ,
  537. connection_t *conn, crypt_path_t *layer_hint) {
  538. struct in_addr in;
  539. uint32_t addr;
  540. int reason;
  541. routerinfo_t *exitrouter;
  542. if (rh->command == RELAY_COMMAND_END) {
  543. reason = *(cell->payload+RELAY_HEADER_SIZE);
  544. /* We have to check this here, since we aren't connected yet. */
  545. if (rh->length >= 5 && reason == END_STREAM_REASON_EXITPOLICY) {
  546. if (conn->type != CONN_TYPE_AP) {
  547. log_fn(LOG_WARN,"Got an end because of exitpolicy, but we're not an AP. Closing.");
  548. return -1;
  549. }
  550. addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+1));
  551. if (addr) {
  552. log_fn(LOG_INFO,"Address '%s' refused due to exit policy. Retrying.",
  553. conn->socks_request->address);
  554. } else {
  555. log_fn(LOG_INFO,"Address '%s' resolved to 0.0.0.0. Closing,",
  556. conn->socks_request->address);
  557. connection_close_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  558. return 0;
  559. }
  560. client_dns_set_addressmap(conn->socks_request->address, addr,
  561. conn->chosen_exit_name);
  562. /* check if he *ought* to have allowed it */
  563. exitrouter = router_get_by_digest(circ->build_state->chosen_exit_digest);
  564. if (!exitrouter) {
  565. log_fn(LOG_INFO,"Skipping broken circ (exit router vanished)");
  566. return 0; /* this circuit is screwed and doesn't know it yet */
  567. }
  568. if (!tor_inet_aton(conn->socks_request->address, &in) &&
  569. !conn->chosen_exit_name) {
  570. log_fn(LOG_NOTICE,"Exitrouter '%s' seems to be more restrictive than its exit policy. Not using this router as exit for now.", exitrouter->nickname);
  571. addr_policy_free(exitrouter->exit_policy);
  572. exitrouter->exit_policy =
  573. router_parse_addr_policy_from_string("reject *:*");
  574. }
  575. if (connection_ap_detach_retriable(conn, circ) >= 0)
  576. return 0;
  577. log_fn(LOG_INFO,"Giving up on retrying (from exitpolicy); conn can't be handled.");
  578. /* else, conn will get closed below */
  579. } else if (rh->length && reason == END_STREAM_REASON_RESOLVEFAILED) {
  580. if (conn->type != CONN_TYPE_AP) {
  581. log_fn(LOG_WARN,"Got an end because of resolvefailed, but we're not an AP. Closing.");
  582. return -1;
  583. }
  584. if (client_dns_incr_failures(conn->socks_request->address)
  585. < MAX_RESOLVE_FAILURES) {
  586. /* We haven't retried too many times; reattach the connection. */
  587. log_fn(LOG_INFO,"Resolve of '%s' failed, trying again.",
  588. conn->socks_request->address);
  589. circuit_log_path(LOG_INFO,circ);
  590. tor_assert(circ->timestamp_dirty);
  591. circ->timestamp_dirty -= get_options()->MaxCircuitDirtiness;
  592. if (connection_ap_detach_retriable(conn, circ) >= 0)
  593. return 0;
  594. /* else, conn will get closed below */
  595. log_fn(LOG_INFO,"Giving up on retrying (from resolvefailed); conn can't be handled.");
  596. } else {
  597. log_fn(LOG_NOTICE,"Have tried resolving address '%s' at %d different places. Giving up.",
  598. conn->socks_request->address, MAX_RESOLVE_FAILURES);
  599. }
  600. }
  601. log_fn(LOG_INFO,"Edge got end (%s) before we're connected. Marking for close.",
  602. connection_edge_end_reason_str(cell->payload+RELAY_HEADER_SIZE,
  603. rh->length));
  604. if (CIRCUIT_IS_ORIGIN(circ))
  605. circuit_log_path(LOG_INFO,circ);
  606. if (conn->type == CONN_TYPE_AP) {
  607. connection_close_unattached_ap(conn,
  608. *(char *)(cell->payload+RELAY_HEADER_SIZE));
  609. } else {
  610. conn->has_sent_end = 1; /* we just got an 'end', don't need to send one */
  611. connection_mark_for_close(conn);
  612. }
  613. return 0;
  614. }
  615. if (conn->type == CONN_TYPE_AP && rh->command == RELAY_COMMAND_CONNECTED) {
  616. if (conn->state != AP_CONN_STATE_CONNECT_WAIT) {
  617. log_fn(LOG_WARN,"Got 'connected' while not in state connect_wait. Dropping.");
  618. return 0;
  619. }
  620. // log_fn(LOG_INFO,"Connected! Notifying application.");
  621. conn->state = AP_CONN_STATE_OPEN;
  622. log_fn(LOG_INFO,"'connected' received after %d seconds.",
  623. (int)(time(NULL) - conn->timestamp_lastread));
  624. if (rh->length >= 4) {
  625. addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE));
  626. if (!addr) {
  627. log_fn(LOG_INFO,"...but it claims the IP address was 0.0.0.0. Closing.");
  628. connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL, conn->cpath_layer);
  629. connection_close_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  630. return 0;
  631. }
  632. client_dns_set_addressmap(conn->socks_request->address, addr,
  633. conn->chosen_exit_name);
  634. }
  635. circuit_log_path(LOG_INFO,circ);
  636. connection_ap_handshake_socks_reply(conn, NULL, 0, SOCKS5_SUCCEEDED);
  637. /* handle anything that might have queued */
  638. if (connection_edge_package_raw_inbuf(conn, 1) < 0) {
  639. /* (We already sent an end cell if possible) */
  640. connection_mark_for_close(conn);
  641. return 0;
  642. }
  643. return 0;
  644. }
  645. if (conn->type == CONN_TYPE_AP && rh->command == RELAY_COMMAND_RESOLVED) {
  646. if (conn->state != AP_CONN_STATE_RESOLVE_WAIT) {
  647. log_fn(LOG_WARN,"Got a 'resolved' cell while not in state resolve_wait. Dropping.");
  648. return 0;
  649. }
  650. tor_assert(conn->socks_request->command == SOCKS_COMMAND_RESOLVE);
  651. if (rh->length < 2 || cell->payload[RELAY_HEADER_SIZE+1]+2>rh->length) {
  652. log_fn(LOG_WARN, "Dropping malformed 'resolved' cell");
  653. connection_close_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  654. return 0;
  655. }
  656. connection_ap_handshake_socks_resolved(conn,
  657. cell->payload[RELAY_HEADER_SIZE], /*answer_type*/
  658. cell->payload[RELAY_HEADER_SIZE+1], /*answer_len*/
  659. cell->payload+RELAY_HEADER_SIZE+2); /* answer */
  660. connection_close_unattached_ap(conn, END_STREAM_REASON_ALREADY_SOCKS_REPLIED);
  661. return 0;
  662. }
  663. log_fn(LOG_WARN,"Got an unexpected relay command %d, in state %d (%s). Closing.",
  664. rh->command, conn->state, conn_state_to_string[conn->type][conn->state]);
  665. connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL, conn->cpath_layer);
  666. connection_mark_for_close(conn);
  667. return -1;
  668. }
  669. /** An incoming relay cell has arrived on circuit <b>circ</b>. If
  670. * <b>conn</b> is NULL this is a control cell, else <b>cell</b> is
  671. * destined for <b>conn</b>.
  672. *
  673. * If <b>layer_hint</b> is defined, then we're the origin of the
  674. * circuit, and it specifies the hop that packaged <b>cell</b>.
  675. *
  676. * Return -1 if you want to tear down the circuit, else 0.
  677. */
  678. static int
  679. connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
  680. connection_t *conn,
  681. crypt_path_t *layer_hint)
  682. {
  683. static int num_seen=0;
  684. relay_header_t rh;
  685. tor_assert(cell);
  686. tor_assert(circ);
  687. relay_header_unpack(&rh, cell->payload);
  688. // log_fn(LOG_DEBUG,"command %d stream %d", rh.command, rh.stream_id);
  689. num_seen++;
  690. log_fn(LOG_DEBUG,"Now seen %d relay cells here.", num_seen);
  691. /* either conn is NULL, in which case we've got a control cell, or else
  692. * conn points to the recognized stream. */
  693. if (conn &&
  694. conn->state != AP_CONN_STATE_OPEN &&
  695. conn->state != EXIT_CONN_STATE_OPEN) {
  696. return connection_edge_process_relay_cell_not_open(
  697. &rh, cell, circ, conn, layer_hint);
  698. }
  699. switch (rh.command) {
  700. case RELAY_COMMAND_DROP:
  701. log_fn(LOG_INFO,"Got a relay-level padding cell. Dropping.");
  702. return 0;
  703. case RELAY_COMMAND_BEGIN:
  704. if (layer_hint &&
  705. circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
  706. log_fn(LOG_WARN,"relay begin request unsupported at AP. Dropping.");
  707. return 0;
  708. }
  709. if (conn) {
  710. log_fn(LOG_WARN,"begin cell for known stream. Dropping.");
  711. return 0;
  712. }
  713. connection_exit_begin_conn(cell, circ);
  714. return 0;
  715. case RELAY_COMMAND_DATA:
  716. ++stats_n_data_cells_received;
  717. if (( layer_hint && --layer_hint->deliver_window < 0) ||
  718. (!layer_hint && --circ->deliver_window < 0)) {
  719. log_fn(LOG_WARN,"(relay data) circ deliver_window below 0. Killing.");
  720. connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL, conn->cpath_layer);
  721. connection_mark_for_close(conn);
  722. return -1;
  723. }
  724. log_fn(LOG_DEBUG,"circ deliver_window now %d.", layer_hint ?
  725. layer_hint->deliver_window : circ->deliver_window);
  726. circuit_consider_sending_sendme(circ, layer_hint);
  727. if (!conn) {
  728. log_fn(LOG_INFO,"data cell dropped, unknown stream.");
  729. return 0;
  730. }
  731. if (--conn->deliver_window < 0) { /* is it below 0 after decrement? */
  732. log_fn(LOG_WARN,"(relay data) conn deliver_window below 0. Killing.");
  733. return -1; /* somebody's breaking protocol. kill the whole circuit. */
  734. }
  735. stats_n_data_bytes_received += rh.length;
  736. if (conn->type == CONN_TYPE_AP) {
  737. conn->stream_size += rh.length;
  738. log_fn(LOG_DEBUG,"%d: stream size now %d.", conn->s, (int)conn->stream_size);
  739. }
  740. connection_write_to_buf(cell->payload + RELAY_HEADER_SIZE,
  741. rh.length, conn);
  742. connection_edge_consider_sending_sendme(conn);
  743. return 0;
  744. case RELAY_COMMAND_END:
  745. if (!conn) {
  746. log_fn(LOG_INFO,"end cell (%s) dropped, unknown stream.",
  747. connection_edge_end_reason_str(cell->payload+RELAY_HEADER_SIZE,
  748. rh.length));
  749. return 0;
  750. }
  751. /* XXX add to this log_fn the exit node's nickname? */
  752. log_fn(LOG_INFO,"%d: end cell (%s) for stream %d. Removing stream. Size %d.",
  753. conn->s,
  754. connection_edge_end_reason_str(cell->payload+RELAY_HEADER_SIZE,
  755. rh.length),
  756. conn->stream_id, (int)conn->stream_size);
  757. if (conn->socks_request && !conn->socks_request->has_finished) {
  758. socks5_reply_status_t status;
  759. if (rh.length < 1) {
  760. log_fn(LOG_WARN,"End cell arrived with length 0. Should be at least 1.");
  761. status = SOCKS5_GENERAL_ERROR;
  762. } else {
  763. status = connection_edge_end_reason_socks5_response(
  764. *(uint8_t*)cell->payload+RELAY_HEADER_SIZE);
  765. }
  766. connection_ap_handshake_socks_reply(conn, NULL, 0, status);
  767. }
  768. #ifdef HALF_OPEN
  769. conn->done_sending = 1;
  770. shutdown(conn->s, 1); /* XXX check return; refactor NM */
  771. if (conn->done_receiving) {
  772. /* We just *got* an end; no reason to send one. */
  773. conn->has_sent_end = 1;
  774. connection_mark_for_close(conn);
  775. conn->hold_open_until_flushed = 1;
  776. }
  777. #else
  778. /* We just *got* an end; no reason to send one. */
  779. conn->has_sent_end = 1;
  780. if (!conn->marked_for_close) {
  781. /* only mark it if not already marked. it's possible to
  782. * get the 'end' right around when the client hangs up on us. */
  783. connection_mark_for_close(conn);
  784. conn->hold_open_until_flushed = 1;
  785. }
  786. #endif
  787. return 0;
  788. case RELAY_COMMAND_EXTEND:
  789. if (conn) {
  790. log_fn(LOG_WARN,"'extend' for non-zero stream. Dropping.");
  791. return 0;
  792. }
  793. return circuit_extend(cell, circ);
  794. case RELAY_COMMAND_EXTENDED:
  795. if (!layer_hint) {
  796. log_fn(LOG_WARN,"'extended' unsupported at non-origin. Dropping.");
  797. return 0;
  798. }
  799. log_fn(LOG_DEBUG,"Got an extended cell! Yay.");
  800. if (circuit_finish_handshake(circ, cell->payload+RELAY_HEADER_SIZE) < 0) {
  801. log_fn(LOG_WARN,"circuit_finish_handshake failed.");
  802. return -1;
  803. }
  804. if (circuit_send_next_onion_skin(circ)<0) {
  805. log_fn(LOG_INFO,"circuit_send_next_onion_skin() failed.");
  806. return -1;
  807. }
  808. return 0;
  809. case RELAY_COMMAND_TRUNCATE:
  810. if (layer_hint) {
  811. log_fn(LOG_WARN,"'truncate' unsupported at origin. Dropping.");
  812. return 0;
  813. }
  814. if (circ->n_conn) {
  815. connection_send_destroy(circ->n_circ_id, circ->n_conn);
  816. circ->n_conn = NULL;
  817. }
  818. log_fn(LOG_DEBUG, "Processed 'truncate', replying.");
  819. connection_edge_send_command(NULL, circ, RELAY_COMMAND_TRUNCATED,
  820. NULL, 0, NULL);
  821. return 0;
  822. case RELAY_COMMAND_TRUNCATED:
  823. if (!layer_hint) {
  824. log_fn(LOG_WARN,"'truncated' unsupported at non-origin. Dropping.");
  825. return 0;
  826. }
  827. circuit_truncated(circ, layer_hint);
  828. return 0;
  829. case RELAY_COMMAND_CONNECTED:
  830. if (conn) {
  831. log_fn(LOG_WARN,"'connected' unsupported while open. Closing circ.");
  832. return -1;
  833. }
  834. log_fn(LOG_INFO,"'connected' received, no conn attached anymore. Ignoring.");
  835. return 0;
  836. case RELAY_COMMAND_SENDME:
  837. if (!conn) {
  838. if (layer_hint) {
  839. layer_hint->package_window += CIRCWINDOW_INCREMENT;
  840. log_fn(LOG_DEBUG,"circ-level sendme at origin, packagewindow %d.",
  841. layer_hint->package_window);
  842. circuit_resume_edge_reading(circ, layer_hint);
  843. } else {
  844. circ->package_window += CIRCWINDOW_INCREMENT;
  845. log_fn(LOG_DEBUG,"circ-level sendme at non-origin, packagewindow %d.",
  846. circ->package_window);
  847. circuit_resume_edge_reading(circ, layer_hint);
  848. }
  849. return 0;
  850. }
  851. conn->package_window += STREAMWINDOW_INCREMENT;
  852. log_fn(LOG_DEBUG,"stream-level sendme, packagewindow now %d.", conn->package_window);
  853. connection_start_reading(conn);
  854. /* handle whatever might still be on the inbuf */
  855. if (connection_edge_package_raw_inbuf(conn, 1) < 0) {
  856. /* (We already sent an end cell if possible) */
  857. connection_mark_for_close(conn);
  858. return 0;
  859. }
  860. return 0;
  861. case RELAY_COMMAND_RESOLVE:
  862. if (layer_hint) {
  863. log_fn(LOG_WARN,"resolve request unsupported at AP; dropping.");
  864. return 0;
  865. } else if (conn) {
  866. log_fn(LOG_WARN, "resolve request for known stream; dropping.");
  867. return 0;
  868. } else if (circ->purpose != CIRCUIT_PURPOSE_OR) {
  869. log_fn(LOG_WARN, "resolve request on circ with purpose %d; dropping",
  870. circ->purpose);
  871. return 0;
  872. }
  873. connection_exit_begin_resolve(cell, circ);
  874. return 0;
  875. case RELAY_COMMAND_RESOLVED:
  876. if (conn) {
  877. log_fn(LOG_WARN,"'resolved' unsupported while open. Closing circ.");
  878. return -1;
  879. }
  880. log_fn(LOG_INFO,"'resolved' received, no conn attached anymore. Ignoring.");
  881. return 0;
  882. case RELAY_COMMAND_ESTABLISH_INTRO:
  883. case RELAY_COMMAND_ESTABLISH_RENDEZVOUS:
  884. case RELAY_COMMAND_INTRODUCE1:
  885. case RELAY_COMMAND_INTRODUCE2:
  886. case RELAY_COMMAND_INTRODUCE_ACK:
  887. case RELAY_COMMAND_RENDEZVOUS1:
  888. case RELAY_COMMAND_RENDEZVOUS2:
  889. case RELAY_COMMAND_INTRO_ESTABLISHED:
  890. case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
  891. rend_process_relay_cell(circ, rh.command, rh.length,
  892. cell->payload+RELAY_HEADER_SIZE);
  893. return 0;
  894. }
  895. log_fn(LOG_WARN,"unknown relay command %d.",rh.command);
  896. return -1;
  897. }
  898. uint64_t stats_n_data_cells_packaged = 0;
  899. uint64_t stats_n_data_bytes_packaged = 0;
  900. uint64_t stats_n_data_cells_received = 0;
  901. uint64_t stats_n_data_bytes_received = 0;
  902. /** While conn->inbuf has an entire relay payload of bytes on it,
  903. * and the appropriate package windows aren't empty, grab a cell
  904. * and send it down the circuit.
  905. *
  906. * Return -1 (and send a RELAY_END cell if necessary) if conn should
  907. * be marked for close, else return 0.
  908. */
  909. int connection_edge_package_raw_inbuf(connection_t *conn, int package_partial) {
  910. size_t amount_to_process, length;
  911. char payload[CELL_PAYLOAD_SIZE];
  912. circuit_t *circ;
  913. tor_assert(conn);
  914. tor_assert(!connection_speaks_cells(conn));
  915. if (conn->marked_for_close) {
  916. log_fn(LOG_WARN,"Bug: called on conn that's already marked for close at %s:%d.",
  917. conn->marked_for_close_file, conn->marked_for_close);
  918. return 0;
  919. }
  920. repeat_connection_edge_package_raw_inbuf:
  921. circ = circuit_get_by_conn(conn);
  922. if (!circ) {
  923. log_fn(LOG_INFO,"conn has no circuit! Closing.");
  924. return -1;
  925. }
  926. if (circuit_consider_stop_edge_reading(circ, conn->cpath_layer))
  927. return 0;
  928. if (conn->package_window <= 0) {
  929. log_fn(LOG_INFO,"called with package_window %d. Skipping.", conn->package_window);
  930. connection_stop_reading(conn);
  931. return 0;
  932. }
  933. amount_to_process = buf_datalen(conn->inbuf);
  934. if (!amount_to_process)
  935. return 0;
  936. if (!package_partial && amount_to_process < RELAY_PAYLOAD_SIZE)
  937. return 0;
  938. if (amount_to_process > RELAY_PAYLOAD_SIZE) {
  939. length = RELAY_PAYLOAD_SIZE;
  940. } else {
  941. length = amount_to_process;
  942. }
  943. stats_n_data_bytes_packaged += length;
  944. stats_n_data_cells_packaged += 1;
  945. connection_fetch_from_buf(payload, length, conn);
  946. log_fn(LOG_DEBUG,"(%d) Packaging %d bytes (%d waiting).", conn->s,
  947. (int)length, (int)buf_datalen(conn->inbuf));
  948. if (conn->type == CONN_TYPE_EXIT) {
  949. conn->stream_size += length;
  950. log_fn(LOG_DEBUG,"%d: Stream size now %d.", conn->s, (int)conn->stream_size);
  951. }
  952. if (connection_edge_send_command(conn, circ, RELAY_COMMAND_DATA,
  953. payload, length, conn->cpath_layer) < 0)
  954. /* circuit got marked for close, don't continue, don't need to mark conn */
  955. return 0;
  956. if (!conn->cpath_layer) { /* non-rendezvous exit */
  957. tor_assert(circ->package_window > 0);
  958. circ->package_window--;
  959. } else { /* we're an AP, or an exit on a rendezvous circ */
  960. tor_assert(conn->cpath_layer->package_window > 0);
  961. conn->cpath_layer->package_window--;
  962. }
  963. if (--conn->package_window <= 0) { /* is it 0 after decrement? */
  964. connection_stop_reading(conn);
  965. log_fn(LOG_DEBUG,"conn->package_window reached 0.");
  966. circuit_consider_stop_edge_reading(circ, conn->cpath_layer);
  967. return 0; /* don't process the inbuf any more */
  968. }
  969. log_fn(LOG_DEBUG,"conn->package_window is now %d",conn->package_window);
  970. /* handle more if there's more, or return 0 if there isn't */
  971. goto repeat_connection_edge_package_raw_inbuf;
  972. }
  973. /** Called when we've just received a relay data cell, or when
  974. * we've just finished flushing all bytes to stream <b>conn</b>.
  975. *
  976. * If conn->outbuf is not too full, and our deliver window is
  977. * low, send back a suitable number of stream-level sendme cells.
  978. */
  979. void connection_edge_consider_sending_sendme(connection_t *conn) {
  980. circuit_t *circ;
  981. if (connection_outbuf_too_full(conn))
  982. return;
  983. circ = circuit_get_by_conn(conn);
  984. if (!circ) {
  985. /* this can legitimately happen if the destroy has already
  986. * arrived and torn down the circuit */
  987. log_fn(LOG_INFO,"No circuit associated with conn. Skipping.");
  988. return;
  989. }
  990. while (conn->deliver_window < STREAMWINDOW_START - STREAMWINDOW_INCREMENT) {
  991. log_fn(LOG_DEBUG,"Outbuf %d, Queueing stream sendme.", (int)conn->outbuf_flushlen);
  992. conn->deliver_window += STREAMWINDOW_INCREMENT;
  993. if (connection_edge_send_command(conn, circ, RELAY_COMMAND_SENDME,
  994. NULL, 0, conn->cpath_layer) < 0) {
  995. log_fn(LOG_WARN,"connection_edge_send_command failed. Returning.");
  996. return; /* the circuit's closed, don't continue */
  997. }
  998. }
  999. }
  1000. /** The circuit <b>circ</b> has received a circuit-level sendme
  1001. * (on hop <b>layer_hint</b>, if we're the OP). Go through all the
  1002. * attached streams and let them resume reading and packaging, if
  1003. * their stream windows allow it.
  1004. */
  1005. static void
  1006. circuit_resume_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
  1007. {
  1008. log_fn(LOG_DEBUG,"resuming");
  1009. /* have to check both n_streams and p_streams, to handle rendezvous */
  1010. if (circuit_resume_edge_reading_helper(circ->n_streams, circ, layer_hint) >= 0)
  1011. circuit_resume_edge_reading_helper(circ->p_streams, circ, layer_hint);
  1012. }
  1013. /** A helper function for circuit_resume_edge_reading() above.
  1014. * The arguments are the same, except that <b>conn</b> is the head
  1015. * of a linked list of edge streams that should each be considered.
  1016. */
  1017. static int
  1018. circuit_resume_edge_reading_helper(connection_t *conn,
  1019. circuit_t *circ,
  1020. crypt_path_t *layer_hint) {
  1021. for ( ; conn; conn=conn->next_stream) {
  1022. if (conn->marked_for_close)
  1023. continue;
  1024. if ((!layer_hint && conn->package_window > 0) ||
  1025. (layer_hint && conn->package_window > 0 && conn->cpath_layer == layer_hint)) {
  1026. connection_start_reading(conn);
  1027. /* handle whatever might still be on the inbuf */
  1028. if (connection_edge_package_raw_inbuf(conn, 1)<0) {
  1029. /* (We already sent an end cell if possible) */
  1030. connection_mark_for_close(conn);
  1031. continue;
  1032. }
  1033. /* If the circuit won't accept any more data, return without looking
  1034. * at any more of the streams. Any connections that should be stopped
  1035. * have already been stopped by connection_edge_package_raw_inbuf. */
  1036. if (circuit_consider_stop_edge_reading(circ, layer_hint))
  1037. return -1;
  1038. }
  1039. }
  1040. return 0;
  1041. }
  1042. /** Check if the package window for <b>circ</b> is empty (at
  1043. * hop <b>layer_hint</b> if it's defined).
  1044. *
  1045. * If yes, tell edge streams to stop reading and return 1.
  1046. * Else return 0.
  1047. */
  1048. static int
  1049. circuit_consider_stop_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
  1050. {
  1051. connection_t *conn = NULL;
  1052. if (!layer_hint) {
  1053. log_fn(LOG_DEBUG,"considering circ->package_window %d", circ->package_window);
  1054. if (circ->package_window <= 0) {
  1055. log_fn(LOG_DEBUG,"yes, not-at-origin. stopped.");
  1056. for (conn = circ->n_streams; conn; conn=conn->next_stream)
  1057. connection_stop_reading(conn);
  1058. return 1;
  1059. }
  1060. return 0;
  1061. }
  1062. /* else, layer hint is defined, use it */
  1063. log_fn(LOG_DEBUG,"considering layer_hint->package_window %d", layer_hint->package_window);
  1064. if (layer_hint->package_window <= 0) {
  1065. log_fn(LOG_DEBUG,"yes, at-origin. stopped.");
  1066. for (conn = circ->n_streams; conn; conn=conn->next_stream)
  1067. if (conn->cpath_layer == layer_hint)
  1068. connection_stop_reading(conn);
  1069. for (conn = circ->p_streams; conn; conn=conn->next_stream)
  1070. if (conn->cpath_layer == layer_hint)
  1071. connection_stop_reading(conn);
  1072. return 1;
  1073. }
  1074. return 0;
  1075. }
  1076. /** Check if the deliver_window for circuit <b>circ</b> (at hop
  1077. * <b>layer_hint</b> if it's defined) is low enough that we should
  1078. * send a circuit-level sendme back down the circuit. If so, send
  1079. * enough sendmes that the window would be overfull if we sent any
  1080. * more.
  1081. */
  1082. static void
  1083. circuit_consider_sending_sendme(circuit_t *circ, crypt_path_t *layer_hint)
  1084. {
  1085. // log_fn(LOG_INFO,"Considering: layer_hint is %s",
  1086. // layer_hint ? "defined" : "null");
  1087. while ((layer_hint ? layer_hint->deliver_window : circ->deliver_window) <
  1088. CIRCWINDOW_START - CIRCWINDOW_INCREMENT) {
  1089. log_fn(LOG_DEBUG,"Queueing circuit sendme.");
  1090. if (layer_hint)
  1091. layer_hint->deliver_window += CIRCWINDOW_INCREMENT;
  1092. else
  1093. circ->deliver_window += CIRCWINDOW_INCREMENT;
  1094. if (connection_edge_send_command(NULL, circ, RELAY_COMMAND_SENDME,
  1095. NULL, 0, layer_hint) < 0) {
  1096. log_fn(LOG_WARN,"connection_edge_send_command failed. Circuit's closed.");
  1097. return; /* the circuit's closed, don't continue */
  1098. }
  1099. }
  1100. }