relay.c 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214
  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_mark_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 <b>reason</b>, which came from a relay 'end' cell,
  408. * into a static const string describing why the stream is closing.
  409. * <b>reason</b> is -1 if no reason was provided.
  410. */
  411. static const char *
  412. connection_edge_end_reason_str(int reason) {
  413. switch (reason) {
  414. case -1:
  415. log_fn(LOG_WARN,"End cell arrived with length 0. Should be at least 1.");
  416. return "MALFORMED";
  417. case END_STREAM_REASON_MISC: return "misc error";
  418. case END_STREAM_REASON_RESOLVEFAILED: return "resolve failed";
  419. case END_STREAM_REASON_CONNECTREFUSED: return "connection refused";
  420. case END_STREAM_REASON_EXITPOLICY: return "exit policy failed";
  421. case END_STREAM_REASON_DESTROY: return "destroyed";
  422. case END_STREAM_REASON_DONE: return "closed normally";
  423. case END_STREAM_REASON_TIMEOUT: return "gave up (timeout)";
  424. case END_STREAM_REASON_HIBERNATING: return "server is hibernating";
  425. case END_STREAM_REASON_INTERNAL: return "internal error at server";
  426. case END_STREAM_REASON_RESOURCELIMIT: return "server out of resources";
  427. case END_STREAM_REASON_CONNRESET: return "connection reset";
  428. case END_STREAM_REASON_TORPROTOCOL: return "Tor protocol error";
  429. default:
  430. log_fn(LOG_WARN,"Reason for ending (%d) not recognized.",reason);
  431. return "unknown";
  432. }
  433. }
  434. /** Translate <b>reason</b> (as from a relay 'end' cell) into an
  435. * appropriate SOCKS5 reply code.
  436. */
  437. socks5_reply_status_t
  438. connection_edge_end_reason_socks5_response(int reason)
  439. {
  440. switch (reason) {
  441. case END_STREAM_REASON_MISC:
  442. return SOCKS5_GENERAL_ERROR;
  443. case END_STREAM_REASON_RESOLVEFAILED:
  444. return SOCKS5_HOST_UNREACHABLE;
  445. case END_STREAM_REASON_CONNECTREFUSED:
  446. return SOCKS5_CONNECTION_REFUSED;
  447. case END_STREAM_REASON_EXITPOLICY:
  448. return SOCKS5_NOT_ALLOWED;
  449. case END_STREAM_REASON_DESTROY:
  450. return SOCKS5_GENERAL_ERROR;
  451. case END_STREAM_REASON_DONE:
  452. return SOCKS5_SUCCEEDED;
  453. case END_STREAM_REASON_TIMEOUT:
  454. return SOCKS5_TTL_EXPIRED;
  455. case END_STREAM_REASON_RESOURCELIMIT:
  456. return SOCKS5_GENERAL_ERROR;
  457. case END_STREAM_REASON_HIBERNATING:
  458. return SOCKS5_GENERAL_ERROR;
  459. case END_STREAM_REASON_INTERNAL:
  460. return SOCKS5_GENERAL_ERROR;
  461. case END_STREAM_REASON_CONNRESET:
  462. return SOCKS5_CONNECTION_REFUSED;
  463. case END_STREAM_REASON_TORPROTOCOL:
  464. return SOCKS5_GENERAL_ERROR;
  465. case END_STREAM_REASON_ALREADY_SOCKS_REPLIED:
  466. return SOCKS5_SUCCEEDED; /* never used */
  467. case END_STREAM_REASON_CANT_ATTACH:
  468. return SOCKS5_GENERAL_ERROR;
  469. case END_STREAM_REASON_NET_UNREACHABLE:
  470. return SOCKS5_NET_UNREACHABLE;
  471. default:
  472. log_fn(LOG_WARN,"Reason for ending (%d) not recognized.",reason);
  473. return SOCKS5_GENERAL_ERROR;
  474. }
  475. }
  476. /* We need to use a few macros to deal with the fact that Windows
  477. * decided that their sockets interface should be a permakludge.
  478. * E_CASE is for errors where windows has both a EFOO and a WSAEFOO
  479. * version, and S_CASE is for errors where windows has only a WSAEFOO
  480. * version. (The E is for 'error', the S is for 'socket'). */
  481. #ifdef MS_WINDOWS
  482. #define E_CASE(s) case s: case WSA ## s
  483. #define S_CASE(s) case WSA ## s
  484. #else
  485. #define E_CASE(s) case s
  486. #define S_CASE(s) case s
  487. #endif
  488. int
  489. errno_to_end_reason(int e)
  490. {
  491. switch (e) {
  492. case EPIPE:
  493. return END_STREAM_REASON_DONE;
  494. E_CASE(EBADF):
  495. E_CASE(EFAULT):
  496. E_CASE(EINVAL):
  497. S_CASE(EISCONN):
  498. S_CASE(ENOTSOCK):
  499. S_CASE(EPROTONOSUPPORT):
  500. S_CASE(EAFNOSUPPORT):
  501. E_CASE(EACCES):
  502. S_CASE(ENOTCONN):
  503. S_CASE(ENETUNREACH):
  504. return END_STREAM_REASON_INTERNAL;
  505. S_CASE(ECONNREFUSED):
  506. return END_STREAM_REASON_CONNECTREFUSED;
  507. S_CASE(ECONNRESET):
  508. return END_STREAM_REASON_CONNRESET;
  509. S_CASE(ETIMEDOUT):
  510. return END_STREAM_REASON_TIMEOUT;
  511. S_CASE(ENOBUFS):
  512. case ENOMEM:
  513. case ENFILE:
  514. E_CASE(EMFILE):
  515. return END_STREAM_REASON_RESOURCELIMIT;
  516. default:
  517. log_fn(LOG_INFO, "Didn't recognize errno %d (%s); telling the OP that we are ending a stream for 'misc' reason.",
  518. e, tor_socket_strerror(e));
  519. return END_STREAM_REASON_MISC;
  520. }
  521. }
  522. /** How many times will I retry a stream that fails due to DNS
  523. * resolve failure?
  524. */
  525. #define MAX_RESOLVE_FAILURES 3
  526. /** Return 1 if reason is something that you should retry if you
  527. * get the end cell before you've connected; else return 0. */
  528. static int
  529. edge_reason_is_retriable(int reason) {
  530. return reason == END_STREAM_REASON_HIBERNATING ||
  531. reason == END_STREAM_REASON_RESOURCELIMIT ||
  532. reason == END_STREAM_REASON_EXITPOLICY ||
  533. reason == END_STREAM_REASON_RESOLVEFAILED;
  534. }
  535. static int
  536. connection_edge_process_end_not_open(
  537. relay_header_t *rh, cell_t *cell, circuit_t *circ,
  538. connection_t *conn, crypt_path_t *layer_hint) {
  539. struct in_addr in;
  540. routerinfo_t *exitrouter;
  541. int reason = *(cell->payload+RELAY_HEADER_SIZE);
  542. if (rh->length > 0 && edge_reason_is_retriable(reason)) {
  543. if (conn->type != CONN_TYPE_AP) {
  544. log_fn(LOG_WARN,"Got an end because of %s, but we're not an AP. Closing.",
  545. connection_edge_end_reason_str(reason));
  546. return -1;
  547. }
  548. log_fn(LOG_INFO,"Address '%s' refused due to '%s'. Considering retrying.",
  549. safe_str(conn->socks_request->address),
  550. connection_edge_end_reason_str(reason));
  551. exitrouter = router_get_by_digest(circ->build_state->chosen_exit_digest);
  552. if (!exitrouter) {
  553. log_fn(LOG_INFO,"Skipping broken circ (exit router vanished)");
  554. return 0; /* this circuit is screwed and doesn't know it yet */
  555. }
  556. switch (reason) {
  557. case END_STREAM_REASON_EXITPOLICY:
  558. if (rh->length >= 5) {
  559. uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+1));
  560. if (!addr) {
  561. log_fn(LOG_INFO,"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. client_dns_set_addressmap(conn->socks_request->address, addr,
  567. conn->chosen_exit_name);
  568. }
  569. /* check if he *ought* to have allowed it */
  570. if (rh->length < 5 ||
  571. (!tor_inet_aton(conn->socks_request->address, &in) &&
  572. !conn->chosen_exit_name)) {
  573. 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);
  574. addr_policy_free(exitrouter->exit_policy);
  575. exitrouter->exit_policy =
  576. router_parse_addr_policy_from_string("reject *:*");
  577. }
  578. if (connection_ap_detach_retriable(conn, circ) >= 0)
  579. return 0;
  580. /* else, conn will get closed below */
  581. break;
  582. case END_STREAM_REASON_RESOLVEFAILED:
  583. if (client_dns_incr_failures(conn->socks_request->address)
  584. < MAX_RESOLVE_FAILURES) {
  585. /* We haven't retried too many times; reattach the connection. */
  586. circuit_log_path(LOG_INFO,circ);
  587. tor_assert(circ->timestamp_dirty);
  588. circ->timestamp_dirty -= get_options()->MaxCircuitDirtiness;
  589. if (connection_ap_detach_retriable(conn, circ) >= 0)
  590. return 0;
  591. /* else, conn will get closed below */
  592. } else {
  593. log_fn(LOG_NOTICE,"Have tried resolving address '%s' at %d different places. Giving up.",
  594. safe_str(conn->socks_request->address), MAX_RESOLVE_FAILURES);
  595. }
  596. break;
  597. case END_STREAM_REASON_HIBERNATING:
  598. case END_STREAM_REASON_RESOURCELIMIT:
  599. addr_policy_free(exitrouter->exit_policy);
  600. exitrouter->exit_policy =
  601. router_parse_addr_policy_from_string("reject *:*");
  602. if (connection_ap_detach_retriable(conn, circ) >= 0)
  603. return 0;
  604. /* else, will close below */
  605. break;
  606. } /* end switch */
  607. log_fn(LOG_INFO,"Giving up on retrying; conn can't be handled.");
  608. }
  609. log_fn(LOG_INFO,"Edge got end (%s) before we're connected. Marking for close.",
  610. connection_edge_end_reason_str(rh->length > 0 ? reason : -1));
  611. if (conn->type == CONN_TYPE_AP) {
  612. circuit_log_path(LOG_INFO,circ);
  613. connection_mark_unattached_ap(conn, reason);
  614. } else {
  615. conn->has_sent_end = 1; /* we just got an 'end', don't need to send one */
  616. connection_mark_for_close(conn);
  617. }
  618. return 0;
  619. }
  620. /** An incoming relay cell has arrived from circuit <b>circ</b> to
  621. * stream <b>conn</b>.
  622. *
  623. * The arguments here are the same as in
  624. * connection_edge_process_relay_cell() below; this function is called
  625. * from there when <b>conn</b> is defined and not in an open state.
  626. */
  627. static int
  628. connection_edge_process_relay_cell_not_open(
  629. relay_header_t *rh, cell_t *cell, circuit_t *circ,
  630. connection_t *conn, crypt_path_t *layer_hint) {
  631. if (rh->command == RELAY_COMMAND_END)
  632. return connection_edge_process_end_not_open(rh, cell, circ, conn, layer_hint);
  633. if (conn->type == CONN_TYPE_AP && rh->command == RELAY_COMMAND_CONNECTED) {
  634. if (conn->state != AP_CONN_STATE_CONNECT_WAIT) {
  635. log_fn(LOG_WARN,"Got 'connected' while not in state connect_wait. Dropping.");
  636. return 0;
  637. }
  638. // log_fn(LOG_INFO,"Connected! Notifying application.");
  639. conn->state = AP_CONN_STATE_OPEN;
  640. log_fn(LOG_INFO,"'connected' received after %d seconds.",
  641. (int)(time(NULL) - conn->timestamp_lastread));
  642. if (rh->length >= 4) {
  643. uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE));
  644. if (!addr) {
  645. log_fn(LOG_INFO,"...but it claims the IP address was 0.0.0.0. Closing.");
  646. connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL, conn->cpath_layer);
  647. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  648. return 0;
  649. }
  650. client_dns_set_addressmap(conn->socks_request->address, addr,
  651. conn->chosen_exit_name);
  652. }
  653. circuit_log_path(LOG_INFO,circ);
  654. connection_ap_handshake_socks_reply(conn, NULL, 0, SOCKS5_SUCCEEDED);
  655. /* handle anything that might have queued */
  656. if (connection_edge_package_raw_inbuf(conn, 1) < 0) {
  657. /* (We already sent an end cell if possible) */
  658. connection_mark_for_close(conn);
  659. return 0;
  660. }
  661. return 0;
  662. }
  663. if (conn->type == CONN_TYPE_AP && rh->command == RELAY_COMMAND_RESOLVED) {
  664. if (conn->state != AP_CONN_STATE_RESOLVE_WAIT) {
  665. log_fn(LOG_WARN,"Got a 'resolved' cell while not in state resolve_wait. Dropping.");
  666. return 0;
  667. }
  668. tor_assert(conn->socks_request->command == SOCKS_COMMAND_RESOLVE);
  669. if (rh->length < 2 || cell->payload[RELAY_HEADER_SIZE+1]+2>rh->length) {
  670. log_fn(LOG_WARN, "Dropping malformed 'resolved' cell");
  671. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  672. return 0;
  673. }
  674. connection_ap_handshake_socks_resolved(conn,
  675. cell->payload[RELAY_HEADER_SIZE], /*answer_type*/
  676. cell->payload[RELAY_HEADER_SIZE+1], /*answer_len*/
  677. cell->payload+RELAY_HEADER_SIZE+2); /* answer */
  678. connection_mark_unattached_ap(conn, END_STREAM_REASON_ALREADY_SOCKS_REPLIED);
  679. return 0;
  680. }
  681. log_fn(LOG_WARN,"Got an unexpected relay command %d, in state %d (%s). Closing.",
  682. rh->command, conn->state, conn_state_to_string(conn->type, conn->state));
  683. connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL, conn->cpath_layer);
  684. connection_mark_for_close(conn);
  685. return -1;
  686. }
  687. /** An incoming relay cell has arrived on circuit <b>circ</b>. If
  688. * <b>conn</b> is NULL this is a control cell, else <b>cell</b> is
  689. * destined for <b>conn</b>.
  690. *
  691. * If <b>layer_hint</b> is defined, then we're the origin of the
  692. * circuit, and it specifies the hop that packaged <b>cell</b>.
  693. *
  694. * Return -1 if you want to tear down the circuit, else 0.
  695. */
  696. static int
  697. connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
  698. connection_t *conn,
  699. crypt_path_t *layer_hint)
  700. {
  701. static int num_seen=0;
  702. relay_header_t rh;
  703. tor_assert(cell);
  704. tor_assert(circ);
  705. relay_header_unpack(&rh, cell->payload);
  706. // log_fn(LOG_DEBUG,"command %d stream %d", rh.command, rh.stream_id);
  707. num_seen++;
  708. log_fn(LOG_DEBUG,"Now seen %d relay cells here.", num_seen);
  709. if (rh.length > RELAY_PAYLOAD_SIZE) {
  710. log_fn(LOG_WARN, "Relay cell length field too long. Closing circuit.");
  711. return -1;
  712. }
  713. /* either conn is NULL, in which case we've got a control cell, or else
  714. * conn points to the recognized stream. */
  715. if (conn && !connection_state_is_open(conn))
  716. return connection_edge_process_relay_cell_not_open(
  717. &rh, cell, circ, conn, layer_hint);
  718. switch (rh.command) {
  719. case RELAY_COMMAND_DROP:
  720. log_fn(LOG_INFO,"Got a relay-level padding cell. Dropping.");
  721. return 0;
  722. case RELAY_COMMAND_BEGIN:
  723. if (layer_hint &&
  724. circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
  725. log_fn(LOG_WARN,"relay begin request unsupported at AP. Dropping.");
  726. return 0;
  727. }
  728. if (conn) {
  729. log_fn(LOG_WARN,"begin cell for known stream. Dropping.");
  730. return 0;
  731. }
  732. connection_exit_begin_conn(cell, circ);
  733. return 0;
  734. case RELAY_COMMAND_DATA:
  735. ++stats_n_data_cells_received;
  736. if (( layer_hint && --layer_hint->deliver_window < 0) ||
  737. (!layer_hint && --circ->deliver_window < 0)) {
  738. log_fn(LOG_WARN,"(relay data) circ deliver_window below 0. Killing.");
  739. connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL, conn->cpath_layer);
  740. connection_mark_for_close(conn);
  741. return -1;
  742. }
  743. log_fn(LOG_DEBUG,"circ deliver_window now %d.", layer_hint ?
  744. layer_hint->deliver_window : circ->deliver_window);
  745. circuit_consider_sending_sendme(circ, layer_hint);
  746. if (!conn) {
  747. log_fn(LOG_INFO,"data cell dropped, unknown stream.");
  748. return 0;
  749. }
  750. if (--conn->deliver_window < 0) { /* is it below 0 after decrement? */
  751. log_fn(LOG_WARN,"(relay data) conn deliver_window below 0. Killing.");
  752. return -1; /* somebody's breaking protocol. kill the whole circuit. */
  753. }
  754. stats_n_data_bytes_received += rh.length;
  755. connection_write_to_buf(cell->payload + RELAY_HEADER_SIZE,
  756. rh.length, conn);
  757. connection_edge_consider_sending_sendme(conn);
  758. return 0;
  759. case RELAY_COMMAND_END:
  760. if (!conn) {
  761. log_fn(LOG_INFO,"end cell (%s) dropped, unknown stream.",
  762. connection_edge_end_reason_str(rh.length > 0 ?
  763. *(char *)(cell->payload+RELAY_HEADER_SIZE) : -1));
  764. return 0;
  765. }
  766. /* XXX add to this log_fn the exit node's nickname? */
  767. log_fn(LOG_INFO,"%d: end cell (%s) for stream %d. Removing stream.",
  768. conn->s,
  769. connection_edge_end_reason_str(rh.length > 0 ?
  770. *(char *)(cell->payload+RELAY_HEADER_SIZE) : -1),
  771. conn->stream_id);
  772. if (conn->socks_request && !conn->socks_request->has_finished)
  773. log_fn(LOG_WARN,"Bug: open stream hasn't sent socks answer yet? Closing.");
  774. #ifdef HALF_OPEN
  775. conn->done_sending = 1;
  776. shutdown(conn->s, 1); /* XXX check return; refactor NM */
  777. if (conn->done_receiving) {
  778. /* We just *got* an end; no reason to send one. */
  779. conn->has_sent_end = 1;
  780. connection_mark_for_close(conn);
  781. conn->hold_open_until_flushed = 1;
  782. }
  783. #else
  784. /* We just *got* an end; no reason to send one. */
  785. conn->has_sent_end = 1;
  786. if (!conn->marked_for_close) {
  787. /* only mark it if not already marked. it's possible to
  788. * get the 'end' right around when the client hangs up on us. */
  789. connection_mark_for_close(conn);
  790. conn->hold_open_until_flushed = 1;
  791. }
  792. #endif
  793. return 0;
  794. case RELAY_COMMAND_EXTEND:
  795. if (conn) {
  796. log_fn(LOG_WARN,"'extend' for non-zero stream. Dropping.");
  797. return 0;
  798. }
  799. return circuit_extend(cell, circ);
  800. case RELAY_COMMAND_EXTENDED:
  801. if (!layer_hint) {
  802. log_fn(LOG_WARN,"'extended' unsupported at non-origin. Dropping.");
  803. return 0;
  804. }
  805. log_fn(LOG_DEBUG,"Got an extended cell! Yay.");
  806. if (circuit_finish_handshake(circ, CELL_CREATED,
  807. cell->payload+RELAY_HEADER_SIZE) < 0) {
  808. log_fn(LOG_WARN,"circuit_finish_handshake failed.");
  809. return -1;
  810. }
  811. if (circuit_send_next_onion_skin(circ)<0) {
  812. log_fn(LOG_INFO,"circuit_send_next_onion_skin() failed.");
  813. return -1;
  814. }
  815. return 0;
  816. case RELAY_COMMAND_TRUNCATE:
  817. if (layer_hint) {
  818. log_fn(LOG_WARN,"'truncate' unsupported at origin. Dropping.");
  819. return 0;
  820. }
  821. if (circ->n_conn) {
  822. connection_send_destroy(circ->n_circ_id, circ->n_conn);
  823. circuit_set_circid_orconn(circ, 0, NULL, N_CONN_CHANGED);
  824. }
  825. log_fn(LOG_DEBUG, "Processed 'truncate', replying.");
  826. connection_edge_send_command(NULL, circ, RELAY_COMMAND_TRUNCATED,
  827. NULL, 0, NULL);
  828. return 0;
  829. case RELAY_COMMAND_TRUNCATED:
  830. if (!layer_hint) {
  831. log_fn(LOG_WARN,"'truncated' unsupported at non-origin. Dropping.");
  832. return 0;
  833. }
  834. circuit_truncated(circ, layer_hint);
  835. return 0;
  836. case RELAY_COMMAND_CONNECTED:
  837. if (conn) {
  838. log_fn(LOG_WARN,"'connected' unsupported while open. Closing circ.");
  839. return -1;
  840. }
  841. log_fn(LOG_INFO,"'connected' received, no conn attached anymore. Ignoring.");
  842. return 0;
  843. case RELAY_COMMAND_SENDME:
  844. if (!conn) {
  845. if (layer_hint) {
  846. layer_hint->package_window += CIRCWINDOW_INCREMENT;
  847. log_fn(LOG_DEBUG,"circ-level sendme at origin, packagewindow %d.",
  848. layer_hint->package_window);
  849. circuit_resume_edge_reading(circ, layer_hint);
  850. } else {
  851. circ->package_window += CIRCWINDOW_INCREMENT;
  852. log_fn(LOG_DEBUG,"circ-level sendme at non-origin, packagewindow %d.",
  853. circ->package_window);
  854. circuit_resume_edge_reading(circ, layer_hint);
  855. }
  856. return 0;
  857. }
  858. conn->package_window += STREAMWINDOW_INCREMENT;
  859. log_fn(LOG_DEBUG,"stream-level sendme, packagewindow now %d.", conn->package_window);
  860. connection_start_reading(conn);
  861. /* handle whatever might still be on the inbuf */
  862. if (connection_edge_package_raw_inbuf(conn, 1) < 0) {
  863. /* (We already sent an end cell if possible) */
  864. connection_mark_for_close(conn);
  865. return 0;
  866. }
  867. return 0;
  868. case RELAY_COMMAND_RESOLVE:
  869. if (layer_hint) {
  870. log_fn(LOG_WARN,"resolve request unsupported at AP; dropping.");
  871. return 0;
  872. } else if (conn) {
  873. log_fn(LOG_WARN, "resolve request for known stream; dropping.");
  874. return 0;
  875. } else if (circ->purpose != CIRCUIT_PURPOSE_OR) {
  876. log_fn(LOG_WARN, "resolve request on circ with purpose %d; dropping",
  877. circ->purpose);
  878. return 0;
  879. }
  880. connection_exit_begin_resolve(cell, circ);
  881. return 0;
  882. case RELAY_COMMAND_RESOLVED:
  883. if (conn) {
  884. log_fn(LOG_WARN,"'resolved' unsupported while open. Closing circ.");
  885. return -1;
  886. }
  887. log_fn(LOG_INFO,"'resolved' received, no conn attached anymore. Ignoring.");
  888. return 0;
  889. case RELAY_COMMAND_ESTABLISH_INTRO:
  890. case RELAY_COMMAND_ESTABLISH_RENDEZVOUS:
  891. case RELAY_COMMAND_INTRODUCE1:
  892. case RELAY_COMMAND_INTRODUCE2:
  893. case RELAY_COMMAND_INTRODUCE_ACK:
  894. case RELAY_COMMAND_RENDEZVOUS1:
  895. case RELAY_COMMAND_RENDEZVOUS2:
  896. case RELAY_COMMAND_INTRO_ESTABLISHED:
  897. case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
  898. rend_process_relay_cell(circ, rh.command, rh.length,
  899. cell->payload+RELAY_HEADER_SIZE);
  900. return 0;
  901. }
  902. log_fn(LOG_WARN,"unknown relay command %d.",rh.command);
  903. return -1;
  904. }
  905. uint64_t stats_n_data_cells_packaged = 0;
  906. uint64_t stats_n_data_bytes_packaged = 0;
  907. uint64_t stats_n_data_cells_received = 0;
  908. uint64_t stats_n_data_bytes_received = 0;
  909. /** While conn->inbuf has an entire relay payload of bytes on it,
  910. * and the appropriate package windows aren't empty, grab a cell
  911. * and send it down the circuit.
  912. *
  913. * Return -1 (and send a RELAY_END cell if necessary) if conn should
  914. * be marked for close, else return 0.
  915. */
  916. int connection_edge_package_raw_inbuf(connection_t *conn, int package_partial) {
  917. size_t amount_to_process, length;
  918. char payload[CELL_PAYLOAD_SIZE];
  919. circuit_t *circ;
  920. tor_assert(conn);
  921. tor_assert(!connection_speaks_cells(conn));
  922. if (conn->marked_for_close) {
  923. log_fn(LOG_WARN,"Bug: called on conn that's already marked for close at %s:%d.",
  924. conn->marked_for_close_file, conn->marked_for_close);
  925. return 0;
  926. }
  927. repeat_connection_edge_package_raw_inbuf:
  928. circ = circuit_get_by_edge_conn(conn);
  929. if (!circ) {
  930. log_fn(LOG_INFO,"conn has no circuit! Closing.");
  931. return -1;
  932. }
  933. if (circuit_consider_stop_edge_reading(circ, conn->cpath_layer))
  934. return 0;
  935. if (conn->package_window <= 0) {
  936. log_fn(LOG_INFO,"called with package_window %d. Skipping.", conn->package_window);
  937. connection_stop_reading(conn);
  938. return 0;
  939. }
  940. amount_to_process = buf_datalen(conn->inbuf);
  941. if (!amount_to_process)
  942. return 0;
  943. if (!package_partial && amount_to_process < RELAY_PAYLOAD_SIZE)
  944. return 0;
  945. if (amount_to_process > RELAY_PAYLOAD_SIZE) {
  946. length = RELAY_PAYLOAD_SIZE;
  947. } else {
  948. length = amount_to_process;
  949. }
  950. stats_n_data_bytes_packaged += length;
  951. stats_n_data_cells_packaged += 1;
  952. connection_fetch_from_buf(payload, length, conn);
  953. log_fn(LOG_DEBUG,"(%d) Packaging %d bytes (%d waiting).", conn->s,
  954. (int)length, (int)buf_datalen(conn->inbuf));
  955. if (connection_edge_send_command(conn, circ, RELAY_COMMAND_DATA,
  956. payload, length, conn->cpath_layer) < 0)
  957. /* circuit got marked for close, don't continue, don't need to mark conn */
  958. return 0;
  959. if (!conn->cpath_layer) { /* non-rendezvous exit */
  960. tor_assert(circ->package_window > 0);
  961. circ->package_window--;
  962. } else { /* we're an AP, or an exit on a rendezvous circ */
  963. tor_assert(conn->cpath_layer->package_window > 0);
  964. conn->cpath_layer->package_window--;
  965. }
  966. if (--conn->package_window <= 0) { /* is it 0 after decrement? */
  967. connection_stop_reading(conn);
  968. log_fn(LOG_DEBUG,"conn->package_window reached 0.");
  969. circuit_consider_stop_edge_reading(circ, conn->cpath_layer);
  970. return 0; /* don't process the inbuf any more */
  971. }
  972. log_fn(LOG_DEBUG,"conn->package_window is now %d",conn->package_window);
  973. /* handle more if there's more, or return 0 if there isn't */
  974. goto repeat_connection_edge_package_raw_inbuf;
  975. }
  976. /** Called when we've just received a relay data cell, or when
  977. * we've just finished flushing all bytes to stream <b>conn</b>.
  978. *
  979. * If conn->outbuf is not too full, and our deliver window is
  980. * low, send back a suitable number of stream-level sendme cells.
  981. */
  982. void connection_edge_consider_sending_sendme(connection_t *conn) {
  983. circuit_t *circ;
  984. if (connection_outbuf_too_full(conn))
  985. return;
  986. circ = circuit_get_by_edge_conn(conn);
  987. if (!circ) {
  988. /* this can legitimately happen if the destroy has already
  989. * arrived and torn down the circuit */
  990. log_fn(LOG_INFO,"No circuit associated with conn. Skipping.");
  991. return;
  992. }
  993. while (conn->deliver_window < STREAMWINDOW_START - STREAMWINDOW_INCREMENT) {
  994. log_fn(LOG_DEBUG,"Outbuf %d, Queueing stream sendme.", (int)conn->outbuf_flushlen);
  995. conn->deliver_window += STREAMWINDOW_INCREMENT;
  996. if (connection_edge_send_command(conn, circ, RELAY_COMMAND_SENDME,
  997. NULL, 0, conn->cpath_layer) < 0) {
  998. log_fn(LOG_WARN,"connection_edge_send_command failed. Returning.");
  999. return; /* the circuit's closed, don't continue */
  1000. }
  1001. }
  1002. }
  1003. /** The circuit <b>circ</b> has received a circuit-level sendme
  1004. * (on hop <b>layer_hint</b>, if we're the OP). Go through all the
  1005. * attached streams and let them resume reading and packaging, if
  1006. * their stream windows allow it.
  1007. */
  1008. static void
  1009. circuit_resume_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
  1010. {
  1011. log_fn(LOG_DEBUG,"resuming");
  1012. /* have to check both n_streams and p_streams, to handle rendezvous */
  1013. if (circuit_resume_edge_reading_helper(circ->n_streams, circ, layer_hint) >= 0)
  1014. circuit_resume_edge_reading_helper(circ->p_streams, circ, layer_hint);
  1015. }
  1016. /** A helper function for circuit_resume_edge_reading() above.
  1017. * The arguments are the same, except that <b>conn</b> is the head
  1018. * of a linked list of edge streams that should each be considered.
  1019. */
  1020. static int
  1021. circuit_resume_edge_reading_helper(connection_t *conn,
  1022. circuit_t *circ,
  1023. crypt_path_t *layer_hint) {
  1024. for ( ; conn; conn=conn->next_stream) {
  1025. if (conn->marked_for_close)
  1026. continue;
  1027. if ((!layer_hint && conn->package_window > 0) ||
  1028. (layer_hint && conn->package_window > 0 && conn->cpath_layer == layer_hint)) {
  1029. connection_start_reading(conn);
  1030. /* handle whatever might still be on the inbuf */
  1031. if (connection_edge_package_raw_inbuf(conn, 1)<0) {
  1032. /* (We already sent an end cell if possible) */
  1033. connection_mark_for_close(conn);
  1034. continue;
  1035. }
  1036. /* If the circuit won't accept any more data, return without looking
  1037. * at any more of the streams. Any connections that should be stopped
  1038. * have already been stopped by connection_edge_package_raw_inbuf. */
  1039. if (circuit_consider_stop_edge_reading(circ, layer_hint))
  1040. return -1;
  1041. }
  1042. }
  1043. return 0;
  1044. }
  1045. /** Check if the package window for <b>circ</b> is empty (at
  1046. * hop <b>layer_hint</b> if it's defined).
  1047. *
  1048. * If yes, tell edge streams to stop reading and return 1.
  1049. * Else return 0.
  1050. */
  1051. static int
  1052. circuit_consider_stop_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
  1053. {
  1054. connection_t *conn = NULL;
  1055. if (!layer_hint) {
  1056. log_fn(LOG_DEBUG,"considering circ->package_window %d", circ->package_window);
  1057. if (circ->package_window <= 0) {
  1058. log_fn(LOG_DEBUG,"yes, not-at-origin. stopped.");
  1059. for (conn = circ->n_streams; conn; conn=conn->next_stream)
  1060. connection_stop_reading(conn);
  1061. return 1;
  1062. }
  1063. return 0;
  1064. }
  1065. /* else, layer hint is defined, use it */
  1066. log_fn(LOG_DEBUG,"considering layer_hint->package_window %d", layer_hint->package_window);
  1067. if (layer_hint->package_window <= 0) {
  1068. log_fn(LOG_DEBUG,"yes, at-origin. stopped.");
  1069. for (conn = circ->n_streams; conn; conn=conn->next_stream)
  1070. if (conn->cpath_layer == layer_hint)
  1071. connection_stop_reading(conn);
  1072. for (conn = circ->p_streams; conn; conn=conn->next_stream)
  1073. if (conn->cpath_layer == layer_hint)
  1074. connection_stop_reading(conn);
  1075. return 1;
  1076. }
  1077. return 0;
  1078. }
  1079. /** Check if the deliver_window for circuit <b>circ</b> (at hop
  1080. * <b>layer_hint</b> if it's defined) is low enough that we should
  1081. * send a circuit-level sendme back down the circuit. If so, send
  1082. * enough sendmes that the window would be overfull if we sent any
  1083. * more.
  1084. */
  1085. static void
  1086. circuit_consider_sending_sendme(circuit_t *circ, crypt_path_t *layer_hint)
  1087. {
  1088. // log_fn(LOG_INFO,"Considering: layer_hint is %s",
  1089. // layer_hint ? "defined" : "null");
  1090. while ((layer_hint ? layer_hint->deliver_window : circ->deliver_window) <
  1091. CIRCWINDOW_START - CIRCWINDOW_INCREMENT) {
  1092. log_fn(LOG_DEBUG,"Queueing circuit sendme.");
  1093. if (layer_hint)
  1094. layer_hint->deliver_window += CIRCWINDOW_INCREMENT;
  1095. else
  1096. circ->deliver_window += CIRCWINDOW_INCREMENT;
  1097. if (connection_edge_send_command(NULL, circ, RELAY_COMMAND_SENDME,
  1098. NULL, 0, layer_hint) < 0) {
  1099. log_fn(LOG_WARN,"connection_edge_send_command failed. Circuit's closed.");
  1100. return; /* the circuit's closed, don't continue */
  1101. }
  1102. }
  1103. }