relay.c 87 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462
  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-2012, 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. #define RELAY_PRIVATE
  12. #include "or.h"
  13. #include "addressmap.h"
  14. #include "buffers.h"
  15. #include "channel.h"
  16. #include "circuitbuild.h"
  17. #include "circuitlist.h"
  18. #include "config.h"
  19. #include "connection.h"
  20. #include "connection_edge.h"
  21. #include "connection_or.h"
  22. #include "control.h"
  23. #include "geoip.h"
  24. #include "main.h"
  25. #include "mempool.h"
  26. #include "networkstatus.h"
  27. #include "nodelist.h"
  28. #include "onion.h"
  29. #include "policies.h"
  30. #include "reasons.h"
  31. #include "relay.h"
  32. #include "rendcommon.h"
  33. #include "router.h"
  34. #include "routerlist.h"
  35. #include "routerparse.h"
  36. static edge_connection_t *relay_lookup_conn(circuit_t *circ, cell_t *cell,
  37. cell_direction_t cell_direction,
  38. crypt_path_t *layer_hint);
  39. static int connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
  40. edge_connection_t *conn,
  41. crypt_path_t *layer_hint);
  42. static void circuit_consider_sending_sendme(circuit_t *circ,
  43. crypt_path_t *layer_hint);
  44. static void circuit_resume_edge_reading(circuit_t *circ,
  45. crypt_path_t *layer_hint);
  46. static int circuit_resume_edge_reading_helper(edge_connection_t *conn,
  47. circuit_t *circ,
  48. crypt_path_t *layer_hint);
  49. static int circuit_consider_stop_edge_reading(circuit_t *circ,
  50. crypt_path_t *layer_hint);
  51. static int circuit_queue_streams_are_blocked(circuit_t *circ);
  52. /** Stop reading on edge connections when we have this many cells
  53. * waiting on the appropriate queue. */
  54. #define CELL_QUEUE_HIGHWATER_SIZE 256
  55. /** Start reading from edge connections again when we get down to this many
  56. * cells. */
  57. #define CELL_QUEUE_LOWWATER_SIZE 64
  58. /** Stats: how many relay cells have originated at this hop, or have
  59. * been relayed onward (not recognized at this hop)?
  60. */
  61. uint64_t stats_n_relay_cells_relayed = 0;
  62. /** Stats: how many relay cells have been delivered to streams at this
  63. * hop?
  64. */
  65. uint64_t stats_n_relay_cells_delivered = 0;
  66. /** Update digest from the payload of cell. Assign integrity part to
  67. * cell.
  68. */
  69. static void
  70. relay_set_digest(crypto_digest_t *digest, cell_t *cell)
  71. {
  72. char integrity[4];
  73. relay_header_t rh;
  74. crypto_digest_add_bytes(digest, (char*)cell->payload, CELL_PAYLOAD_SIZE);
  75. crypto_digest_get_digest(digest, integrity, 4);
  76. // log_fn(LOG_DEBUG,"Putting digest of %u %u %u %u into relay cell.",
  77. // integrity[0], integrity[1], integrity[2], integrity[3]);
  78. relay_header_unpack(&rh, cell->payload);
  79. memcpy(rh.integrity, integrity, 4);
  80. relay_header_pack(cell->payload, &rh);
  81. }
  82. /** Does the digest for this circuit indicate that this cell is for us?
  83. *
  84. * Update digest from the payload of cell (with the integrity part set
  85. * to 0). If the integrity part is valid, return 1, else restore digest
  86. * and cell to their original state and return 0.
  87. */
  88. static int
  89. relay_digest_matches(crypto_digest_t *digest, cell_t *cell)
  90. {
  91. char received_integrity[4], calculated_integrity[4];
  92. relay_header_t rh;
  93. crypto_digest_t *backup_digest=NULL;
  94. backup_digest = crypto_digest_dup(digest);
  95. relay_header_unpack(&rh, cell->payload);
  96. memcpy(received_integrity, rh.integrity, 4);
  97. memset(rh.integrity, 0, 4);
  98. relay_header_pack(cell->payload, &rh);
  99. // log_fn(LOG_DEBUG,"Reading digest of %u %u %u %u from relay cell.",
  100. // received_integrity[0], received_integrity[1],
  101. // received_integrity[2], received_integrity[3]);
  102. crypto_digest_add_bytes(digest, (char*) cell->payload, CELL_PAYLOAD_SIZE);
  103. crypto_digest_get_digest(digest, calculated_integrity, 4);
  104. if (tor_memneq(received_integrity, calculated_integrity, 4)) {
  105. // log_fn(LOG_INFO,"Recognized=0 but bad digest. Not recognizing.");
  106. // (%d vs %d).", received_integrity, calculated_integrity);
  107. /* restore digest to its old form */
  108. crypto_digest_assign(digest, backup_digest);
  109. /* restore the relay header */
  110. memcpy(rh.integrity, received_integrity, 4);
  111. relay_header_pack(cell->payload, &rh);
  112. crypto_digest_free(backup_digest);
  113. return 0;
  114. }
  115. crypto_digest_free(backup_digest);
  116. return 1;
  117. }
  118. /** Apply <b>cipher</b> to CELL_PAYLOAD_SIZE bytes of <b>in</b>
  119. * (in place).
  120. *
  121. * If <b>encrypt_mode</b> is 1 then encrypt, else decrypt.
  122. *
  123. * Return -1 if the crypto fails, else return 0.
  124. */
  125. static int
  126. relay_crypt_one_payload(crypto_cipher_t *cipher, uint8_t *in,
  127. int encrypt_mode)
  128. {
  129. int r;
  130. (void)encrypt_mode;
  131. r = crypto_cipher_crypt_inplace(cipher, (char*) in, CELL_PAYLOAD_SIZE);
  132. if (r) {
  133. log_warn(LD_BUG,"Error during relay encryption");
  134. return -1;
  135. }
  136. return 0;
  137. }
  138. /** Receive a relay cell:
  139. * - Crypt it (encrypt if headed toward the origin or if we <b>are</b> the
  140. * origin; decrypt if we're headed toward the exit).
  141. * - Check if recognized (if exitward).
  142. * - If recognized and the digest checks out, then find if there's a stream
  143. * that the cell is intended for, and deliver it to the right
  144. * connection_edge.
  145. * - If not recognized, then we need to relay it: append it to the appropriate
  146. * cell_queue on <b>circ</b>.
  147. *
  148. * Return -<b>reason</b> on failure.
  149. */
  150. int
  151. circuit_receive_relay_cell(cell_t *cell, circuit_t *circ,
  152. cell_direction_t cell_direction)
  153. {
  154. channel_t *chan = NULL;
  155. crypt_path_t *layer_hint=NULL;
  156. char recognized=0;
  157. int reason;
  158. tor_assert(cell);
  159. tor_assert(circ);
  160. tor_assert(cell_direction == CELL_DIRECTION_OUT ||
  161. cell_direction == CELL_DIRECTION_IN);
  162. if (circ->marked_for_close)
  163. return 0;
  164. if (relay_crypt(circ, cell, cell_direction, &layer_hint, &recognized) < 0) {
  165. log_warn(LD_BUG,"relay crypt failed. Dropping connection.");
  166. return -END_CIRC_REASON_INTERNAL;
  167. }
  168. if (recognized) {
  169. edge_connection_t *conn = relay_lookup_conn(circ, cell, cell_direction,
  170. layer_hint);
  171. if (cell_direction == CELL_DIRECTION_OUT) {
  172. ++stats_n_relay_cells_delivered;
  173. log_debug(LD_OR,"Sending away from origin.");
  174. if ((reason=connection_edge_process_relay_cell(cell, circ, conn, NULL))
  175. < 0) {
  176. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  177. "connection_edge_process_relay_cell (away from origin) "
  178. "failed.");
  179. return reason;
  180. }
  181. }
  182. if (cell_direction == CELL_DIRECTION_IN) {
  183. ++stats_n_relay_cells_delivered;
  184. log_debug(LD_OR,"Sending to origin.");
  185. if ((reason = connection_edge_process_relay_cell(cell, circ, conn,
  186. layer_hint)) < 0) {
  187. log_warn(LD_OR,
  188. "connection_edge_process_relay_cell (at origin) failed.");
  189. return reason;
  190. }
  191. }
  192. return 0;
  193. }
  194. /* not recognized. pass it on. */
  195. if (cell_direction == CELL_DIRECTION_OUT) {
  196. cell->circ_id = circ->n_circ_id; /* switch it */
  197. chan = circ->n_chan;
  198. } else if (! CIRCUIT_IS_ORIGIN(circ)) {
  199. cell->circ_id = TO_OR_CIRCUIT(circ)->p_circ_id; /* switch it */
  200. chan = TO_OR_CIRCUIT(circ)->p_chan;
  201. } else {
  202. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  203. "Dropping unrecognized inbound cell on origin circuit.");
  204. return 0;
  205. }
  206. if (!chan) {
  207. // XXXX Can this splice stuff be done more cleanly?
  208. if (! CIRCUIT_IS_ORIGIN(circ) &&
  209. TO_OR_CIRCUIT(circ)->rend_splice &&
  210. cell_direction == CELL_DIRECTION_OUT) {
  211. or_circuit_t *splice = TO_OR_CIRCUIT(circ)->rend_splice;
  212. tor_assert(circ->purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED);
  213. tor_assert(splice->base_.purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED);
  214. cell->circ_id = splice->p_circ_id;
  215. cell->command = CELL_RELAY; /* can't be relay_early anyway */
  216. if ((reason = circuit_receive_relay_cell(cell, TO_CIRCUIT(splice),
  217. CELL_DIRECTION_IN)) < 0) {
  218. log_warn(LD_REND, "Error relaying cell across rendezvous; closing "
  219. "circuits");
  220. /* XXXX Do this here, or just return -1? */
  221. circuit_mark_for_close(circ, -reason);
  222. return reason;
  223. }
  224. return 0;
  225. }
  226. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  227. "Didn't recognize cell, but circ stops here! Closing circ.");
  228. return -END_CIRC_REASON_TORPROTOCOL;
  229. }
  230. log_debug(LD_OR,"Passing on unrecognized cell.");
  231. ++stats_n_relay_cells_relayed; /* XXXX no longer quite accurate {cells}
  232. * we might kill the circ before we relay
  233. * the cells. */
  234. append_cell_to_circuit_queue(circ, chan, cell, cell_direction, 0);
  235. return 0;
  236. }
  237. /** Do the appropriate en/decryptions for <b>cell</b> arriving on
  238. * <b>circ</b> in direction <b>cell_direction</b>.
  239. *
  240. * If cell_direction == CELL_DIRECTION_IN:
  241. * - If we're at the origin (we're the OP), for hops 1..N,
  242. * decrypt cell. If recognized, stop.
  243. * - Else (we're not the OP), encrypt one hop. Cell is not recognized.
  244. *
  245. * If cell_direction == CELL_DIRECTION_OUT:
  246. * - decrypt one hop. Check if recognized.
  247. *
  248. * If cell is recognized, set *recognized to 1, and set
  249. * *layer_hint to the hop that recognized it.
  250. *
  251. * Return -1 to indicate that we should mark the circuit for close,
  252. * else return 0.
  253. */
  254. int
  255. relay_crypt(circuit_t *circ, cell_t *cell, cell_direction_t cell_direction,
  256. crypt_path_t **layer_hint, char *recognized)
  257. {
  258. relay_header_t rh;
  259. tor_assert(circ);
  260. tor_assert(cell);
  261. tor_assert(recognized);
  262. tor_assert(cell_direction == CELL_DIRECTION_IN ||
  263. cell_direction == CELL_DIRECTION_OUT);
  264. if (cell_direction == CELL_DIRECTION_IN) {
  265. if (CIRCUIT_IS_ORIGIN(circ)) { /* We're at the beginning of the circuit.
  266. * We'll want to do layered decrypts. */
  267. crypt_path_t *thishop, *cpath = TO_ORIGIN_CIRCUIT(circ)->cpath;
  268. thishop = cpath;
  269. if (thishop->state != CPATH_STATE_OPEN) {
  270. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  271. "Relay cell before first created cell? Closing.");
  272. return -1;
  273. }
  274. do { /* Remember: cpath is in forward order, that is, first hop first. */
  275. tor_assert(thishop);
  276. if (relay_crypt_one_payload(thishop->b_crypto, 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(thishop->b_digest, cell)) {
  282. *recognized = 1;
  283. *layer_hint = thishop;
  284. return 0;
  285. }
  286. }
  287. thishop = thishop->next;
  288. } while (thishop != cpath && thishop->state == CPATH_STATE_OPEN);
  289. log_fn(LOG_PROTOCOL_WARN, LD_OR,
  290. "Incoming cell at client not recognized. Closing.");
  291. return -1;
  292. } else { /* we're in the middle. Just one crypt. */
  293. if (relay_crypt_one_payload(TO_OR_CIRCUIT(circ)->p_crypto,
  294. cell->payload, 1) < 0)
  295. return -1;
  296. // log_fn(LOG_DEBUG,"Skipping recognized check, because we're not "
  297. // "the client.");
  298. }
  299. } else /* cell_direction == CELL_DIRECTION_OUT */ {
  300. /* we're in the middle. Just one crypt. */
  301. if (relay_crypt_one_payload(TO_OR_CIRCUIT(circ)->n_crypto,
  302. cell->payload, 0) < 0)
  303. return -1;
  304. relay_header_unpack(&rh, cell->payload);
  305. if (rh.recognized == 0) {
  306. /* it's possibly recognized. have to check digest to be sure. */
  307. if (relay_digest_matches(TO_OR_CIRCUIT(circ)->n_digest, cell)) {
  308. *recognized = 1;
  309. return 0;
  310. }
  311. }
  312. }
  313. return 0;
  314. }
  315. /** Package a relay cell from an edge:
  316. * - Encrypt it to the right layer
  317. * - Append it to the appropriate cell_queue on <b>circ</b>.
  318. */
  319. static int
  320. circuit_package_relay_cell(cell_t *cell, circuit_t *circ,
  321. cell_direction_t cell_direction,
  322. crypt_path_t *layer_hint, streamid_t on_stream)
  323. {
  324. channel_t *chan; /* where to send the cell */
  325. if (cell_direction == CELL_DIRECTION_OUT) {
  326. crypt_path_t *thishop; /* counter for repeated crypts */
  327. chan = circ->n_chan;
  328. if (!CIRCUIT_IS_ORIGIN(circ) || !chan) {
  329. log_warn(LD_BUG,"outgoing relay cell has n_chan==NULL. Dropping.");
  330. return 0; /* just drop it */
  331. }
  332. relay_set_digest(layer_hint->f_digest, cell);
  333. thishop = layer_hint;
  334. /* moving from farthest to nearest hop */
  335. do {
  336. tor_assert(thishop);
  337. /* XXXX RD This is a bug, right? */
  338. log_debug(LD_OR,"crypting a layer of the relay cell.");
  339. if (relay_crypt_one_payload(thishop->f_crypto, cell->payload, 1) < 0) {
  340. return -1;
  341. }
  342. thishop = thishop->prev;
  343. } while (thishop != TO_ORIGIN_CIRCUIT(circ)->cpath->prev);
  344. } else { /* incoming cell */
  345. or_circuit_t *or_circ;
  346. if (CIRCUIT_IS_ORIGIN(circ)) {
  347. /* We should never package an _incoming_ cell from the circuit
  348. * origin; that means we messed up somewhere. */
  349. log_warn(LD_BUG,"incoming relay cell at origin circuit. Dropping.");
  350. assert_circuit_ok(circ);
  351. return 0; /* just drop it */
  352. }
  353. or_circ = TO_OR_CIRCUIT(circ);
  354. chan = or_circ->p_chan;
  355. relay_set_digest(or_circ->p_digest, cell);
  356. if (relay_crypt_one_payload(or_circ->p_crypto, cell->payload, 1) < 0)
  357. return -1;
  358. }
  359. ++stats_n_relay_cells_relayed;
  360. append_cell_to_circuit_queue(circ, chan, cell, cell_direction, on_stream);
  361. return 0;
  362. }
  363. /** If cell's stream_id matches the stream_id of any conn that's
  364. * attached to circ, return that conn, else return NULL.
  365. */
  366. static edge_connection_t *
  367. relay_lookup_conn(circuit_t *circ, cell_t *cell,
  368. cell_direction_t cell_direction, crypt_path_t *layer_hint)
  369. {
  370. edge_connection_t *tmpconn;
  371. relay_header_t rh;
  372. relay_header_unpack(&rh, cell->payload);
  373. if (!rh.stream_id)
  374. return NULL;
  375. /* IN or OUT cells could have come from either direction, now
  376. * that we allow rendezvous *to* an OP.
  377. */
  378. if (CIRCUIT_IS_ORIGIN(circ)) {
  379. for (tmpconn = TO_ORIGIN_CIRCUIT(circ)->p_streams; tmpconn;
  380. tmpconn=tmpconn->next_stream) {
  381. if (rh.stream_id == tmpconn->stream_id &&
  382. !tmpconn->base_.marked_for_close &&
  383. tmpconn->cpath_layer == layer_hint) {
  384. log_debug(LD_APP,"found conn for stream %d.", rh.stream_id);
  385. return tmpconn;
  386. }
  387. }
  388. } else {
  389. for (tmpconn = TO_OR_CIRCUIT(circ)->n_streams; tmpconn;
  390. tmpconn=tmpconn->next_stream) {
  391. if (rh.stream_id == tmpconn->stream_id &&
  392. !tmpconn->base_.marked_for_close) {
  393. log_debug(LD_EXIT,"found conn for stream %d.", rh.stream_id);
  394. if (cell_direction == CELL_DIRECTION_OUT ||
  395. connection_edge_is_rendezvous_stream(tmpconn))
  396. return tmpconn;
  397. }
  398. }
  399. for (tmpconn = TO_OR_CIRCUIT(circ)->resolving_streams; tmpconn;
  400. tmpconn=tmpconn->next_stream) {
  401. if (rh.stream_id == tmpconn->stream_id &&
  402. !tmpconn->base_.marked_for_close) {
  403. log_debug(LD_EXIT,"found conn for stream %d.", rh.stream_id);
  404. return tmpconn;
  405. }
  406. }
  407. }
  408. return NULL; /* probably a begin relay cell */
  409. }
  410. /** Pack the relay_header_t host-order structure <b>src</b> into
  411. * network-order in the buffer <b>dest</b>. See tor-spec.txt for details
  412. * about the wire format.
  413. */
  414. void
  415. relay_header_pack(uint8_t *dest, const relay_header_t *src)
  416. {
  417. set_uint8(dest, src->command);
  418. set_uint16(dest+1, htons(src->recognized));
  419. set_uint16(dest+3, htons(src->stream_id));
  420. memcpy(dest+5, src->integrity, 4);
  421. set_uint16(dest+9, htons(src->length));
  422. }
  423. /** Unpack the network-order buffer <b>src</b> into a host-order
  424. * relay_header_t structure <b>dest</b>.
  425. */
  426. void
  427. relay_header_unpack(relay_header_t *dest, const uint8_t *src)
  428. {
  429. dest->command = get_uint8(src);
  430. dest->recognized = ntohs(get_uint16(src+1));
  431. dest->stream_id = ntohs(get_uint16(src+3));
  432. memcpy(dest->integrity, src+5, 4);
  433. dest->length = ntohs(get_uint16(src+9));
  434. }
  435. /** Convert the relay <b>command</b> into a human-readable string. */
  436. static const char *
  437. relay_command_to_string(uint8_t command)
  438. {
  439. switch (command) {
  440. case RELAY_COMMAND_BEGIN: return "BEGIN";
  441. case RELAY_COMMAND_DATA: return "DATA";
  442. case RELAY_COMMAND_END: return "END";
  443. case RELAY_COMMAND_CONNECTED: return "CONNECTED";
  444. case RELAY_COMMAND_SENDME: return "SENDME";
  445. case RELAY_COMMAND_EXTEND: return "EXTEND";
  446. case RELAY_COMMAND_EXTENDED: return "EXTENDED";
  447. case RELAY_COMMAND_TRUNCATE: return "TRUNCATE";
  448. case RELAY_COMMAND_TRUNCATED: return "TRUNCATED";
  449. case RELAY_COMMAND_DROP: return "DROP";
  450. case RELAY_COMMAND_RESOLVE: return "RESOLVE";
  451. case RELAY_COMMAND_RESOLVED: return "RESOLVED";
  452. case RELAY_COMMAND_BEGIN_DIR: return "BEGIN_DIR";
  453. case RELAY_COMMAND_ESTABLISH_INTRO: return "ESTABLISH_INTRO";
  454. case RELAY_COMMAND_ESTABLISH_RENDEZVOUS: return "ESTABLISH_RENDEZVOUS";
  455. case RELAY_COMMAND_INTRODUCE1: return "INTRODUCE1";
  456. case RELAY_COMMAND_INTRODUCE2: return "INTRODUCE2";
  457. case RELAY_COMMAND_RENDEZVOUS1: return "RENDEZVOUS1";
  458. case RELAY_COMMAND_RENDEZVOUS2: return "RENDEZVOUS2";
  459. case RELAY_COMMAND_INTRO_ESTABLISHED: return "INTRO_ESTABLISHED";
  460. case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
  461. return "RENDEZVOUS_ESTABLISHED";
  462. case RELAY_COMMAND_INTRODUCE_ACK: return "INTRODUCE_ACK";
  463. default: return "(unrecognized)";
  464. }
  465. }
  466. /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and send
  467. * it onto the open circuit <b>circ</b>. <b>stream_id</b> is the ID on
  468. * <b>circ</b> for the stream that's sending the relay cell, or 0 if it's a
  469. * control cell. <b>cpath_layer</b> is NULL for OR->OP cells, or the
  470. * destination hop for OP->OR cells.
  471. *
  472. * If you can't send the cell, mark the circuit for close and return -1. Else
  473. * return 0.
  474. */
  475. int
  476. relay_send_command_from_edge(streamid_t stream_id, circuit_t *circ,
  477. uint8_t relay_command, const char *payload,
  478. size_t payload_len, crypt_path_t *cpath_layer)
  479. {
  480. cell_t cell;
  481. relay_header_t rh;
  482. cell_direction_t cell_direction;
  483. /* XXXX NM Split this function into a separate versions per circuit type? */
  484. tor_assert(circ);
  485. tor_assert(payload_len <= RELAY_PAYLOAD_SIZE);
  486. memset(&cell, 0, sizeof(cell_t));
  487. cell.command = CELL_RELAY;
  488. if (cpath_layer) {
  489. cell.circ_id = circ->n_circ_id;
  490. cell_direction = CELL_DIRECTION_OUT;
  491. } else if (! CIRCUIT_IS_ORIGIN(circ)) {
  492. cell.circ_id = TO_OR_CIRCUIT(circ)->p_circ_id;
  493. cell_direction = CELL_DIRECTION_IN;
  494. } else {
  495. return -1;
  496. }
  497. memset(&rh, 0, sizeof(rh));
  498. rh.command = relay_command;
  499. rh.stream_id = stream_id;
  500. rh.length = payload_len;
  501. relay_header_pack(cell.payload, &rh);
  502. if (payload_len)
  503. memcpy(cell.payload+RELAY_HEADER_SIZE, payload, payload_len);
  504. log_debug(LD_OR,"delivering %d cell %s.", relay_command,
  505. cell_direction == CELL_DIRECTION_OUT ? "forward" : "backward");
  506. /* If we are sending an END cell and this circuit is used for a tunneled
  507. * directory request, advance its state. */
  508. if (relay_command == RELAY_COMMAND_END && circ->dirreq_id)
  509. geoip_change_dirreq_state(circ->dirreq_id, DIRREQ_TUNNELED,
  510. DIRREQ_END_CELL_SENT);
  511. if (cell_direction == CELL_DIRECTION_OUT && circ->n_chan) {
  512. /* if we're using relaybandwidthrate, this conn wants priority */
  513. channel_timestamp_client(circ->n_chan);
  514. }
  515. if (cell_direction == CELL_DIRECTION_OUT) {
  516. origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
  517. if (origin_circ->remaining_relay_early_cells > 0 &&
  518. (relay_command == RELAY_COMMAND_EXTEND ||
  519. cpath_layer != origin_circ->cpath)) {
  520. /* If we've got any relay_early cells left and (we're sending
  521. * an extend cell or we're not talking to the first hop), use
  522. * one of them. Don't worry about the conn protocol version:
  523. * append_cell_to_circuit_queue will fix it up. */
  524. cell.command = CELL_RELAY_EARLY;
  525. --origin_circ->remaining_relay_early_cells;
  526. log_debug(LD_OR, "Sending a RELAY_EARLY cell; %d remaining.",
  527. (int)origin_circ->remaining_relay_early_cells);
  528. /* Memorize the command that is sent as RELAY_EARLY cell; helps debug
  529. * task 878. */
  530. origin_circ->relay_early_commands[
  531. origin_circ->relay_early_cells_sent++] = relay_command;
  532. } else if (relay_command == RELAY_COMMAND_EXTEND) {
  533. /* If no RELAY_EARLY cells can be sent over this circuit, log which
  534. * commands have been sent as RELAY_EARLY cells before; helps debug
  535. * task 878. */
  536. smartlist_t *commands_list = smartlist_new();
  537. int i = 0;
  538. char *commands = NULL;
  539. for (; i < origin_circ->relay_early_cells_sent; i++)
  540. smartlist_add(commands_list, (char *)
  541. relay_command_to_string(origin_circ->relay_early_commands[i]));
  542. commands = smartlist_join_strings(commands_list, ",", 0, NULL);
  543. log_warn(LD_BUG, "Uh-oh. We're sending a RELAY_COMMAND_EXTEND cell, "
  544. "but we have run out of RELAY_EARLY cells on that circuit. "
  545. "Commands sent before: %s", commands);
  546. tor_free(commands);
  547. smartlist_free(commands_list);
  548. }
  549. }
  550. if (circuit_package_relay_cell(&cell, circ, cell_direction, cpath_layer,
  551. stream_id) < 0) {
  552. log_warn(LD_BUG,"circuit_package_relay_cell failed. Closing.");
  553. circuit_mark_for_close(circ, END_CIRC_REASON_INTERNAL);
  554. return -1;
  555. }
  556. return 0;
  557. }
  558. /** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and
  559. * send it onto the open circuit <b>circ</b>. <b>fromconn</b> is the stream
  560. * that's sending the relay cell, or NULL if it's a control cell.
  561. * <b>cpath_layer</b> is NULL for OR->OP cells, or the destination hop
  562. * for OP->OR cells.
  563. *
  564. * If you can't send the cell, mark the circuit for close and
  565. * return -1. Else return 0.
  566. */
  567. int
  568. connection_edge_send_command(edge_connection_t *fromconn,
  569. uint8_t relay_command, const char *payload,
  570. size_t payload_len)
  571. {
  572. /* XXXX NM Split this function into a separate versions per circuit type? */
  573. circuit_t *circ;
  574. crypt_path_t *cpath_layer = fromconn->cpath_layer;
  575. tor_assert(fromconn);
  576. circ = fromconn->on_circuit;
  577. if (fromconn->base_.marked_for_close) {
  578. log_warn(LD_BUG,
  579. "called on conn that's already marked for close at %s:%d.",
  580. fromconn->base_.marked_for_close_file,
  581. fromconn->base_.marked_for_close);
  582. return 0;
  583. }
  584. if (!circ) {
  585. if (fromconn->base_.type == CONN_TYPE_AP) {
  586. log_info(LD_APP,"no circ. Closing conn.");
  587. connection_mark_unattached_ap(EDGE_TO_ENTRY_CONN(fromconn),
  588. END_STREAM_REASON_INTERNAL);
  589. } else {
  590. log_info(LD_EXIT,"no circ. Closing conn.");
  591. fromconn->edge_has_sent_end = 1; /* no circ to send to */
  592. fromconn->end_reason = END_STREAM_REASON_INTERNAL;
  593. connection_mark_for_close(TO_CONN(fromconn));
  594. }
  595. return -1;
  596. }
  597. return relay_send_command_from_edge(fromconn->stream_id, circ,
  598. relay_command, payload,
  599. payload_len, cpath_layer);
  600. }
  601. /** How many times will I retry a stream that fails due to DNS
  602. * resolve failure or misc error?
  603. */
  604. #define MAX_RESOLVE_FAILURES 3
  605. /** Return 1 if reason is something that you should retry if you
  606. * get the end cell before you've connected; else return 0. */
  607. static int
  608. edge_reason_is_retriable(int reason)
  609. {
  610. return reason == END_STREAM_REASON_HIBERNATING ||
  611. reason == END_STREAM_REASON_RESOURCELIMIT ||
  612. reason == END_STREAM_REASON_EXITPOLICY ||
  613. reason == END_STREAM_REASON_RESOLVEFAILED ||
  614. reason == END_STREAM_REASON_MISC ||
  615. reason == END_STREAM_REASON_NOROUTE;
  616. }
  617. /** Called when we receive an END cell on a stream that isn't open yet,
  618. * from the client side.
  619. * Arguments are as for connection_edge_process_relay_cell().
  620. */
  621. static int
  622. connection_ap_process_end_not_open(
  623. relay_header_t *rh, cell_t *cell, origin_circuit_t *circ,
  624. entry_connection_t *conn, crypt_path_t *layer_hint)
  625. {
  626. struct in_addr in;
  627. node_t *exitrouter;
  628. int reason = *(cell->payload+RELAY_HEADER_SIZE);
  629. int control_reason = reason | END_STREAM_REASON_FLAG_REMOTE;
  630. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
  631. (void) layer_hint; /* unused */
  632. if (rh->length > 0 && edge_reason_is_retriable(reason) &&
  633. /* avoid retry if rend */
  634. !connection_edge_is_rendezvous_stream(edge_conn)) {
  635. const char *chosen_exit_digest =
  636. circ->build_state->chosen_exit->identity_digest;
  637. log_info(LD_APP,"Address '%s' refused due to '%s'. Considering retrying.",
  638. safe_str(conn->socks_request->address),
  639. stream_end_reason_to_string(reason));
  640. exitrouter = node_get_mutable_by_id(chosen_exit_digest);
  641. switch (reason) {
  642. case END_STREAM_REASON_EXITPOLICY:
  643. if (rh->length >= 5) {
  644. tor_addr_t addr;
  645. int ttl = -1;
  646. tor_addr_make_unspec(&addr);
  647. if (rh->length == 5 || rh->length == 9) {
  648. tor_addr_from_ipv4n(&addr,
  649. get_uint32(cell->payload+RELAY_HEADER_SIZE+1));
  650. if (rh->length == 9)
  651. ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+5));
  652. } else if (rh->length == 17 || rh->length == 21) {
  653. tor_addr_from_ipv6_bytes(&addr,
  654. (char*)(cell->payload+RELAY_HEADER_SIZE+1));
  655. if (rh->length == 21)
  656. ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+17));
  657. }
  658. if (tor_addr_is_null(&addr)) {
  659. log_info(LD_APP,"Address '%s' resolved to 0.0.0.0. Closing,",
  660. safe_str(conn->socks_request->address));
  661. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  662. return 0;
  663. }
  664. if ((tor_addr_family(&addr) == AF_INET && !conn->ipv4_traffic_ok) ||
  665. (tor_addr_family(&addr) == AF_INET6 && !conn->ipv6_traffic_ok)) {
  666. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  667. "Got an EXITPOLICY failure on a connection with a "
  668. "mismatched family. Closing.");
  669. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  670. return 0;
  671. }
  672. if (get_options()->ClientDNSRejectInternalAddresses &&
  673. tor_addr_is_internal(&addr, 0)) {
  674. log_info(LD_APP,"Address '%s' resolved to internal. Closing,",
  675. safe_str(conn->socks_request->address));
  676. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  677. return 0;
  678. }
  679. client_dns_set_addressmap(circ,
  680. conn->socks_request->address, &addr,
  681. conn->chosen_exit_name, ttl);
  682. }
  683. /* check if he *ought* to have allowed it */
  684. if (exitrouter &&
  685. (rh->length < 5 ||
  686. (tor_inet_aton(conn->socks_request->address, &in) &&
  687. !conn->chosen_exit_name))) {
  688. log_info(LD_APP,
  689. "Exitrouter %s seems to be more restrictive than its exit "
  690. "policy. Not using this router as exit for now.",
  691. node_describe(exitrouter));
  692. policies_set_node_exitpolicy_to_reject_all(exitrouter);
  693. }
  694. /* rewrite it to an IP if we learned one. */
  695. if (addressmap_rewrite(conn->socks_request->address,
  696. sizeof(conn->socks_request->address),
  697. NULL, NULL)) {
  698. control_event_stream_status(conn, STREAM_EVENT_REMAP, 0);
  699. }
  700. if (conn->chosen_exit_optional ||
  701. conn->chosen_exit_retries) {
  702. /* stop wanting a specific exit */
  703. conn->chosen_exit_optional = 0;
  704. /* A non-zero chosen_exit_retries can happen if we set a
  705. * TrackHostExits for this address under a port that the exit
  706. * relay allows, but then try the same address with a different
  707. * port that it doesn't allow to exit. We shouldn't unregister
  708. * the mapping, since it is probably still wanted on the
  709. * original port. But now we give away to the exit relay that
  710. * we probably have a TrackHostExits on it. So be it. */
  711. conn->chosen_exit_retries = 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, conn will get closed below */
  717. break;
  718. case END_STREAM_REASON_CONNECTREFUSED:
  719. if (!conn->chosen_exit_optional)
  720. break; /* break means it'll close, below */
  721. /* Else fall through: expire this circuit, clear the
  722. * chosen_exit_name field, and try again. */
  723. case END_STREAM_REASON_RESOLVEFAILED:
  724. case END_STREAM_REASON_TIMEOUT:
  725. case END_STREAM_REASON_MISC:
  726. case END_STREAM_REASON_NOROUTE:
  727. if (client_dns_incr_failures(conn->socks_request->address)
  728. < MAX_RESOLVE_FAILURES) {
  729. /* We haven't retried too many times; reattach the connection. */
  730. circuit_log_path(LOG_INFO,LD_APP,circ);
  731. /* Mark this circuit "unusable for new streams". */
  732. /* XXXX024 this is a kludgy way to do this. */
  733. tor_assert(circ->base_.timestamp_dirty);
  734. circ->base_.timestamp_dirty -= get_options()->MaxCircuitDirtiness;
  735. if (conn->chosen_exit_optional) {
  736. /* stop wanting a specific exit */
  737. conn->chosen_exit_optional = 0;
  738. tor_free(conn->chosen_exit_name); /* clears it */
  739. }
  740. if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
  741. return 0;
  742. /* else, conn will get closed below */
  743. } else {
  744. log_notice(LD_APP,
  745. "Have tried resolving or connecting to address '%s' "
  746. "at %d different places. Giving up.",
  747. safe_str(conn->socks_request->address),
  748. MAX_RESOLVE_FAILURES);
  749. /* clear the failures, so it will have a full try next time */
  750. client_dns_clear_failures(conn->socks_request->address);
  751. }
  752. break;
  753. case END_STREAM_REASON_HIBERNATING:
  754. case END_STREAM_REASON_RESOURCELIMIT:
  755. if (exitrouter) {
  756. policies_set_node_exitpolicy_to_reject_all(exitrouter);
  757. }
  758. if (conn->chosen_exit_optional) {
  759. /* stop wanting a specific exit */
  760. conn->chosen_exit_optional = 0;
  761. tor_free(conn->chosen_exit_name); /* clears it */
  762. }
  763. if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
  764. return 0;
  765. /* else, will close below */
  766. break;
  767. } /* end switch */
  768. log_info(LD_APP,"Giving up on retrying; conn can't be handled.");
  769. }
  770. log_info(LD_APP,
  771. "Edge got end (%s) before we're connected. Marking for close.",
  772. stream_end_reason_to_string(rh->length > 0 ? reason : -1));
  773. circuit_log_path(LOG_INFO,LD_APP,circ);
  774. /* need to test because of detach_retriable */
  775. if (!ENTRY_TO_CONN(conn)->marked_for_close)
  776. connection_mark_unattached_ap(conn, control_reason);
  777. return 0;
  778. }
  779. /** Helper: change the socks_request-&gt;address field on conn to the
  780. * dotted-quad representation of <b>new_addr</b>,
  781. * and send an appropriate REMAP event. */
  782. static void
  783. remap_event_helper(entry_connection_t *conn, const tor_addr_t *new_addr)
  784. {
  785. tor_addr_to_str(conn->socks_request->address, new_addr,
  786. sizeof(conn->socks_request->address),
  787. 1);
  788. control_event_stream_status(conn, STREAM_EVENT_REMAP,
  789. REMAP_STREAM_SOURCE_EXIT);
  790. }
  791. /** Extract the contents of a connected cell in <b>cell</b>, whose relay
  792. * header has already been parsed into <b>rh</b>. On success, set
  793. * <b>addr_out</b> to the address we're connected to, and <b>ttl_out</b> to
  794. * the ttl of that address, in seconds, and return 0. On failure, return
  795. * -1. */
  796. int
  797. connected_cell_parse(const relay_header_t *rh, const cell_t *cell,
  798. tor_addr_t *addr_out, int *ttl_out)
  799. {
  800. uint32_t bytes;
  801. const uint8_t *payload = cell->payload + RELAY_HEADER_SIZE;
  802. tor_addr_make_unspec(addr_out);
  803. *ttl_out = -1;
  804. if (rh->length == 0)
  805. return 0;
  806. if (rh->length < 4)
  807. return -1;
  808. bytes = ntohl(get_uint32(payload));
  809. /* If bytes is 0, this is maybe a v6 address. Otherwise it's a v4 address */
  810. if (bytes != 0) {
  811. /* v4 address */
  812. tor_addr_from_ipv4h(addr_out, bytes);
  813. if (rh->length >= 8) {
  814. bytes = ntohl(get_uint32(payload + 4));
  815. if (bytes <= INT32_MAX)
  816. *ttl_out = bytes;
  817. }
  818. } else {
  819. if (rh->length < 25) /* 4 bytes of 0s, 1 addr, 16 ipv4, 4 ttl. */
  820. return -1;
  821. if (get_uint8(payload + 4) != 6)
  822. return -1;
  823. tor_addr_from_ipv6_bytes(addr_out, (char*)(payload + 5));
  824. bytes = ntohl(get_uint32(payload + 21));
  825. if (bytes <= INT32_MAX)
  826. *ttl_out = (int) bytes;
  827. }
  828. return 0;
  829. }
  830. /** An incoming relay cell has arrived from circuit <b>circ</b> to
  831. * stream <b>conn</b>.
  832. *
  833. * The arguments here are the same as in
  834. * connection_edge_process_relay_cell() below; this function is called
  835. * from there when <b>conn</b> is defined and not in an open state.
  836. */
  837. static int
  838. connection_edge_process_relay_cell_not_open(
  839. relay_header_t *rh, cell_t *cell, circuit_t *circ,
  840. edge_connection_t *conn, crypt_path_t *layer_hint)
  841. {
  842. if (rh->command == RELAY_COMMAND_END) {
  843. if (CIRCUIT_IS_ORIGIN(circ) && conn->base_.type == CONN_TYPE_AP) {
  844. return connection_ap_process_end_not_open(rh, cell,
  845. TO_ORIGIN_CIRCUIT(circ),
  846. EDGE_TO_ENTRY_CONN(conn),
  847. layer_hint);
  848. } else {
  849. /* we just got an 'end', don't need to send one */
  850. conn->edge_has_sent_end = 1;
  851. conn->end_reason = *(cell->payload+RELAY_HEADER_SIZE) |
  852. END_STREAM_REASON_FLAG_REMOTE;
  853. connection_mark_for_close(TO_CONN(conn));
  854. return 0;
  855. }
  856. }
  857. if (conn->base_.type == CONN_TYPE_AP &&
  858. rh->command == RELAY_COMMAND_CONNECTED) {
  859. tor_addr_t addr;
  860. int ttl;
  861. entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
  862. tor_assert(CIRCUIT_IS_ORIGIN(circ));
  863. if (conn->base_.state != AP_CONN_STATE_CONNECT_WAIT) {
  864. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  865. "Got 'connected' while not in state connect_wait. Dropping.");
  866. return 0;
  867. }
  868. conn->base_.state = AP_CONN_STATE_OPEN;
  869. log_info(LD_APP,"'connected' received after %d seconds.",
  870. (int)(time(NULL) - conn->base_.timestamp_lastread));
  871. if (connected_cell_parse(rh, cell, &addr, &ttl) < 0) {
  872. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  873. "Got a badly formatted connected cell. Closing.");
  874. connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
  875. connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TORPROTOCOL);
  876. }
  877. if (tor_addr_family(&addr) != AF_UNSPEC) {
  878. const sa_family_t family = tor_addr_family(&addr);
  879. if (tor_addr_is_null(&addr) ||
  880. (get_options()->ClientDNSRejectInternalAddresses &&
  881. tor_addr_is_internal(&addr, 0))) {
  882. log_info(LD_APP, "...but it claims the IP address was %s. Closing.",
  883. fmt_addr(&addr));
  884. connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
  885. connection_mark_unattached_ap(entry_conn,
  886. END_STREAM_REASON_TORPROTOCOL);
  887. return 0;
  888. }
  889. if ((family == AF_INET && ! entry_conn->ipv4_traffic_ok) ||
  890. (family == AF_INET6 && ! entry_conn->ipv6_traffic_ok)) {
  891. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  892. "Got a connected cell to %s with unsupported address family."
  893. " Closing.", fmt_addr(&addr));
  894. connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
  895. connection_mark_unattached_ap(entry_conn,
  896. END_STREAM_REASON_TORPROTOCOL);
  897. return 0;
  898. }
  899. client_dns_set_addressmap(TO_ORIGIN_CIRCUIT(circ),
  900. entry_conn->socks_request->address, &addr,
  901. entry_conn->chosen_exit_name, ttl);
  902. remap_event_helper(entry_conn, &addr);
  903. }
  904. circuit_log_path(LOG_INFO,LD_APP,TO_ORIGIN_CIRCUIT(circ));
  905. /* don't send a socks reply to transparent conns */
  906. tor_assert(entry_conn->socks_request != NULL);
  907. if (!entry_conn->socks_request->has_finished)
  908. connection_ap_handshake_socks_reply(entry_conn, NULL, 0, 0);
  909. /* Was it a linked dir conn? If so, a dir request just started to
  910. * fetch something; this could be a bootstrap status milestone. */
  911. log_debug(LD_APP, "considering");
  912. if (TO_CONN(conn)->linked_conn &&
  913. TO_CONN(conn)->linked_conn->type == CONN_TYPE_DIR) {
  914. connection_t *dirconn = TO_CONN(conn)->linked_conn;
  915. log_debug(LD_APP, "it is! %d", dirconn->purpose);
  916. switch (dirconn->purpose) {
  917. case DIR_PURPOSE_FETCH_CERTIFICATE:
  918. if (consensus_is_waiting_for_certs())
  919. control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_KEYS, 0);
  920. break;
  921. case DIR_PURPOSE_FETCH_CONSENSUS:
  922. control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_STATUS, 0);
  923. break;
  924. case DIR_PURPOSE_FETCH_SERVERDESC:
  925. control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_DESCRIPTORS,
  926. count_loading_descriptors_progress());
  927. break;
  928. }
  929. }
  930. /* This is definitely a success, so forget about any pending data we
  931. * had sent. */
  932. if (entry_conn->pending_optimistic_data) {
  933. generic_buffer_free(entry_conn->pending_optimistic_data);
  934. entry_conn->pending_optimistic_data = NULL;
  935. }
  936. /* handle anything that might have queued */
  937. if (connection_edge_package_raw_inbuf(conn, 1, NULL) < 0) {
  938. /* (We already sent an end cell if possible) */
  939. connection_mark_for_close(TO_CONN(conn));
  940. return 0;
  941. }
  942. return 0;
  943. }
  944. if (conn->base_.type == CONN_TYPE_AP &&
  945. rh->command == RELAY_COMMAND_RESOLVED) {
  946. int ttl;
  947. int answer_len;
  948. uint8_t answer_type;
  949. entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
  950. if (conn->base_.state != AP_CONN_STATE_RESOLVE_WAIT) {
  951. log_fn(LOG_PROTOCOL_WARN, LD_APP, "Got a 'resolved' cell while "
  952. "not in state resolve_wait. Dropping.");
  953. return 0;
  954. }
  955. tor_assert(SOCKS_COMMAND_IS_RESOLVE(entry_conn->socks_request->command));
  956. answer_len = cell->payload[RELAY_HEADER_SIZE+1];
  957. if (rh->length < 2 || answer_len+2>rh->length) {
  958. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  959. "Dropping malformed 'resolved' cell");
  960. connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TORPROTOCOL);
  961. return 0;
  962. }
  963. answer_type = cell->payload[RELAY_HEADER_SIZE];
  964. if (rh->length >= answer_len+6)
  965. ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+
  966. 2+answer_len));
  967. else
  968. ttl = -1;
  969. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  970. uint32_t addr = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+2));
  971. if (get_options()->ClientDNSRejectInternalAddresses &&
  972. is_internal_IP(addr, 0)) {
  973. log_info(LD_APP,"Got a resolve with answer %s. Rejecting.",
  974. fmt_addr32(addr));
  975. connection_ap_handshake_socks_resolved(entry_conn,
  976. RESOLVED_TYPE_ERROR_TRANSIENT,
  977. 0, NULL, 0, TIME_MAX);
  978. connection_mark_unattached_ap(entry_conn,
  979. END_STREAM_REASON_TORPROTOCOL);
  980. return 0;
  981. }
  982. }
  983. connection_ap_handshake_socks_resolved(entry_conn,
  984. answer_type,
  985. cell->payload[RELAY_HEADER_SIZE+1], /*answer_len*/
  986. cell->payload+RELAY_HEADER_SIZE+2, /*answer*/
  987. ttl,
  988. -1);
  989. if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
  990. tor_addr_t addr;
  991. tor_addr_from_ipv4n(&addr,
  992. get_uint32(cell->payload+RELAY_HEADER_SIZE+2));
  993. remap_event_helper(entry_conn, &addr);
  994. } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
  995. tor_addr_t addr;
  996. tor_addr_from_ipv6_bytes(&addr,
  997. (char*)(cell->payload+RELAY_HEADER_SIZE+2));
  998. remap_event_helper(entry_conn, &addr);
  999. }
  1000. connection_mark_unattached_ap(entry_conn,
  1001. END_STREAM_REASON_DONE |
  1002. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  1003. return 0;
  1004. }
  1005. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1006. "Got an unexpected relay command %d, in state %d (%s). Dropping.",
  1007. rh->command, conn->base_.state,
  1008. conn_state_to_string(conn->base_.type, conn->base_.state));
  1009. return 0; /* for forward compatibility, don't kill the circuit */
  1010. // connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
  1011. // connection_mark_for_close(conn);
  1012. // return -1;
  1013. }
  1014. /** An incoming relay cell has arrived on circuit <b>circ</b>. If
  1015. * <b>conn</b> is NULL this is a control cell, else <b>cell</b> is
  1016. * destined for <b>conn</b>.
  1017. *
  1018. * If <b>layer_hint</b> is defined, then we're the origin of the
  1019. * circuit, and it specifies the hop that packaged <b>cell</b>.
  1020. *
  1021. * Return -reason if you want to warn and tear down the circuit, else 0.
  1022. */
  1023. static int
  1024. connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
  1025. edge_connection_t *conn,
  1026. crypt_path_t *layer_hint)
  1027. {
  1028. static int num_seen=0;
  1029. relay_header_t rh;
  1030. unsigned domain = layer_hint?LD_APP:LD_EXIT;
  1031. int reason;
  1032. int optimistic_data = 0; /* Set to 1 if we receive data on a stream
  1033. * that's in the EXIT_CONN_STATE_RESOLVING
  1034. * or EXIT_CONN_STATE_CONNECTING states. */
  1035. tor_assert(cell);
  1036. tor_assert(circ);
  1037. relay_header_unpack(&rh, cell->payload);
  1038. // log_fn(LOG_DEBUG,"command %d stream %d", rh.command, rh.stream_id);
  1039. num_seen++;
  1040. log_debug(domain, "Now seen %d relay cells here (command %d, stream %d).",
  1041. num_seen, rh.command, rh.stream_id);
  1042. if (rh.length > RELAY_PAYLOAD_SIZE) {
  1043. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1044. "Relay cell length field too long. Closing circuit.");
  1045. return - END_CIRC_REASON_TORPROTOCOL;
  1046. }
  1047. /* either conn is NULL, in which case we've got a control cell, or else
  1048. * conn points to the recognized stream. */
  1049. if (conn && !connection_state_is_open(TO_CONN(conn))) {
  1050. if (conn->base_.type == CONN_TYPE_EXIT &&
  1051. (conn->base_.state == EXIT_CONN_STATE_CONNECTING ||
  1052. conn->base_.state == EXIT_CONN_STATE_RESOLVING) &&
  1053. rh.command == RELAY_COMMAND_DATA) {
  1054. /* Allow DATA cells to be delivered to an exit node in state
  1055. * EXIT_CONN_STATE_CONNECTING or EXIT_CONN_STATE_RESOLVING.
  1056. * This speeds up HTTP, for example. */
  1057. optimistic_data = 1;
  1058. } else {
  1059. return connection_edge_process_relay_cell_not_open(
  1060. &rh, cell, circ, conn, layer_hint);
  1061. }
  1062. }
  1063. switch (rh.command) {
  1064. case RELAY_COMMAND_DROP:
  1065. // log_info(domain,"Got a relay-level padding cell. Dropping.");
  1066. return 0;
  1067. case RELAY_COMMAND_BEGIN:
  1068. case RELAY_COMMAND_BEGIN_DIR:
  1069. if (layer_hint &&
  1070. circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
  1071. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  1072. "Relay begin request unsupported at AP. Dropping.");
  1073. return 0;
  1074. }
  1075. if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED &&
  1076. layer_hint != TO_ORIGIN_CIRCUIT(circ)->cpath->prev) {
  1077. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  1078. "Relay begin request to Hidden Service "
  1079. "from intermediary node. Dropping.");
  1080. return 0;
  1081. }
  1082. if (conn) {
  1083. log_fn(LOG_PROTOCOL_WARN, domain,
  1084. "Begin cell for known stream. Dropping.");
  1085. return 0;
  1086. }
  1087. if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
  1088. /* Assign this circuit and its app-ward OR connection a unique ID,
  1089. * so that we can measure download times. The local edge and dir
  1090. * connection will be assigned the same ID when they are created
  1091. * and linked. */
  1092. static uint64_t next_id = 0;
  1093. circ->dirreq_id = ++next_id;
  1094. TO_OR_CIRCUIT(circ)->p_chan->dirreq_id = circ->dirreq_id;
  1095. }
  1096. return connection_exit_begin_conn(cell, circ);
  1097. case RELAY_COMMAND_DATA:
  1098. ++stats_n_data_cells_received;
  1099. if (( layer_hint && --layer_hint->deliver_window < 0) ||
  1100. (!layer_hint && --circ->deliver_window < 0)) {
  1101. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1102. "(relay data) circ deliver_window below 0. Killing.");
  1103. if (conn) {
  1104. /* XXXX Do we actually need to do this? Will killing the circuit
  1105. * not send an END and mark the stream for close as appropriate? */
  1106. connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
  1107. connection_mark_for_close(TO_CONN(conn));
  1108. }
  1109. return -END_CIRC_REASON_TORPROTOCOL;
  1110. }
  1111. log_debug(domain,"circ deliver_window now %d.", layer_hint ?
  1112. layer_hint->deliver_window : circ->deliver_window);
  1113. circuit_consider_sending_sendme(circ, layer_hint);
  1114. if (!conn) {
  1115. log_info(domain,"data cell dropped, unknown stream (streamid %d).",
  1116. rh.stream_id);
  1117. return 0;
  1118. }
  1119. if (--conn->deliver_window < 0) { /* is it below 0 after decrement? */
  1120. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1121. "(relay data) conn deliver_window below 0. Killing.");
  1122. return -END_CIRC_REASON_TORPROTOCOL;
  1123. }
  1124. stats_n_data_bytes_received += rh.length;
  1125. connection_write_to_buf((char*)(cell->payload + RELAY_HEADER_SIZE),
  1126. rh.length, TO_CONN(conn));
  1127. if (!optimistic_data) {
  1128. /* Only send a SENDME if we're not getting optimistic data; otherwise
  1129. * a SENDME could arrive before the CONNECTED.
  1130. */
  1131. connection_edge_consider_sending_sendme(conn);
  1132. }
  1133. return 0;
  1134. case RELAY_COMMAND_END:
  1135. reason = rh.length > 0 ?
  1136. get_uint8(cell->payload+RELAY_HEADER_SIZE) : END_STREAM_REASON_MISC;
  1137. if (!conn) {
  1138. log_info(domain,"end cell (%s) dropped, unknown stream.",
  1139. stream_end_reason_to_string(reason));
  1140. return 0;
  1141. }
  1142. /* XXX add to this log_fn the exit node's nickname? */
  1143. log_info(domain,"%d: end cell (%s) for stream %d. Removing stream.",
  1144. conn->base_.s,
  1145. stream_end_reason_to_string(reason),
  1146. conn->stream_id);
  1147. if (conn->base_.type == CONN_TYPE_AP) {
  1148. entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
  1149. if (entry_conn->socks_request &&
  1150. !entry_conn->socks_request->has_finished)
  1151. log_warn(LD_BUG,
  1152. "open stream hasn't sent socks answer yet? Closing.");
  1153. }
  1154. /* We just *got* an end; no reason to send one. */
  1155. conn->edge_has_sent_end = 1;
  1156. if (!conn->end_reason)
  1157. conn->end_reason = reason | END_STREAM_REASON_FLAG_REMOTE;
  1158. if (!conn->base_.marked_for_close) {
  1159. /* only mark it if not already marked. it's possible to
  1160. * get the 'end' right around when the client hangs up on us. */
  1161. connection_mark_and_flush(TO_CONN(conn));
  1162. }
  1163. return 0;
  1164. case RELAY_COMMAND_EXTEND: {
  1165. static uint64_t total_n_extend=0, total_nonearly=0;
  1166. total_n_extend++;
  1167. if (rh.stream_id) {
  1168. log_fn(LOG_PROTOCOL_WARN, domain,
  1169. "'extend' cell received for non-zero stream. Dropping.");
  1170. return 0;
  1171. }
  1172. if (cell->command != CELL_RELAY_EARLY &&
  1173. !networkstatus_get_param(NULL,"AllowNonearlyExtend",0,0,1)) {
  1174. #define EARLY_WARNING_INTERVAL 3600
  1175. static ratelim_t early_warning_limit =
  1176. RATELIM_INIT(EARLY_WARNING_INTERVAL);
  1177. char *m;
  1178. if (cell->command == CELL_RELAY) {
  1179. ++total_nonearly;
  1180. if ((m = rate_limit_log(&early_warning_limit, approx_time()))) {
  1181. double percentage = ((double)total_nonearly)/total_n_extend;
  1182. percentage *= 100;
  1183. log_fn(LOG_PROTOCOL_WARN, domain, "EXTEND cell received, "
  1184. "but not via RELAY_EARLY. Dropping.%s", m);
  1185. log_fn(LOG_PROTOCOL_WARN, domain, " (We have dropped %.02f%% of "
  1186. "all EXTEND cells for this reason)", percentage);
  1187. tor_free(m);
  1188. }
  1189. } else {
  1190. log_fn(LOG_WARN, domain,
  1191. "EXTEND cell received, in a cell with type %d! Dropping.",
  1192. cell->command);
  1193. }
  1194. return 0;
  1195. }
  1196. return circuit_extend(cell, circ);
  1197. }
  1198. case RELAY_COMMAND_EXTENDED:
  1199. if (!layer_hint) {
  1200. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1201. "'extended' unsupported at non-origin. Dropping.");
  1202. return 0;
  1203. }
  1204. log_debug(domain,"Got an extended cell! Yay.");
  1205. {
  1206. extended_cell_t extended_cell;
  1207. if (extended_cell_parse(&extended_cell, rh.command,
  1208. (const uint8_t*)cell->payload+RELAY_HEADER_SIZE,
  1209. rh.length)<0) {
  1210. log_warn(LD_PROTOCOL,
  1211. "Can't parse EXTENDED cell; killing circuit.");
  1212. return -END_CIRC_REASON_TORPROTOCOL;
  1213. }
  1214. if ((reason = circuit_finish_handshake(TO_ORIGIN_CIRCUIT(circ),
  1215. &extended_cell.created_cell)) < 0) {
  1216. log_warn(domain,"circuit_finish_handshake failed.");
  1217. return reason;
  1218. }
  1219. }
  1220. if ((reason=circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ)))<0) {
  1221. log_info(domain,"circuit_send_next_onion_skin() failed.");
  1222. return reason;
  1223. }
  1224. return 0;
  1225. case RELAY_COMMAND_TRUNCATE:
  1226. if (layer_hint) {
  1227. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  1228. "'truncate' unsupported at origin. Dropping.");
  1229. return 0;
  1230. }
  1231. if (circ->n_chan) {
  1232. uint8_t trunc_reason = get_uint8(cell->payload + RELAY_HEADER_SIZE);
  1233. circuit_clear_cell_queue(circ, circ->n_chan);
  1234. channel_send_destroy(circ->n_circ_id, circ->n_chan,
  1235. trunc_reason);
  1236. circuit_set_n_circid_chan(circ, 0, NULL);
  1237. }
  1238. log_debug(LD_EXIT, "Processed 'truncate', replying.");
  1239. {
  1240. char payload[1];
  1241. payload[0] = (char)END_CIRC_REASON_REQUESTED;
  1242. relay_send_command_from_edge(0, circ, RELAY_COMMAND_TRUNCATED,
  1243. payload, sizeof(payload), NULL);
  1244. }
  1245. return 0;
  1246. case RELAY_COMMAND_TRUNCATED:
  1247. if (!layer_hint) {
  1248. log_fn(LOG_PROTOCOL_WARN, LD_EXIT,
  1249. "'truncated' unsupported at non-origin. Dropping.");
  1250. return 0;
  1251. }
  1252. circuit_truncated(TO_ORIGIN_CIRCUIT(circ), layer_hint,
  1253. get_uint8(cell->payload + RELAY_HEADER_SIZE));
  1254. return 0;
  1255. case RELAY_COMMAND_CONNECTED:
  1256. if (conn) {
  1257. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1258. "'connected' unsupported while open. Closing circ.");
  1259. return -END_CIRC_REASON_TORPROTOCOL;
  1260. }
  1261. log_info(domain,
  1262. "'connected' received, no conn attached anymore. Ignoring.");
  1263. return 0;
  1264. case RELAY_COMMAND_SENDME:
  1265. if (!rh.stream_id) {
  1266. if (layer_hint) {
  1267. if (layer_hint->package_window + CIRCWINDOW_INCREMENT >
  1268. CIRCWINDOW_START_MAX) {
  1269. /*XXXX024: Downgrade this back to LOG_PROTOCOL_WARN after a while*/
  1270. log_fn(LOG_WARN, LD_PROTOCOL,
  1271. "Bug/attack: unexpected sendme cell from exit relay. "
  1272. "Closing circ.");
  1273. return -END_CIRC_REASON_TORPROTOCOL;
  1274. }
  1275. layer_hint->package_window += CIRCWINDOW_INCREMENT;
  1276. log_debug(LD_APP,"circ-level sendme at origin, packagewindow %d.",
  1277. layer_hint->package_window);
  1278. circuit_resume_edge_reading(circ, layer_hint);
  1279. } else {
  1280. if (circ->package_window + CIRCWINDOW_INCREMENT >
  1281. CIRCWINDOW_START_MAX) {
  1282. /*XXXX024: Downgrade this back to LOG_PROTOCOL_WARN after a while*/
  1283. log_fn(LOG_WARN, LD_PROTOCOL,
  1284. "Bug/attack: unexpected sendme cell from client. "
  1285. "Closing circ.");
  1286. return -END_CIRC_REASON_TORPROTOCOL;
  1287. }
  1288. circ->package_window += CIRCWINDOW_INCREMENT;
  1289. log_debug(LD_APP,
  1290. "circ-level sendme at non-origin, packagewindow %d.",
  1291. circ->package_window);
  1292. circuit_resume_edge_reading(circ, layer_hint);
  1293. }
  1294. return 0;
  1295. }
  1296. if (!conn) {
  1297. log_info(domain,"sendme cell dropped, unknown stream (streamid %d).",
  1298. rh.stream_id);
  1299. return 0;
  1300. }
  1301. conn->package_window += STREAMWINDOW_INCREMENT;
  1302. log_debug(domain,"stream-level sendme, packagewindow now %d.",
  1303. conn->package_window);
  1304. if (circuit_queue_streams_are_blocked(circ)) {
  1305. /* Still waiting for queue to flush; don't touch conn */
  1306. return 0;
  1307. }
  1308. connection_start_reading(TO_CONN(conn));
  1309. /* handle whatever might still be on the inbuf */
  1310. if (connection_edge_package_raw_inbuf(conn, 1, NULL) < 0) {
  1311. /* (We already sent an end cell if possible) */
  1312. connection_mark_for_close(TO_CONN(conn));
  1313. return 0;
  1314. }
  1315. return 0;
  1316. case RELAY_COMMAND_RESOLVE:
  1317. if (layer_hint) {
  1318. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  1319. "resolve request unsupported at AP; dropping.");
  1320. return 0;
  1321. } else if (conn) {
  1322. log_fn(LOG_PROTOCOL_WARN, domain,
  1323. "resolve request for known stream; dropping.");
  1324. return 0;
  1325. } else if (circ->purpose != CIRCUIT_PURPOSE_OR) {
  1326. log_fn(LOG_PROTOCOL_WARN, domain,
  1327. "resolve request on circ with purpose %d; dropping",
  1328. circ->purpose);
  1329. return 0;
  1330. }
  1331. connection_exit_begin_resolve(cell, TO_OR_CIRCUIT(circ));
  1332. return 0;
  1333. case RELAY_COMMAND_RESOLVED:
  1334. if (conn) {
  1335. log_fn(LOG_PROTOCOL_WARN, domain,
  1336. "'resolved' unsupported while open. Closing circ.");
  1337. return -END_CIRC_REASON_TORPROTOCOL;
  1338. }
  1339. log_info(domain,
  1340. "'resolved' received, no conn attached anymore. Ignoring.");
  1341. return 0;
  1342. case RELAY_COMMAND_ESTABLISH_INTRO:
  1343. case RELAY_COMMAND_ESTABLISH_RENDEZVOUS:
  1344. case RELAY_COMMAND_INTRODUCE1:
  1345. case RELAY_COMMAND_INTRODUCE2:
  1346. case RELAY_COMMAND_INTRODUCE_ACK:
  1347. case RELAY_COMMAND_RENDEZVOUS1:
  1348. case RELAY_COMMAND_RENDEZVOUS2:
  1349. case RELAY_COMMAND_INTRO_ESTABLISHED:
  1350. case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
  1351. rend_process_relay_cell(circ, layer_hint,
  1352. rh.command, rh.length,
  1353. cell->payload+RELAY_HEADER_SIZE);
  1354. return 0;
  1355. }
  1356. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1357. "Received unknown relay command %d. Perhaps the other side is using "
  1358. "a newer version of Tor? Dropping.",
  1359. rh.command);
  1360. return 0; /* for forward compatibility, don't kill the circuit */
  1361. }
  1362. /** How many relay_data cells have we built, ever? */
  1363. uint64_t stats_n_data_cells_packaged = 0;
  1364. /** How many bytes of data have we put in relay_data cells have we built,
  1365. * ever? This would be RELAY_PAYLOAD_SIZE*stats_n_data_cells_packaged if
  1366. * every relay cell we ever sent were completely full of data. */
  1367. uint64_t stats_n_data_bytes_packaged = 0;
  1368. /** How many relay_data cells have we received, ever? */
  1369. uint64_t stats_n_data_cells_received = 0;
  1370. /** How many bytes of data have we received relay_data cells, ever? This would
  1371. * be RELAY_PAYLOAD_SIZE*stats_n_data_cells_packaged if every relay cell we
  1372. * ever received were completely full of data. */
  1373. uint64_t stats_n_data_bytes_received = 0;
  1374. /** If <b>conn</b> has an entire relay payload of bytes on its inbuf (or
  1375. * <b>package_partial</b> is true), and the appropriate package windows aren't
  1376. * empty, grab a cell and send it down the circuit.
  1377. *
  1378. * If *<b>max_cells</b> is given, package no more than max_cells. Decrement
  1379. * *<b>max_cells</b> by the number of cells packaged.
  1380. *
  1381. * Return -1 (and send a RELAY_COMMAND_END cell if necessary) if conn should
  1382. * be marked for close, else return 0.
  1383. */
  1384. int
  1385. connection_edge_package_raw_inbuf(edge_connection_t *conn, int package_partial,
  1386. int *max_cells)
  1387. {
  1388. size_t bytes_to_process, length;
  1389. char payload[CELL_PAYLOAD_SIZE];
  1390. circuit_t *circ;
  1391. const unsigned domain = conn->base_.type == CONN_TYPE_AP ? LD_APP : LD_EXIT;
  1392. int sending_from_optimistic = 0;
  1393. const int sending_optimistically =
  1394. conn->base_.type == CONN_TYPE_AP &&
  1395. conn->base_.state != AP_CONN_STATE_OPEN;
  1396. entry_connection_t *entry_conn =
  1397. conn->base_.type == CONN_TYPE_AP ? EDGE_TO_ENTRY_CONN(conn) : NULL;
  1398. crypt_path_t *cpath_layer = conn->cpath_layer;
  1399. tor_assert(conn);
  1400. if (conn->base_.marked_for_close) {
  1401. log_warn(LD_BUG,
  1402. "called on conn that's already marked for close at %s:%d.",
  1403. conn->base_.marked_for_close_file, conn->base_.marked_for_close);
  1404. return 0;
  1405. }
  1406. if (max_cells && *max_cells <= 0)
  1407. return 0;
  1408. repeat_connection_edge_package_raw_inbuf:
  1409. circ = circuit_get_by_edge_conn(conn);
  1410. if (!circ) {
  1411. log_info(domain,"conn has no circuit! Closing.");
  1412. conn->end_reason = END_STREAM_REASON_CANT_ATTACH;
  1413. return -1;
  1414. }
  1415. if (circuit_consider_stop_edge_reading(circ, cpath_layer))
  1416. return 0;
  1417. if (conn->package_window <= 0) {
  1418. log_info(domain,"called with package_window %d. Skipping.",
  1419. conn->package_window);
  1420. connection_stop_reading(TO_CONN(conn));
  1421. return 0;
  1422. }
  1423. sending_from_optimistic = entry_conn &&
  1424. entry_conn->sending_optimistic_data != NULL;
  1425. if (PREDICT_UNLIKELY(sending_from_optimistic)) {
  1426. bytes_to_process = generic_buffer_len(entry_conn->sending_optimistic_data);
  1427. if (PREDICT_UNLIKELY(!bytes_to_process)) {
  1428. log_warn(LD_BUG, "sending_optimistic_data was non-NULL but empty");
  1429. bytes_to_process = connection_get_inbuf_len(TO_CONN(conn));
  1430. sending_from_optimistic = 0;
  1431. }
  1432. } else {
  1433. bytes_to_process = connection_get_inbuf_len(TO_CONN(conn));
  1434. }
  1435. if (!bytes_to_process)
  1436. return 0;
  1437. if (!package_partial && bytes_to_process < RELAY_PAYLOAD_SIZE)
  1438. return 0;
  1439. if (bytes_to_process > RELAY_PAYLOAD_SIZE) {
  1440. length = RELAY_PAYLOAD_SIZE;
  1441. } else {
  1442. length = bytes_to_process;
  1443. }
  1444. stats_n_data_bytes_packaged += length;
  1445. stats_n_data_cells_packaged += 1;
  1446. if (PREDICT_UNLIKELY(sending_from_optimistic)) {
  1447. /* XXXX We could be more efficient here by sometimes packing
  1448. * previously-sent optimistic data in the same cell with data
  1449. * from the inbuf. */
  1450. generic_buffer_get(entry_conn->sending_optimistic_data, payload, length);
  1451. if (!generic_buffer_len(entry_conn->sending_optimistic_data)) {
  1452. generic_buffer_free(entry_conn->sending_optimistic_data);
  1453. entry_conn->sending_optimistic_data = NULL;
  1454. }
  1455. } else {
  1456. connection_fetch_from_buf(payload, length, TO_CONN(conn));
  1457. }
  1458. log_debug(domain,"(%d) Packaging %d bytes (%d waiting).", conn->base_.s,
  1459. (int)length, (int)connection_get_inbuf_len(TO_CONN(conn)));
  1460. if (sending_optimistically && !sending_from_optimistic) {
  1461. /* This is new optimistic data; remember it in case we need to detach and
  1462. retry */
  1463. if (!entry_conn->pending_optimistic_data)
  1464. entry_conn->pending_optimistic_data = generic_buffer_new();
  1465. generic_buffer_add(entry_conn->pending_optimistic_data, payload, length);
  1466. }
  1467. if (connection_edge_send_command(conn, RELAY_COMMAND_DATA,
  1468. payload, length) < 0 )
  1469. /* circuit got marked for close, don't continue, don't need to mark conn */
  1470. return 0;
  1471. if (!cpath_layer) { /* non-rendezvous exit */
  1472. tor_assert(circ->package_window > 0);
  1473. circ->package_window--;
  1474. } else { /* we're an AP, or an exit on a rendezvous circ */
  1475. tor_assert(cpath_layer->package_window > 0);
  1476. cpath_layer->package_window--;
  1477. }
  1478. if (--conn->package_window <= 0) { /* is it 0 after decrement? */
  1479. connection_stop_reading(TO_CONN(conn));
  1480. log_debug(domain,"conn->package_window reached 0.");
  1481. circuit_consider_stop_edge_reading(circ, cpath_layer);
  1482. return 0; /* don't process the inbuf any more */
  1483. }
  1484. log_debug(domain,"conn->package_window is now %d",conn->package_window);
  1485. if (max_cells) {
  1486. *max_cells -= 1;
  1487. if (*max_cells <= 0)
  1488. return 0;
  1489. }
  1490. /* handle more if there's more, or return 0 if there isn't */
  1491. goto repeat_connection_edge_package_raw_inbuf;
  1492. }
  1493. /** Called when we've just received a relay data cell, when
  1494. * we've just finished flushing all bytes to stream <b>conn</b>,
  1495. * or when we've flushed *some* bytes to the stream <b>conn</b>.
  1496. *
  1497. * If conn->outbuf is not too full, and our deliver window is
  1498. * low, send back a suitable number of stream-level sendme cells.
  1499. */
  1500. void
  1501. connection_edge_consider_sending_sendme(edge_connection_t *conn)
  1502. {
  1503. circuit_t *circ;
  1504. if (connection_outbuf_too_full(TO_CONN(conn)))
  1505. return;
  1506. circ = circuit_get_by_edge_conn(conn);
  1507. if (!circ) {
  1508. /* this can legitimately happen if the destroy has already
  1509. * arrived and torn down the circuit */
  1510. log_info(LD_APP,"No circuit associated with conn. Skipping.");
  1511. return;
  1512. }
  1513. while (conn->deliver_window <= STREAMWINDOW_START - STREAMWINDOW_INCREMENT) {
  1514. log_debug(conn->base_.type == CONN_TYPE_AP ?LD_APP:LD_EXIT,
  1515. "Outbuf %d, Queuing stream sendme.",
  1516. (int)conn->base_.outbuf_flushlen);
  1517. conn->deliver_window += STREAMWINDOW_INCREMENT;
  1518. if (connection_edge_send_command(conn, RELAY_COMMAND_SENDME,
  1519. NULL, 0) < 0) {
  1520. log_warn(LD_APP,"connection_edge_send_command failed. Skipping.");
  1521. return; /* the circuit's closed, don't continue */
  1522. }
  1523. }
  1524. }
  1525. /** The circuit <b>circ</b> has received a circuit-level sendme
  1526. * (on hop <b>layer_hint</b>, if we're the OP). Go through all the
  1527. * attached streams and let them resume reading and packaging, if
  1528. * their stream windows allow it.
  1529. */
  1530. static void
  1531. circuit_resume_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
  1532. {
  1533. if (circuit_queue_streams_are_blocked(circ)) {
  1534. log_debug(layer_hint?LD_APP:LD_EXIT,"Too big queue, no resuming");
  1535. return;
  1536. }
  1537. log_debug(layer_hint?LD_APP:LD_EXIT,"resuming");
  1538. if (CIRCUIT_IS_ORIGIN(circ))
  1539. circuit_resume_edge_reading_helper(TO_ORIGIN_CIRCUIT(circ)->p_streams,
  1540. circ, layer_hint);
  1541. else
  1542. circuit_resume_edge_reading_helper(TO_OR_CIRCUIT(circ)->n_streams,
  1543. circ, layer_hint);
  1544. }
  1545. /** A helper function for circuit_resume_edge_reading() above.
  1546. * The arguments are the same, except that <b>conn</b> is the head
  1547. * of a linked list of edge streams that should each be considered.
  1548. */
  1549. static int
  1550. circuit_resume_edge_reading_helper(edge_connection_t *first_conn,
  1551. circuit_t *circ,
  1552. crypt_path_t *layer_hint)
  1553. {
  1554. edge_connection_t *conn;
  1555. int n_packaging_streams, n_streams_left;
  1556. int packaged_this_round;
  1557. int cells_on_queue;
  1558. int cells_per_conn;
  1559. edge_connection_t *chosen_stream = NULL;
  1560. /* How many cells do we have space for? It will be the minimum of
  1561. * the number needed to exhaust the package window, and the minimum
  1562. * needed to fill the cell queue. */
  1563. int max_to_package = circ->package_window;
  1564. if (CIRCUIT_IS_ORIGIN(circ)) {
  1565. cells_on_queue = circ->n_chan_cells.n;
  1566. } else {
  1567. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  1568. cells_on_queue = or_circ->p_chan_cells.n;
  1569. }
  1570. if (CELL_QUEUE_HIGHWATER_SIZE - cells_on_queue < max_to_package)
  1571. max_to_package = CELL_QUEUE_HIGHWATER_SIZE - cells_on_queue;
  1572. /* Once we used to start listening on the streams in the order they
  1573. * appeared in the linked list. That leads to starvation on the
  1574. * streams that appeared later on the list, since the first streams
  1575. * would always get to read first. Instead, we just pick a random
  1576. * stream on the list, and enable reading for streams starting at that
  1577. * point (and wrapping around as if the list were circular). It would
  1578. * probably be better to actually remember which streams we've
  1579. * serviced in the past, but this is simple and effective. */
  1580. /* Select a stream uniformly at random from the linked list. We
  1581. * don't need cryptographic randomness here. */
  1582. {
  1583. int num_streams = 0;
  1584. for (conn = first_conn; conn; conn = conn->next_stream) {
  1585. num_streams++;
  1586. if ((tor_weak_random() % num_streams)==0)
  1587. chosen_stream = conn;
  1588. /* Invariant: chosen_stream has been chosen uniformly at random from
  1589. * among the first num_streams streams on first_conn. */
  1590. }
  1591. }
  1592. /* Count how many non-marked streams there are that have anything on
  1593. * their inbuf, and enable reading on all of the connections. */
  1594. n_packaging_streams = 0;
  1595. /* Activate reading starting from the chosen stream */
  1596. for (conn=chosen_stream; conn; conn = conn->next_stream) {
  1597. /* Start reading for the streams starting from here */
  1598. if (conn->base_.marked_for_close || conn->package_window <= 0)
  1599. continue;
  1600. if (!layer_hint || conn->cpath_layer == layer_hint) {
  1601. connection_start_reading(TO_CONN(conn));
  1602. if (connection_get_inbuf_len(TO_CONN(conn)) > 0)
  1603. ++n_packaging_streams;
  1604. }
  1605. }
  1606. /* Go back and do the ones we skipped, circular-style */
  1607. for (conn = first_conn; conn != chosen_stream; conn = conn->next_stream) {
  1608. if (conn->base_.marked_for_close || conn->package_window <= 0)
  1609. continue;
  1610. if (!layer_hint || conn->cpath_layer == layer_hint) {
  1611. connection_start_reading(TO_CONN(conn));
  1612. if (connection_get_inbuf_len(TO_CONN(conn)) > 0)
  1613. ++n_packaging_streams;
  1614. }
  1615. }
  1616. if (n_packaging_streams == 0) /* avoid divide-by-zero */
  1617. return 0;
  1618. again:
  1619. cells_per_conn = CEIL_DIV(max_to_package, n_packaging_streams);
  1620. packaged_this_round = 0;
  1621. n_streams_left = 0;
  1622. /* Iterate over all connections. Package up to cells_per_conn cells on
  1623. * each. Update packaged_this_round with the total number of cells
  1624. * packaged, and n_streams_left with the number that still have data to
  1625. * package.
  1626. */
  1627. for (conn=first_conn; conn; conn=conn->next_stream) {
  1628. if (conn->base_.marked_for_close || conn->package_window <= 0)
  1629. continue;
  1630. if (!layer_hint || conn->cpath_layer == layer_hint) {
  1631. int n = cells_per_conn, r;
  1632. /* handle whatever might still be on the inbuf */
  1633. r = connection_edge_package_raw_inbuf(conn, 1, &n);
  1634. /* Note how many we packaged */
  1635. packaged_this_round += (cells_per_conn-n);
  1636. if (r<0) {
  1637. /* Problem while packaging. (We already sent an end cell if
  1638. * possible) */
  1639. connection_mark_for_close(TO_CONN(conn));
  1640. continue;
  1641. }
  1642. /* If there's still data to read, we'll be coming back to this stream. */
  1643. if (connection_get_inbuf_len(TO_CONN(conn)))
  1644. ++n_streams_left;
  1645. /* If the circuit won't accept any more data, return without looking
  1646. * at any more of the streams. Any connections that should be stopped
  1647. * have already been stopped by connection_edge_package_raw_inbuf. */
  1648. if (circuit_consider_stop_edge_reading(circ, layer_hint))
  1649. return -1;
  1650. /* XXXX should we also stop immediately if we fill up the cell queue?
  1651. * Probably. */
  1652. }
  1653. }
  1654. /* If we made progress, and we are willing to package more, and there are
  1655. * any streams left that want to package stuff... try again!
  1656. */
  1657. if (packaged_this_round && packaged_this_round < max_to_package &&
  1658. n_streams_left) {
  1659. max_to_package -= packaged_this_round;
  1660. n_packaging_streams = n_streams_left;
  1661. goto again;
  1662. }
  1663. return 0;
  1664. }
  1665. /** Check if the package window for <b>circ</b> is empty (at
  1666. * hop <b>layer_hint</b> if it's defined).
  1667. *
  1668. * If yes, tell edge streams to stop reading and return 1.
  1669. * Else return 0.
  1670. */
  1671. static int
  1672. circuit_consider_stop_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
  1673. {
  1674. edge_connection_t *conn = NULL;
  1675. unsigned domain = layer_hint ? LD_APP : LD_EXIT;
  1676. if (!layer_hint) {
  1677. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  1678. log_debug(domain,"considering circ->package_window %d",
  1679. circ->package_window);
  1680. if (circ->package_window <= 0) {
  1681. log_debug(domain,"yes, not-at-origin. stopped.");
  1682. for (conn = or_circ->n_streams; conn; conn=conn->next_stream)
  1683. connection_stop_reading(TO_CONN(conn));
  1684. return 1;
  1685. }
  1686. return 0;
  1687. }
  1688. /* else, layer hint is defined, use it */
  1689. log_debug(domain,"considering layer_hint->package_window %d",
  1690. layer_hint->package_window);
  1691. if (layer_hint->package_window <= 0) {
  1692. log_debug(domain,"yes, at-origin. stopped.");
  1693. for (conn = TO_ORIGIN_CIRCUIT(circ)->p_streams; conn;
  1694. conn=conn->next_stream) {
  1695. if (conn->cpath_layer == layer_hint)
  1696. connection_stop_reading(TO_CONN(conn));
  1697. }
  1698. return 1;
  1699. }
  1700. return 0;
  1701. }
  1702. /** Check if the deliver_window for circuit <b>circ</b> (at hop
  1703. * <b>layer_hint</b> if it's defined) is low enough that we should
  1704. * send a circuit-level sendme back down the circuit. If so, send
  1705. * enough sendmes that the window would be overfull if we sent any
  1706. * more.
  1707. */
  1708. static void
  1709. circuit_consider_sending_sendme(circuit_t *circ, crypt_path_t *layer_hint)
  1710. {
  1711. // log_fn(LOG_INFO,"Considering: layer_hint is %s",
  1712. // layer_hint ? "defined" : "null");
  1713. while ((layer_hint ? layer_hint->deliver_window : circ->deliver_window) <=
  1714. CIRCWINDOW_START - CIRCWINDOW_INCREMENT) {
  1715. log_debug(LD_CIRC,"Queuing circuit sendme.");
  1716. if (layer_hint)
  1717. layer_hint->deliver_window += CIRCWINDOW_INCREMENT;
  1718. else
  1719. circ->deliver_window += CIRCWINDOW_INCREMENT;
  1720. if (relay_send_command_from_edge(0, circ, RELAY_COMMAND_SENDME,
  1721. NULL, 0, layer_hint) < 0) {
  1722. log_warn(LD_CIRC,
  1723. "relay_send_command_from_edge failed. Circuit's closed.");
  1724. return; /* the circuit's closed, don't continue */
  1725. }
  1726. }
  1727. }
  1728. #ifdef ACTIVE_CIRCUITS_PARANOIA
  1729. #define assert_cmux_ok_paranoid(chan) \
  1730. assert_circuit_mux_okay(chan)
  1731. #else
  1732. #define assert_cmux_ok_paranoid(chan)
  1733. #endif
  1734. /** The total number of cells we have allocated from the memory pool. */
  1735. static int total_cells_allocated = 0;
  1736. /** A memory pool to allocate packed_cell_t objects. */
  1737. static mp_pool_t *cell_pool = NULL;
  1738. /** Memory pool to allocate insertion_time_elem_t objects used for cell
  1739. * statistics. */
  1740. static mp_pool_t *it_pool = NULL;
  1741. /** Allocate structures to hold cells. */
  1742. void
  1743. init_cell_pool(void)
  1744. {
  1745. tor_assert(!cell_pool);
  1746. cell_pool = mp_pool_new(sizeof(packed_cell_t), 128*1024);
  1747. }
  1748. /** Free all storage used to hold cells (and insertion times if we measure
  1749. * cell statistics). */
  1750. void
  1751. free_cell_pool(void)
  1752. {
  1753. /* Maybe we haven't called init_cell_pool yet; need to check for it. */
  1754. if (cell_pool) {
  1755. mp_pool_destroy(cell_pool);
  1756. cell_pool = NULL;
  1757. }
  1758. if (it_pool) {
  1759. mp_pool_destroy(it_pool);
  1760. it_pool = NULL;
  1761. }
  1762. }
  1763. /** Free excess storage in cell pool. */
  1764. void
  1765. clean_cell_pool(void)
  1766. {
  1767. tor_assert(cell_pool);
  1768. mp_pool_clean(cell_pool, 0, 1);
  1769. }
  1770. /** Release storage held by <b>cell</b>. */
  1771. static INLINE void
  1772. packed_cell_free_unchecked(packed_cell_t *cell)
  1773. {
  1774. --total_cells_allocated;
  1775. mp_pool_release(cell);
  1776. }
  1777. /** Allocate and return a new packed_cell_t. */
  1778. static INLINE packed_cell_t *
  1779. packed_cell_new(void)
  1780. {
  1781. ++total_cells_allocated;
  1782. return mp_pool_get(cell_pool);
  1783. }
  1784. /** Return a packed cell used outside by channel_t lower layer */
  1785. void
  1786. packed_cell_free(packed_cell_t *cell)
  1787. {
  1788. packed_cell_free_unchecked(cell);
  1789. }
  1790. /** Log current statistics for cell pool allocation at log level
  1791. * <b>severity</b>. */
  1792. void
  1793. dump_cell_pool_usage(int severity)
  1794. {
  1795. circuit_t *c;
  1796. int n_circs = 0;
  1797. int n_cells = 0;
  1798. for (c = circuit_get_global_list_(); c; c = c->next) {
  1799. n_cells += c->n_chan_cells.n;
  1800. if (!CIRCUIT_IS_ORIGIN(c))
  1801. n_cells += TO_OR_CIRCUIT(c)->p_chan_cells.n;
  1802. ++n_circs;
  1803. }
  1804. log(severity, LD_MM, "%d cells allocated on %d circuits. %d cells leaked.",
  1805. n_cells, n_circs, total_cells_allocated - n_cells);
  1806. mp_pool_log_status(cell_pool, severity);
  1807. }
  1808. /** Allocate a new copy of packed <b>cell</b>. */
  1809. static INLINE packed_cell_t *
  1810. packed_cell_copy(const cell_t *cell)
  1811. {
  1812. packed_cell_t *c = packed_cell_new();
  1813. cell_pack(c, cell);
  1814. c->next = NULL;
  1815. return c;
  1816. }
  1817. /** Append <b>cell</b> to the end of <b>queue</b>. */
  1818. void
  1819. cell_queue_append(cell_queue_t *queue, packed_cell_t *cell)
  1820. {
  1821. if (queue->tail) {
  1822. tor_assert(!queue->tail->next);
  1823. queue->tail->next = cell;
  1824. } else {
  1825. queue->head = cell;
  1826. }
  1827. queue->tail = cell;
  1828. cell->next = NULL;
  1829. ++queue->n;
  1830. }
  1831. /** Append a newly allocated copy of <b>cell</b> to the end of <b>queue</b> */
  1832. void
  1833. cell_queue_append_packed_copy(cell_queue_t *queue, const cell_t *cell)
  1834. {
  1835. packed_cell_t *copy = packed_cell_copy(cell);
  1836. /* Remember the time when this cell was put in the queue. */
  1837. if (get_options()->CellStatistics) {
  1838. struct timeval now;
  1839. uint32_t added;
  1840. insertion_time_queue_t *it_queue = queue->insertion_times;
  1841. if (!it_pool)
  1842. it_pool = mp_pool_new(sizeof(insertion_time_elem_t), 1024);
  1843. tor_gettimeofday_cached(&now);
  1844. #define SECONDS_IN_A_DAY 86400L
  1845. added = (uint32_t)(((now.tv_sec % SECONDS_IN_A_DAY) * 100L)
  1846. + ((uint32_t)now.tv_usec / (uint32_t)10000L));
  1847. if (!it_queue) {
  1848. it_queue = tor_malloc_zero(sizeof(insertion_time_queue_t));
  1849. queue->insertion_times = it_queue;
  1850. }
  1851. if (it_queue->last && it_queue->last->insertion_time == added) {
  1852. it_queue->last->counter++;
  1853. } else {
  1854. insertion_time_elem_t *elem = mp_pool_get(it_pool);
  1855. elem->next = NULL;
  1856. elem->insertion_time = added;
  1857. elem->counter = 1;
  1858. if (it_queue->last) {
  1859. it_queue->last->next = elem;
  1860. it_queue->last = elem;
  1861. } else {
  1862. it_queue->first = it_queue->last = elem;
  1863. }
  1864. }
  1865. }
  1866. cell_queue_append(queue, copy);
  1867. }
  1868. /** Remove and free every cell in <b>queue</b>. */
  1869. void
  1870. cell_queue_clear(cell_queue_t *queue)
  1871. {
  1872. packed_cell_t *cell, *next;
  1873. cell = queue->head;
  1874. while (cell) {
  1875. next = cell->next;
  1876. packed_cell_free_unchecked(cell);
  1877. cell = next;
  1878. }
  1879. queue->head = queue->tail = NULL;
  1880. queue->n = 0;
  1881. if (queue->insertion_times) {
  1882. while (queue->insertion_times->first) {
  1883. insertion_time_elem_t *elem = queue->insertion_times->first;
  1884. queue->insertion_times->first = elem->next;
  1885. mp_pool_release(elem);
  1886. }
  1887. tor_free(queue->insertion_times);
  1888. }
  1889. }
  1890. /** Extract and return the cell at the head of <b>queue</b>; return NULL if
  1891. * <b>queue</b> is empty. */
  1892. static INLINE packed_cell_t *
  1893. cell_queue_pop(cell_queue_t *queue)
  1894. {
  1895. packed_cell_t *cell = queue->head;
  1896. if (!cell)
  1897. return NULL;
  1898. queue->head = cell->next;
  1899. if (cell == queue->tail) {
  1900. tor_assert(!queue->head);
  1901. queue->tail = NULL;
  1902. }
  1903. --queue->n;
  1904. return cell;
  1905. }
  1906. /**
  1907. * Update the number of cells available on the circuit's n_chan or p_chan's
  1908. * circuit mux.
  1909. */
  1910. void
  1911. update_circuit_on_cmux_(circuit_t *circ, cell_direction_t direction,
  1912. const char *file, int lineno)
  1913. {
  1914. channel_t *chan = NULL;
  1915. or_circuit_t *or_circ = NULL;
  1916. circuitmux_t *cmux = NULL;
  1917. tor_assert(circ);
  1918. /* Okay, get the channel */
  1919. if (direction == CELL_DIRECTION_OUT) {
  1920. chan = circ->n_chan;
  1921. } else {
  1922. or_circ = TO_OR_CIRCUIT(circ);
  1923. chan = or_circ->p_chan;
  1924. }
  1925. tor_assert(chan);
  1926. tor_assert(chan->cmux);
  1927. /* Now get the cmux */
  1928. cmux = chan->cmux;
  1929. /* Cmux sanity check */
  1930. if (! circuitmux_is_circuit_attached(cmux, circ)) {
  1931. log_warn(LD_BUG, "called on non-attachd circuit from %s:%d",
  1932. file, lineno);
  1933. return;
  1934. }
  1935. tor_assert(circuitmux_attached_circuit_direction(cmux, circ) == direction);
  1936. assert_cmux_ok_paranoid(chan);
  1937. /* Update the number of cells we have for the circuit mux */
  1938. if (direction == CELL_DIRECTION_OUT) {
  1939. circuitmux_set_num_cells(cmux, circ, circ->n_chan_cells.n);
  1940. } else {
  1941. circuitmux_set_num_cells(cmux, circ, or_circ->p_chan_cells.n);
  1942. }
  1943. assert_cmux_ok_paranoid(chan);
  1944. }
  1945. /** Remove all circuits from the cmux on <b>chan</b>. */
  1946. void
  1947. channel_unlink_all_circuits(channel_t *chan)
  1948. {
  1949. tor_assert(chan);
  1950. tor_assert(chan->cmux);
  1951. circuitmux_detach_all_circuits(chan->cmux);
  1952. chan->num_n_circuits = 0;
  1953. chan->num_p_circuits = 0;
  1954. }
  1955. /** Block (if <b>block</b> is true) or unblock (if <b>block</b> is false)
  1956. * every edge connection that is using <b>circ</b> to write to <b>chan</b>,
  1957. * and start or stop reading as appropriate.
  1958. *
  1959. * If <b>stream_id</b> is nonzero, block only the edge connection whose
  1960. * stream_id matches it.
  1961. *
  1962. * Returns the number of streams whose status we changed.
  1963. */
  1964. static int
  1965. set_streams_blocked_on_circ(circuit_t *circ, channel_t *chan,
  1966. int block, streamid_t stream_id)
  1967. {
  1968. edge_connection_t *edge = NULL;
  1969. int n = 0;
  1970. if (circ->n_chan == chan) {
  1971. circ->streams_blocked_on_n_chan = block;
  1972. if (CIRCUIT_IS_ORIGIN(circ))
  1973. edge = TO_ORIGIN_CIRCUIT(circ)->p_streams;
  1974. } else {
  1975. circ->streams_blocked_on_p_chan = block;
  1976. tor_assert(!CIRCUIT_IS_ORIGIN(circ));
  1977. edge = TO_OR_CIRCUIT(circ)->n_streams;
  1978. }
  1979. for (; edge; edge = edge->next_stream) {
  1980. connection_t *conn = TO_CONN(edge);
  1981. if (stream_id && edge->stream_id != stream_id)
  1982. continue;
  1983. if (edge->edge_blocked_on_circ != block) {
  1984. ++n;
  1985. edge->edge_blocked_on_circ = block;
  1986. }
  1987. if (!conn->read_event && !HAS_BUFFEREVENT(conn)) {
  1988. /* This connection is a placeholder for something; probably a DNS
  1989. * request. It can't actually stop or start reading.*/
  1990. continue;
  1991. }
  1992. if (block) {
  1993. if (connection_is_reading(conn))
  1994. connection_stop_reading(conn);
  1995. } else {
  1996. /* Is this right? */
  1997. if (!connection_is_reading(conn))
  1998. connection_start_reading(conn);
  1999. }
  2000. }
  2001. return n;
  2002. }
  2003. /** Pull as many cells as possible (but no more than <b>max</b>) from the
  2004. * queue of the first active circuit on <b>chan</b>, and write them to
  2005. * <b>chan</b>-&gt;outbuf. Return the number of cells written. Advance
  2006. * the active circuit pointer to the next active circuit in the ring. */
  2007. int
  2008. channel_flush_from_first_active_circuit(channel_t *chan, int max)
  2009. {
  2010. circuitmux_t *cmux = NULL;
  2011. int n_flushed = 0;
  2012. cell_queue_t *queue;
  2013. circuit_t *circ;
  2014. or_circuit_t *or_circ;
  2015. int streams_blocked;
  2016. packed_cell_t *cell;
  2017. /* Get the cmux */
  2018. tor_assert(chan);
  2019. tor_assert(chan->cmux);
  2020. cmux = chan->cmux;
  2021. /* Main loop: pick a circuit, send a cell, update the cmux */
  2022. while (n_flushed < max) {
  2023. circ = circuitmux_get_first_active_circuit(cmux);
  2024. /* If it returns NULL, no cells left to send */
  2025. if (!circ) break;
  2026. assert_cmux_ok_paranoid(chan);
  2027. if (circ->n_chan == chan) {
  2028. queue = &circ->n_chan_cells;
  2029. streams_blocked = circ->streams_blocked_on_n_chan;
  2030. } else {
  2031. or_circ = TO_OR_CIRCUIT(circ);
  2032. tor_assert(or_circ->p_chan == chan);
  2033. queue = &TO_OR_CIRCUIT(circ)->p_chan_cells;
  2034. streams_blocked = circ->streams_blocked_on_p_chan;
  2035. }
  2036. /* Circuitmux told us this was active, so it should have cells */
  2037. tor_assert(queue->n > 0);
  2038. /*
  2039. * Get just one cell here; once we've sent it, that can change the circuit
  2040. * selection, so we have to loop around for another even if this circuit
  2041. * has more than one.
  2042. */
  2043. cell = cell_queue_pop(queue);
  2044. /* Calculate the exact time that this cell has spent in the queue. */
  2045. if (get_options()->CellStatistics && !CIRCUIT_IS_ORIGIN(circ)) {
  2046. struct timeval tvnow;
  2047. uint32_t flushed;
  2048. uint32_t cell_waiting_time;
  2049. insertion_time_queue_t *it_queue = queue->insertion_times;
  2050. tor_gettimeofday_cached(&tvnow);
  2051. flushed = (uint32_t)((tvnow.tv_sec % SECONDS_IN_A_DAY) * 100L +
  2052. (uint32_t)tvnow.tv_usec / (uint32_t)10000L);
  2053. if (!it_queue || !it_queue->first) {
  2054. log_info(LD_GENERAL, "Cannot determine insertion time of cell. "
  2055. "Looks like the CellStatistics option was "
  2056. "recently enabled.");
  2057. } else {
  2058. insertion_time_elem_t *elem = it_queue->first;
  2059. or_circ = TO_OR_CIRCUIT(circ);
  2060. cell_waiting_time =
  2061. (uint32_t)((flushed * 10L + SECONDS_IN_A_DAY * 1000L -
  2062. elem->insertion_time * 10L) %
  2063. (SECONDS_IN_A_DAY * 1000L));
  2064. #undef SECONDS_IN_A_DAY
  2065. elem->counter--;
  2066. if (elem->counter < 1) {
  2067. it_queue->first = elem->next;
  2068. if (elem == it_queue->last)
  2069. it_queue->last = NULL;
  2070. mp_pool_release(elem);
  2071. }
  2072. or_circ->total_cell_waiting_time += cell_waiting_time;
  2073. or_circ->processed_cells++;
  2074. }
  2075. }
  2076. /* If we just flushed our queue and this circuit is used for a
  2077. * tunneled directory request, possibly advance its state. */
  2078. if (queue->n == 0 && chan->dirreq_id)
  2079. geoip_change_dirreq_state(chan->dirreq_id,
  2080. DIRREQ_TUNNELED,
  2081. DIRREQ_CIRC_QUEUE_FLUSHED);
  2082. /* Now send the cell */
  2083. channel_write_packed_cell(chan, cell);
  2084. cell = NULL;
  2085. /*
  2086. * Don't packed_cell_free_unchecked(cell) here because the channel will
  2087. * do so when it gets out of the channel queue (probably already did, in
  2088. * which case that was an immediate double-free bug).
  2089. */
  2090. /* Update the counter */
  2091. ++n_flushed;
  2092. /*
  2093. * Now update the cmux; tell it we've just sent a cell, and how many
  2094. * we have left.
  2095. */
  2096. circuitmux_notify_xmit_cells(cmux, circ, 1);
  2097. circuitmux_set_num_cells(cmux, circ, queue->n);
  2098. if (queue->n == 0)
  2099. log_debug(LD_GENERAL, "Made a circuit inactive.");
  2100. /* Is the cell queue low enough to unblock all the streams that are waiting
  2101. * to write to this circuit? */
  2102. if (streams_blocked && queue->n <= CELL_QUEUE_LOWWATER_SIZE)
  2103. set_streams_blocked_on_circ(circ, chan, 0, 0); /* unblock streams */
  2104. /* If n_flushed < max still, loop around and pick another circuit */
  2105. }
  2106. /* Okay, we're done sending now */
  2107. assert_cmux_ok_paranoid(chan);
  2108. return n_flushed;
  2109. }
  2110. /** Add <b>cell</b> to the queue of <b>circ</b> writing to <b>chan</b>
  2111. * transmitting in <b>direction</b>. */
  2112. void
  2113. append_cell_to_circuit_queue(circuit_t *circ, channel_t *chan,
  2114. cell_t *cell, cell_direction_t direction,
  2115. streamid_t fromstream)
  2116. {
  2117. cell_queue_t *queue;
  2118. int streams_blocked;
  2119. if (circ->marked_for_close)
  2120. return;
  2121. if (direction == CELL_DIRECTION_OUT) {
  2122. queue = &circ->n_chan_cells;
  2123. streams_blocked = circ->streams_blocked_on_n_chan;
  2124. } else {
  2125. or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
  2126. queue = &orcirc->p_chan_cells;
  2127. streams_blocked = circ->streams_blocked_on_p_chan;
  2128. }
  2129. cell_queue_append_packed_copy(queue, cell);
  2130. /* If we have too many cells on the circuit, we should stop reading from
  2131. * the edge streams for a while. */
  2132. if (!streams_blocked && queue->n >= CELL_QUEUE_HIGHWATER_SIZE)
  2133. set_streams_blocked_on_circ(circ, chan, 1, 0); /* block streams */
  2134. if (streams_blocked && fromstream) {
  2135. /* This edge connection is apparently not blocked; block it. */
  2136. set_streams_blocked_on_circ(circ, chan, 1, fromstream);
  2137. }
  2138. update_circuit_on_cmux(circ, direction);
  2139. if (queue->n == 1) {
  2140. /* This was the first cell added to the queue. We just made this
  2141. * circuit active. */
  2142. log_debug(LD_GENERAL, "Made a circuit active.");
  2143. }
  2144. if (!channel_has_queued_writes(chan)) {
  2145. /* There is no data at all waiting to be sent on the outbuf. Add a
  2146. * cell, so that we can notice when it gets flushed, flushed_some can
  2147. * get called, and we can start putting more data onto the buffer then.
  2148. */
  2149. log_debug(LD_GENERAL, "Primed a buffer.");
  2150. channel_flush_from_first_active_circuit(chan, 1);
  2151. }
  2152. }
  2153. /** Append an encoded value of <b>addr</b> to <b>payload_out</b>, which must
  2154. * have at least 18 bytes of free space. The encoding is, as specified in
  2155. * tor-spec.txt:
  2156. * RESOLVED_TYPE_IPV4 or RESOLVED_TYPE_IPV6 [1 byte]
  2157. * LENGTH [1 byte]
  2158. * ADDRESS [length bytes]
  2159. * Return the number of bytes added, or -1 on error */
  2160. int
  2161. append_address_to_payload(uint8_t *payload_out, const tor_addr_t *addr)
  2162. {
  2163. uint32_t a;
  2164. switch (tor_addr_family(addr)) {
  2165. case AF_INET:
  2166. payload_out[0] = RESOLVED_TYPE_IPV4;
  2167. payload_out[1] = 4;
  2168. a = tor_addr_to_ipv4n(addr);
  2169. memcpy(payload_out+2, &a, 4);
  2170. return 6;
  2171. case AF_INET6:
  2172. payload_out[0] = RESOLVED_TYPE_IPV6;
  2173. payload_out[1] = 16;
  2174. memcpy(payload_out+2, tor_addr_to_in6_addr8(addr), 16);
  2175. return 18;
  2176. case AF_UNSPEC:
  2177. default:
  2178. return -1;
  2179. }
  2180. }
  2181. /** Given <b>payload_len</b> bytes at <b>payload</b>, starting with an address
  2182. * encoded as by append_address_to_payload(), try to decode the address into
  2183. * *<b>addr_out</b>. Return the next byte in the payload after the address on
  2184. * success, or NULL on failure. */
  2185. const uint8_t *
  2186. decode_address_from_payload(tor_addr_t *addr_out, const uint8_t *payload,
  2187. int payload_len)
  2188. {
  2189. if (payload_len < 2)
  2190. return NULL;
  2191. if (payload_len < 2+payload[1])
  2192. return NULL;
  2193. switch (payload[0]) {
  2194. case RESOLVED_TYPE_IPV4:
  2195. if (payload[1] != 4)
  2196. return NULL;
  2197. tor_addr_from_ipv4n(addr_out, get_uint32(payload+2));
  2198. break;
  2199. case RESOLVED_TYPE_IPV6:
  2200. if (payload[1] != 16)
  2201. return NULL;
  2202. tor_addr_from_ipv6_bytes(addr_out, (char*)(payload+2));
  2203. break;
  2204. default:
  2205. tor_addr_make_unspec(addr_out);
  2206. break;
  2207. }
  2208. return payload + 2 + payload[1];
  2209. }
  2210. /** Remove all the cells queued on <b>circ</b> for <b>chan</b>. */
  2211. void
  2212. circuit_clear_cell_queue(circuit_t *circ, channel_t *chan)
  2213. {
  2214. cell_queue_t *queue;
  2215. cell_direction_t direction;
  2216. if (circ->n_chan == chan) {
  2217. queue = &circ->n_chan_cells;
  2218. direction = CELL_DIRECTION_OUT;
  2219. } else {
  2220. or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
  2221. tor_assert(orcirc->p_chan == chan);
  2222. queue = &orcirc->p_chan_cells;
  2223. direction = CELL_DIRECTION_IN;
  2224. }
  2225. /* Clear the queue */
  2226. cell_queue_clear(queue);
  2227. /* Update the cell counter in the cmux */
  2228. if (chan->cmux && circuitmux_is_circuit_attached(chan->cmux, circ))
  2229. update_circuit_on_cmux(circ, direction);
  2230. }
  2231. /** Fail with an assert if the circuit mux on chan is corrupt
  2232. */
  2233. void
  2234. assert_circuit_mux_okay(channel_t *chan)
  2235. {
  2236. tor_assert(chan);
  2237. tor_assert(chan->cmux);
  2238. circuitmux_assert_okay(chan->cmux);
  2239. }
  2240. /** Return 1 if we shouldn't restart reading on this circuit, even if
  2241. * we get a SENDME. Else return 0.
  2242. */
  2243. static int
  2244. circuit_queue_streams_are_blocked(circuit_t *circ)
  2245. {
  2246. if (CIRCUIT_IS_ORIGIN(circ)) {
  2247. return circ->streams_blocked_on_n_chan;
  2248. } else {
  2249. return circ->streams_blocked_on_p_chan;
  2250. }
  2251. }