relay.c 97 KB

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