relay.c 44 KB

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