relay.c 70 KB

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