relay.c 103 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942
  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_DESTROY) {
  670. /* Both of these reasons could mean a failed tag
  671. * hit the exit and it complained. Do not probe.
  672. * Fail the circuit. */
  673. circ->path_state = PATH_STATE_USE_FAILED;
  674. return -END_CIRC_REASON_TORPROTOCOL;
  675. } else if (reason == END_STREAM_REASON_INTERNAL) {
  676. /* We can't infer success or failure, since older Tors report
  677. * ENETUNREACH as END_STREAM_REASON_INTERNAL. */
  678. } else {
  679. /* Path bias: If we get a valid reason code from the exit,
  680. * it wasn't due to tagging.
  681. *
  682. * We rely on recognized+digest being strong enough to make
  683. * tags unlikely to allow us to get tagged, yet 'recognized'
  684. * reason codes here. */
  685. pathbias_mark_use_success(circ);
  686. }
  687. }
  688. if (rh->length == 0) {
  689. reason = END_STREAM_REASON_MISC;
  690. }
  691. control_reason = reason | END_STREAM_REASON_FLAG_REMOTE;
  692. if (edge_reason_is_retriable(reason) &&
  693. /* avoid retry if rend */
  694. !connection_edge_is_rendezvous_stream(edge_conn)) {
  695. const char *chosen_exit_digest =
  696. circ->build_state->chosen_exit->identity_digest;
  697. log_info(LD_APP,"Address '%s' refused due to '%s'. Considering retrying.",
  698. safe_str(conn->socks_request->address),
  699. stream_end_reason_to_string(reason));
  700. exitrouter = node_get_mutable_by_id(chosen_exit_digest);
  701. switch (reason) {
  702. case END_STREAM_REASON_EXITPOLICY: {
  703. tor_addr_t addr;
  704. tor_addr_make_unspec(&addr);
  705. if (rh->length >= 5) {
  706. int ttl = -1;
  707. tor_addr_make_unspec(&addr);
  708. if (rh->length == 5 || rh->length == 9) {
  709. tor_addr_from_ipv4n(&addr,
  710. get_uint32(cell->payload+RELAY_HEADER_SIZE+1));
  711. if (rh->length == 9)
  712. ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+5));
  713. } else if (rh->length == 17 || rh->length == 21) {
  714. tor_addr_from_ipv6_bytes(&addr,
  715. (char*)(cell->payload+RELAY_HEADER_SIZE+1));
  716. if (rh->length == 21)
  717. ttl = (int)ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE+17));
  718. }
  719. if (tor_addr_is_null(&addr)) {
  720. log_info(LD_APP,"Address '%s' resolved to 0.0.0.0. Closing,",
  721. safe_str(conn->socks_request->address));
  722. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  723. return 0;
  724. }
  725. if ((tor_addr_family(&addr) == AF_INET && !conn->ipv4_traffic_ok) ||
  726. (tor_addr_family(&addr) == AF_INET6 && !conn->ipv6_traffic_ok)) {
  727. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  728. "Got an EXITPOLICY failure on a connection with a "
  729. "mismatched family. Closing.");
  730. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  731. return 0;
  732. }
  733. if (get_options()->ClientDNSRejectInternalAddresses &&
  734. tor_addr_is_internal(&addr, 0)) {
  735. log_info(LD_APP,"Address '%s' resolved to internal. Closing,",
  736. safe_str(conn->socks_request->address));
  737. connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
  738. return 0;
  739. }
  740. client_dns_set_addressmap(conn,
  741. conn->socks_request->address, &addr,
  742. conn->chosen_exit_name, ttl);
  743. {
  744. char new_addr[TOR_ADDR_BUF_LEN];
  745. tor_addr_to_str(new_addr, &addr, sizeof(new_addr), 1);
  746. if (strcmp(conn->socks_request->address, new_addr)) {
  747. strlcpy(conn->socks_request->address, new_addr,
  748. sizeof(conn->socks_request->address));
  749. control_event_stream_status(conn, STREAM_EVENT_REMAP, 0);
  750. }
  751. }
  752. }
  753. /* check if he *ought* to have allowed it */
  754. adjust_exit_policy_from_exitpolicy_failure(circ,
  755. conn,
  756. exitrouter,
  757. &addr);
  758. if (conn->chosen_exit_optional ||
  759. conn->chosen_exit_retries) {
  760. /* stop wanting a specific exit */
  761. conn->chosen_exit_optional = 0;
  762. /* A non-zero chosen_exit_retries can happen if we set a
  763. * TrackHostExits for this address under a port that the exit
  764. * relay allows, but then try the same address with a different
  765. * port that it doesn't allow to exit. We shouldn't unregister
  766. * the mapping, since it is probably still wanted on the
  767. * original port. But now we give away to the exit relay that
  768. * we probably have a TrackHostExits on it. So be it. */
  769. conn->chosen_exit_retries = 0;
  770. tor_free(conn->chosen_exit_name); /* clears it */
  771. }
  772. if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
  773. return 0;
  774. /* else, conn will get closed below */
  775. break;
  776. }
  777. case END_STREAM_REASON_CONNECTREFUSED:
  778. if (!conn->chosen_exit_optional)
  779. break; /* break means it'll close, below */
  780. /* Else fall through: expire this circuit, clear the
  781. * chosen_exit_name field, and try again. */
  782. case END_STREAM_REASON_RESOLVEFAILED:
  783. case END_STREAM_REASON_TIMEOUT:
  784. case END_STREAM_REASON_MISC:
  785. case END_STREAM_REASON_NOROUTE:
  786. if (client_dns_incr_failures(conn->socks_request->address)
  787. < MAX_RESOLVE_FAILURES) {
  788. /* We haven't retried too many times; reattach the connection. */
  789. circuit_log_path(LOG_INFO,LD_APP,circ);
  790. /* Mark this circuit "unusable for new streams". */
  791. mark_circuit_unusable_for_new_conns(circ);
  792. if (conn->chosen_exit_optional) {
  793. /* stop wanting a specific exit */
  794. conn->chosen_exit_optional = 0;
  795. tor_free(conn->chosen_exit_name); /* clears it */
  796. }
  797. if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
  798. return 0;
  799. /* else, conn will get closed below */
  800. } else {
  801. log_notice(LD_APP,
  802. "Have tried resolving or connecting to address '%s' "
  803. "at %d different places. Giving up.",
  804. safe_str(conn->socks_request->address),
  805. MAX_RESOLVE_FAILURES);
  806. /* clear the failures, so it will have a full try next time */
  807. client_dns_clear_failures(conn->socks_request->address);
  808. }
  809. break;
  810. case END_STREAM_REASON_HIBERNATING:
  811. case END_STREAM_REASON_RESOURCELIMIT:
  812. if (exitrouter) {
  813. policies_set_node_exitpolicy_to_reject_all(exitrouter);
  814. }
  815. if (conn->chosen_exit_optional) {
  816. /* stop wanting a specific exit */
  817. conn->chosen_exit_optional = 0;
  818. tor_free(conn->chosen_exit_name); /* clears it */
  819. }
  820. if (connection_ap_detach_retriable(conn, circ, control_reason) >= 0)
  821. return 0;
  822. /* else, will close below */
  823. break;
  824. } /* end switch */
  825. log_info(LD_APP,"Giving up on retrying; conn can't be handled.");
  826. }
  827. log_info(LD_APP,
  828. "Edge got end (%s) before we're connected. Marking for close.",
  829. stream_end_reason_to_string(rh->length > 0 ? reason : -1));
  830. circuit_log_path(LOG_INFO,LD_APP,circ);
  831. /* need to test because of detach_retriable */
  832. if (!ENTRY_TO_CONN(conn)->marked_for_close)
  833. connection_mark_unattached_ap(conn, control_reason);
  834. return 0;
  835. }
  836. /** Called when we have gotten an END_REASON_EXITPOLICY failure on <b>circ</b>
  837. * for <b>conn</b>, while attempting to connect via <b>node</b>. If the node
  838. * told us which address it rejected, then <b>addr</b> is that address;
  839. * otherwise it is AF_UNSPEC.
  840. *
  841. * If we are sure the node should have allowed this address, mark the node as
  842. * having a reject *:* exit policy. Otherwise, mark the circuit as unusable
  843. * for this particular address.
  844. **/
  845. static void
  846. adjust_exit_policy_from_exitpolicy_failure(origin_circuit_t *circ,
  847. entry_connection_t *conn,
  848. node_t *node,
  849. const tor_addr_t *addr)
  850. {
  851. int make_reject_all = 0;
  852. const sa_family_t family = tor_addr_family(addr);
  853. if (node) {
  854. tor_addr_t tmp;
  855. int asked_for_family = tor_addr_parse(&tmp, conn->socks_request->address);
  856. if (family == AF_UNSPEC) {
  857. make_reject_all = 1;
  858. } else if (node_exit_policy_is_exact(node, family) &&
  859. asked_for_family != -1 && !conn->chosen_exit_name) {
  860. make_reject_all = 1;
  861. }
  862. if (make_reject_all) {
  863. log_info(LD_APP,
  864. "Exitrouter %s seems to be more restrictive than its exit "
  865. "policy. Not using this router as exit for now.",
  866. node_describe(node));
  867. policies_set_node_exitpolicy_to_reject_all(node);
  868. }
  869. }
  870. if (family != AF_UNSPEC)
  871. addr_policy_append_reject_addr(&circ->prepend_policy, addr);
  872. }
  873. /** Helper: change the socks_request-&gt;address field on conn to the
  874. * dotted-quad representation of <b>new_addr</b>,
  875. * and send an appropriate REMAP event. */
  876. static void
  877. remap_event_helper(entry_connection_t *conn, const tor_addr_t *new_addr)
  878. {
  879. tor_addr_to_str(conn->socks_request->address, new_addr,
  880. sizeof(conn->socks_request->address),
  881. 1);
  882. control_event_stream_status(conn, STREAM_EVENT_REMAP,
  883. REMAP_STREAM_SOURCE_EXIT);
  884. }
  885. /** Extract the contents of a connected cell in <b>cell</b>, whose relay
  886. * header has already been parsed into <b>rh</b>. On success, set
  887. * <b>addr_out</b> to the address we're connected to, and <b>ttl_out</b> to
  888. * the ttl of that address, in seconds, and return 0. On failure, return
  889. * -1. */
  890. STATIC int
  891. connected_cell_parse(const relay_header_t *rh, const cell_t *cell,
  892. tor_addr_t *addr_out, int *ttl_out)
  893. {
  894. uint32_t bytes;
  895. const uint8_t *payload = cell->payload + RELAY_HEADER_SIZE;
  896. tor_addr_make_unspec(addr_out);
  897. *ttl_out = -1;
  898. if (rh->length == 0)
  899. return 0;
  900. if (rh->length < 4)
  901. return -1;
  902. bytes = ntohl(get_uint32(payload));
  903. /* If bytes is 0, this is maybe a v6 address. Otherwise it's a v4 address */
  904. if (bytes != 0) {
  905. /* v4 address */
  906. tor_addr_from_ipv4h(addr_out, bytes);
  907. if (rh->length >= 8) {
  908. bytes = ntohl(get_uint32(payload + 4));
  909. if (bytes <= INT32_MAX)
  910. *ttl_out = bytes;
  911. }
  912. } else {
  913. if (rh->length < 25) /* 4 bytes of 0s, 1 addr, 16 ipv4, 4 ttl. */
  914. return -1;
  915. if (get_uint8(payload + 4) != 6)
  916. return -1;
  917. tor_addr_from_ipv6_bytes(addr_out, (char*)(payload + 5));
  918. bytes = ntohl(get_uint32(payload + 21));
  919. if (bytes <= INT32_MAX)
  920. *ttl_out = (int) bytes;
  921. }
  922. return 0;
  923. }
  924. /** Drop all storage held by <b>addr</b>. */
  925. STATIC void
  926. address_ttl_free(address_ttl_t *addr)
  927. {
  928. if (!addr)
  929. return;
  930. tor_free(addr->hostname);
  931. tor_free(addr);
  932. }
  933. /** Parse a resolved cell in <b>cell</b>, with parsed header in <b>rh</b>.
  934. * Return -1 on parse error. On success, add one or more newly allocated
  935. * address_ttl_t to <b>addresses_out</b>; set *<b>errcode_out</b> to
  936. * one of 0, RESOLVED_TYPE_ERROR, or RESOLVED_TYPE_ERROR_TRANSIENT, and
  937. * return 0. */
  938. STATIC int
  939. resolved_cell_parse(const cell_t *cell, const relay_header_t *rh,
  940. smartlist_t *addresses_out, int *errcode_out)
  941. {
  942. const uint8_t *cp;
  943. uint8_t answer_type;
  944. size_t answer_len;
  945. address_ttl_t *addr;
  946. size_t remaining;
  947. int errcode = 0;
  948. smartlist_t *addrs;
  949. tor_assert(cell);
  950. tor_assert(rh);
  951. tor_assert(addresses_out);
  952. tor_assert(errcode_out);
  953. *errcode_out = 0;
  954. if (rh->length > RELAY_PAYLOAD_SIZE)
  955. return -1;
  956. addrs = smartlist_new();
  957. cp = cell->payload + RELAY_HEADER_SIZE;
  958. remaining = rh->length;
  959. while (remaining) {
  960. const uint8_t *cp_orig = cp;
  961. if (remaining < 2)
  962. goto err;
  963. answer_type = *cp++;
  964. answer_len = *cp++;
  965. if (remaining < 2 + answer_len + 4) {
  966. goto err;
  967. }
  968. if (answer_type == RESOLVED_TYPE_IPV4) {
  969. if (answer_len != 4) {
  970. goto err;
  971. }
  972. addr = tor_malloc_zero(sizeof(*addr));
  973. tor_addr_from_ipv4n(&addr->addr, get_uint32(cp));
  974. cp += 4;
  975. addr->ttl = ntohl(get_uint32(cp));
  976. cp += 4;
  977. smartlist_add(addrs, addr);
  978. } else if (answer_type == RESOLVED_TYPE_IPV6) {
  979. if (answer_len != 16)
  980. goto err;
  981. addr = tor_malloc_zero(sizeof(*addr));
  982. tor_addr_from_ipv6_bytes(&addr->addr, (const char*) cp);
  983. cp += 16;
  984. addr->ttl = ntohl(get_uint32(cp));
  985. cp += 4;
  986. smartlist_add(addrs, addr);
  987. } else if (answer_type == RESOLVED_TYPE_HOSTNAME) {
  988. if (answer_len == 0) {
  989. goto err;
  990. }
  991. addr = tor_malloc_zero(sizeof(*addr));
  992. addr->hostname = tor_memdup_nulterm(cp, answer_len);
  993. cp += answer_len;
  994. addr->ttl = ntohl(get_uint32(cp));
  995. cp += 4;
  996. smartlist_add(addrs, addr);
  997. } else if (answer_type == RESOLVED_TYPE_ERROR_TRANSIENT ||
  998. answer_type == RESOLVED_TYPE_ERROR) {
  999. errcode = answer_type;
  1000. /* Ignore the error contents */
  1001. cp += answer_len + 4;
  1002. } else {
  1003. cp += answer_len + 4;
  1004. }
  1005. tor_assert(((ssize_t)remaining) >= (cp - cp_orig));
  1006. remaining -= (cp - cp_orig);
  1007. }
  1008. if (errcode && smartlist_len(addrs) == 0) {
  1009. /* Report an error only if there were no results. */
  1010. *errcode_out = errcode;
  1011. }
  1012. smartlist_add_all(addresses_out, addrs);
  1013. smartlist_free(addrs);
  1014. return 0;
  1015. err:
  1016. /* On parse error, don't report any results */
  1017. SMARTLIST_FOREACH(addrs, address_ttl_t *, a, address_ttl_free(a));
  1018. smartlist_free(addrs);
  1019. return -1;
  1020. }
  1021. /** Helper for connection_edge_process_resolved_cell: given an error code,
  1022. * an entry_connection, and a list of address_ttl_t *, report the best answer
  1023. * to the entry_connection. */
  1024. static void
  1025. connection_ap_handshake_socks_got_resolved_cell(entry_connection_t *conn,
  1026. int error_code,
  1027. smartlist_t *results)
  1028. {
  1029. address_ttl_t *addr_ipv4 = NULL;
  1030. address_ttl_t *addr_ipv6 = NULL;
  1031. address_ttl_t *addr_hostname = NULL;
  1032. address_ttl_t *addr_best = NULL;
  1033. /* If it's an error code, that's easy. */
  1034. if (error_code) {
  1035. tor_assert(error_code == RESOLVED_TYPE_ERROR ||
  1036. error_code == RESOLVED_TYPE_ERROR_TRANSIENT);
  1037. connection_ap_handshake_socks_resolved(conn,
  1038. error_code,0,NULL,-1,-1);
  1039. return;
  1040. }
  1041. /* Get the first answer of each type. */
  1042. SMARTLIST_FOREACH_BEGIN(results, address_ttl_t *, addr) {
  1043. if (addr->hostname) {
  1044. if (!addr_hostname) {
  1045. addr_hostname = addr;
  1046. }
  1047. } else if (tor_addr_family(&addr->addr) == AF_INET) {
  1048. if (!addr_ipv4 && conn->ipv4_traffic_ok) {
  1049. addr_ipv4 = addr;
  1050. }
  1051. } else if (tor_addr_family(&addr->addr) == AF_INET6) {
  1052. if (!addr_ipv6 && conn->ipv6_traffic_ok) {
  1053. addr_ipv6 = addr;
  1054. }
  1055. }
  1056. } SMARTLIST_FOREACH_END(addr);
  1057. /* Now figure out which type we wanted to deliver. */
  1058. if (conn->socks_request->command == SOCKS_COMMAND_RESOLVE_PTR) {
  1059. if (addr_hostname) {
  1060. connection_ap_handshake_socks_resolved(conn,
  1061. RESOLVED_TYPE_HOSTNAME,
  1062. strlen(addr_hostname->hostname),
  1063. (uint8_t*)addr_hostname->hostname,
  1064. addr_hostname->ttl,-1);
  1065. } else {
  1066. connection_ap_handshake_socks_resolved(conn,
  1067. RESOLVED_TYPE_ERROR,0,NULL,-1,-1);
  1068. }
  1069. return;
  1070. }
  1071. if (conn->prefer_ipv6_traffic) {
  1072. addr_best = addr_ipv6 ? addr_ipv6 : addr_ipv4;
  1073. } else {
  1074. addr_best = addr_ipv4 ? addr_ipv4 : addr_ipv6;
  1075. }
  1076. /* Now convert it to the ugly old interface */
  1077. if (! addr_best) {
  1078. connection_ap_handshake_socks_resolved(conn,
  1079. RESOLVED_TYPE_ERROR,0,NULL,-1,-1);
  1080. return;
  1081. }
  1082. connection_ap_handshake_socks_resolved_addr(conn,
  1083. &addr_best->addr,
  1084. addr_best->ttl,
  1085. -1);
  1086. remap_event_helper(conn, &addr_best->addr);
  1087. }
  1088. /** Handle a RELAY_COMMAND_RESOLVED cell that we received on a non-open AP
  1089. * stream. */
  1090. STATIC int
  1091. connection_edge_process_resolved_cell(edge_connection_t *conn,
  1092. const cell_t *cell,
  1093. const relay_header_t *rh)
  1094. {
  1095. entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
  1096. smartlist_t *resolved_addresses = NULL;
  1097. int errcode = 0;
  1098. if (conn->base_.state != AP_CONN_STATE_RESOLVE_WAIT) {
  1099. log_fn(LOG_PROTOCOL_WARN, LD_APP, "Got a 'resolved' cell while "
  1100. "not in state resolve_wait. Dropping.");
  1101. return 0;
  1102. }
  1103. tor_assert(SOCKS_COMMAND_IS_RESOLVE(entry_conn->socks_request->command));
  1104. resolved_addresses = smartlist_new();
  1105. if (resolved_cell_parse(cell, rh, resolved_addresses, &errcode)) {
  1106. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1107. "Dropping malformed 'resolved' cell");
  1108. connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TORPROTOCOL);
  1109. goto done;
  1110. }
  1111. if (get_options()->ClientDNSRejectInternalAddresses) {
  1112. int orig_len = smartlist_len(resolved_addresses);
  1113. SMARTLIST_FOREACH_BEGIN(resolved_addresses, address_ttl_t *, addr) {
  1114. if (addr->hostname == NULL && tor_addr_is_internal(&addr->addr, 0)) {
  1115. log_info(LD_APP, "Got a resolved cell with answer %s; dropping that "
  1116. "answer.",
  1117. safe_str_client(fmt_addr(&addr->addr)));
  1118. address_ttl_free(addr);
  1119. SMARTLIST_DEL_CURRENT(resolved_addresses, addr);
  1120. }
  1121. } SMARTLIST_FOREACH_END(addr);
  1122. if (orig_len && smartlist_len(resolved_addresses) == 0) {
  1123. log_info(LD_APP, "Got a resolved cell with only private addresses; "
  1124. "dropping it.");
  1125. connection_ap_handshake_socks_resolved(entry_conn,
  1126. RESOLVED_TYPE_ERROR_TRANSIENT,
  1127. 0, NULL, 0, TIME_MAX);
  1128. connection_mark_unattached_ap(entry_conn,
  1129. END_STREAM_REASON_TORPROTOCOL);
  1130. goto done;
  1131. }
  1132. }
  1133. connection_ap_handshake_socks_got_resolved_cell(entry_conn,
  1134. errcode,
  1135. resolved_addresses);
  1136. connection_mark_unattached_ap(entry_conn,
  1137. END_STREAM_REASON_DONE |
  1138. END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
  1139. done:
  1140. SMARTLIST_FOREACH(resolved_addresses, address_ttl_t *, addr,
  1141. address_ttl_free(addr));
  1142. smartlist_free(resolved_addresses);
  1143. return 0;
  1144. }
  1145. /** An incoming relay cell has arrived from circuit <b>circ</b> to
  1146. * stream <b>conn</b>.
  1147. *
  1148. * The arguments here are the same as in
  1149. * connection_edge_process_relay_cell() below; this function is called
  1150. * from there when <b>conn</b> is defined and not in an open state.
  1151. */
  1152. static int
  1153. connection_edge_process_relay_cell_not_open(
  1154. relay_header_t *rh, cell_t *cell, circuit_t *circ,
  1155. edge_connection_t *conn, crypt_path_t *layer_hint)
  1156. {
  1157. if (rh->command == RELAY_COMMAND_END) {
  1158. if (CIRCUIT_IS_ORIGIN(circ) && conn->base_.type == CONN_TYPE_AP) {
  1159. return connection_ap_process_end_not_open(rh, cell,
  1160. TO_ORIGIN_CIRCUIT(circ),
  1161. EDGE_TO_ENTRY_CONN(conn),
  1162. layer_hint);
  1163. } else {
  1164. /* we just got an 'end', don't need to send one */
  1165. conn->edge_has_sent_end = 1;
  1166. conn->end_reason = *(cell->payload+RELAY_HEADER_SIZE) |
  1167. END_STREAM_REASON_FLAG_REMOTE;
  1168. connection_mark_for_close(TO_CONN(conn));
  1169. return 0;
  1170. }
  1171. }
  1172. if (conn->base_.type == CONN_TYPE_AP &&
  1173. rh->command == RELAY_COMMAND_CONNECTED) {
  1174. tor_addr_t addr;
  1175. int ttl;
  1176. entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
  1177. tor_assert(CIRCUIT_IS_ORIGIN(circ));
  1178. if (conn->base_.state != AP_CONN_STATE_CONNECT_WAIT) {
  1179. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  1180. "Got 'connected' while not in state connect_wait. Dropping.");
  1181. return 0;
  1182. }
  1183. conn->base_.state = AP_CONN_STATE_OPEN;
  1184. log_info(LD_APP,"'connected' received after %d seconds.",
  1185. (int)(time(NULL) - conn->base_.timestamp_lastread));
  1186. if (connected_cell_parse(rh, cell, &addr, &ttl) < 0) {
  1187. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  1188. "Got a badly formatted connected cell. Closing.");
  1189. connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
  1190. connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TORPROTOCOL);
  1191. }
  1192. if (tor_addr_family(&addr) != AF_UNSPEC) {
  1193. const sa_family_t family = tor_addr_family(&addr);
  1194. if (tor_addr_is_null(&addr) ||
  1195. (get_options()->ClientDNSRejectInternalAddresses &&
  1196. tor_addr_is_internal(&addr, 0))) {
  1197. log_info(LD_APP, "...but it claims the IP address was %s. Closing.",
  1198. fmt_addr(&addr));
  1199. connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
  1200. connection_mark_unattached_ap(entry_conn,
  1201. END_STREAM_REASON_TORPROTOCOL);
  1202. return 0;
  1203. }
  1204. if ((family == AF_INET && ! entry_conn->ipv4_traffic_ok) ||
  1205. (family == AF_INET6 && ! entry_conn->ipv6_traffic_ok)) {
  1206. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  1207. "Got a connected cell to %s with unsupported address family."
  1208. " Closing.", fmt_addr(&addr));
  1209. connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
  1210. connection_mark_unattached_ap(entry_conn,
  1211. END_STREAM_REASON_TORPROTOCOL);
  1212. return 0;
  1213. }
  1214. client_dns_set_addressmap(entry_conn,
  1215. entry_conn->socks_request->address, &addr,
  1216. entry_conn->chosen_exit_name, ttl);
  1217. remap_event_helper(entry_conn, &addr);
  1218. }
  1219. circuit_log_path(LOG_INFO,LD_APP,TO_ORIGIN_CIRCUIT(circ));
  1220. /* don't send a socks reply to transparent conns */
  1221. tor_assert(entry_conn->socks_request != NULL);
  1222. if (!entry_conn->socks_request->has_finished)
  1223. connection_ap_handshake_socks_reply(entry_conn, NULL, 0, 0);
  1224. /* Was it a linked dir conn? If so, a dir request just started to
  1225. * fetch something; this could be a bootstrap status milestone. */
  1226. log_debug(LD_APP, "considering");
  1227. if (TO_CONN(conn)->linked_conn &&
  1228. TO_CONN(conn)->linked_conn->type == CONN_TYPE_DIR) {
  1229. connection_t *dirconn = TO_CONN(conn)->linked_conn;
  1230. log_debug(LD_APP, "it is! %d", dirconn->purpose);
  1231. switch (dirconn->purpose) {
  1232. case DIR_PURPOSE_FETCH_CERTIFICATE:
  1233. if (consensus_is_waiting_for_certs())
  1234. control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_KEYS, 0);
  1235. break;
  1236. case DIR_PURPOSE_FETCH_CONSENSUS:
  1237. control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_STATUS, 0);
  1238. break;
  1239. case DIR_PURPOSE_FETCH_SERVERDESC:
  1240. case DIR_PURPOSE_FETCH_MICRODESC:
  1241. if (TO_DIR_CONN(dirconn)->router_purpose == ROUTER_PURPOSE_GENERAL)
  1242. control_event_bootstrap(BOOTSTRAP_STATUS_LOADING_DESCRIPTORS,
  1243. count_loading_descriptors_progress());
  1244. break;
  1245. }
  1246. }
  1247. /* This is definitely a success, so forget about any pending data we
  1248. * had sent. */
  1249. if (entry_conn->pending_optimistic_data) {
  1250. generic_buffer_free(entry_conn->pending_optimistic_data);
  1251. entry_conn->pending_optimistic_data = NULL;
  1252. }
  1253. /* handle anything that might have queued */
  1254. if (connection_edge_package_raw_inbuf(conn, 1, NULL) < 0) {
  1255. /* (We already sent an end cell if possible) */
  1256. connection_mark_for_close(TO_CONN(conn));
  1257. return 0;
  1258. }
  1259. return 0;
  1260. }
  1261. if (conn->base_.type == CONN_TYPE_AP &&
  1262. rh->command == RELAY_COMMAND_RESOLVED) {
  1263. return connection_edge_process_resolved_cell(conn, cell, rh);
  1264. }
  1265. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1266. "Got an unexpected relay command %d, in state %d (%s). Dropping.",
  1267. rh->command, conn->base_.state,
  1268. conn_state_to_string(conn->base_.type, conn->base_.state));
  1269. return 0; /* for forward compatibility, don't kill the circuit */
  1270. // connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
  1271. // connection_mark_for_close(conn);
  1272. // return -1;
  1273. }
  1274. /** An incoming relay cell has arrived on circuit <b>circ</b>. If
  1275. * <b>conn</b> is NULL this is a control cell, else <b>cell</b> is
  1276. * destined for <b>conn</b>.
  1277. *
  1278. * If <b>layer_hint</b> is defined, then we're the origin of the
  1279. * circuit, and it specifies the hop that packaged <b>cell</b>.
  1280. *
  1281. * Return -reason if you want to warn and tear down the circuit, else 0.
  1282. */
  1283. static int
  1284. connection_edge_process_relay_cell(cell_t *cell, circuit_t *circ,
  1285. edge_connection_t *conn,
  1286. crypt_path_t *layer_hint)
  1287. {
  1288. static int num_seen=0;
  1289. relay_header_t rh;
  1290. unsigned domain = layer_hint?LD_APP:LD_EXIT;
  1291. int reason;
  1292. int optimistic_data = 0; /* Set to 1 if we receive data on a stream
  1293. * that's in the EXIT_CONN_STATE_RESOLVING
  1294. * or EXIT_CONN_STATE_CONNECTING states. */
  1295. tor_assert(cell);
  1296. tor_assert(circ);
  1297. relay_header_unpack(&rh, cell->payload);
  1298. // log_fn(LOG_DEBUG,"command %d stream %d", rh.command, rh.stream_id);
  1299. num_seen++;
  1300. log_debug(domain, "Now seen %d relay cells here (command %d, stream %d).",
  1301. num_seen, rh.command, rh.stream_id);
  1302. if (rh.length > RELAY_PAYLOAD_SIZE) {
  1303. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1304. "Relay cell length field too long. Closing circuit.");
  1305. return - END_CIRC_REASON_TORPROTOCOL;
  1306. }
  1307. if (rh.stream_id == 0) {
  1308. switch (rh.command) {
  1309. case RELAY_COMMAND_BEGIN:
  1310. case RELAY_COMMAND_CONNECTED:
  1311. case RELAY_COMMAND_DATA:
  1312. case RELAY_COMMAND_END:
  1313. case RELAY_COMMAND_RESOLVE:
  1314. case RELAY_COMMAND_RESOLVED:
  1315. case RELAY_COMMAND_BEGIN_DIR:
  1316. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, "Relay command %d with zero "
  1317. "stream_id. Dropping.", (int)rh.command);
  1318. return 0;
  1319. default:
  1320. ;
  1321. }
  1322. }
  1323. /* either conn is NULL, in which case we've got a control cell, or else
  1324. * conn points to the recognized stream. */
  1325. if (conn && !connection_state_is_open(TO_CONN(conn))) {
  1326. if (conn->base_.type == CONN_TYPE_EXIT &&
  1327. (conn->base_.state == EXIT_CONN_STATE_CONNECTING ||
  1328. conn->base_.state == EXIT_CONN_STATE_RESOLVING) &&
  1329. rh.command == RELAY_COMMAND_DATA) {
  1330. /* Allow DATA cells to be delivered to an exit node in state
  1331. * EXIT_CONN_STATE_CONNECTING or EXIT_CONN_STATE_RESOLVING.
  1332. * This speeds up HTTP, for example. */
  1333. optimistic_data = 1;
  1334. } else {
  1335. return connection_edge_process_relay_cell_not_open(
  1336. &rh, cell, circ, conn, layer_hint);
  1337. }
  1338. }
  1339. switch (rh.command) {
  1340. case RELAY_COMMAND_DROP:
  1341. // log_info(domain,"Got a relay-level padding cell. Dropping.");
  1342. return 0;
  1343. case RELAY_COMMAND_BEGIN:
  1344. case RELAY_COMMAND_BEGIN_DIR:
  1345. if (layer_hint &&
  1346. circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
  1347. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  1348. "Relay begin request unsupported at AP. Dropping.");
  1349. return 0;
  1350. }
  1351. if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED &&
  1352. layer_hint != TO_ORIGIN_CIRCUIT(circ)->cpath->prev) {
  1353. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  1354. "Relay begin request to Hidden Service "
  1355. "from intermediary node. Dropping.");
  1356. return 0;
  1357. }
  1358. if (conn) {
  1359. log_fn(LOG_PROTOCOL_WARN, domain,
  1360. "Begin cell for known stream. Dropping.");
  1361. return 0;
  1362. }
  1363. if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
  1364. /* Assign this circuit and its app-ward OR connection a unique ID,
  1365. * so that we can measure download times. The local edge and dir
  1366. * connection will be assigned the same ID when they are created
  1367. * and linked. */
  1368. static uint64_t next_id = 0;
  1369. circ->dirreq_id = ++next_id;
  1370. TO_OR_CIRCUIT(circ)->p_chan->dirreq_id = circ->dirreq_id;
  1371. }
  1372. return connection_exit_begin_conn(cell, circ);
  1373. case RELAY_COMMAND_DATA:
  1374. ++stats_n_data_cells_received;
  1375. if (( layer_hint && --layer_hint->deliver_window < 0) ||
  1376. (!layer_hint && --circ->deliver_window < 0)) {
  1377. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1378. "(relay data) circ deliver_window below 0. Killing.");
  1379. if (conn) {
  1380. /* XXXX Do we actually need to do this? Will killing the circuit
  1381. * not send an END and mark the stream for close as appropriate? */
  1382. connection_edge_end(conn, END_STREAM_REASON_TORPROTOCOL);
  1383. connection_mark_for_close(TO_CONN(conn));
  1384. }
  1385. return -END_CIRC_REASON_TORPROTOCOL;
  1386. }
  1387. log_debug(domain,"circ deliver_window now %d.", layer_hint ?
  1388. layer_hint->deliver_window : circ->deliver_window);
  1389. circuit_consider_sending_sendme(circ, layer_hint);
  1390. if (!conn) {
  1391. log_info(domain,"data cell dropped, unknown stream (streamid %d).",
  1392. rh.stream_id);
  1393. return 0;
  1394. }
  1395. if (--conn->deliver_window < 0) { /* is it below 0 after decrement? */
  1396. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1397. "(relay data) conn deliver_window below 0. Killing.");
  1398. return -END_CIRC_REASON_TORPROTOCOL;
  1399. }
  1400. stats_n_data_bytes_received += rh.length;
  1401. connection_write_to_buf((char*)(cell->payload + RELAY_HEADER_SIZE),
  1402. rh.length, TO_CONN(conn));
  1403. if (!optimistic_data) {
  1404. /* Only send a SENDME if we're not getting optimistic data; otherwise
  1405. * a SENDME could arrive before the CONNECTED.
  1406. */
  1407. connection_edge_consider_sending_sendme(conn);
  1408. }
  1409. return 0;
  1410. case RELAY_COMMAND_END:
  1411. reason = rh.length > 0 ?
  1412. get_uint8(cell->payload+RELAY_HEADER_SIZE) : END_STREAM_REASON_MISC;
  1413. if (!conn) {
  1414. log_info(domain,"end cell (%s) dropped, unknown stream.",
  1415. stream_end_reason_to_string(reason));
  1416. return 0;
  1417. }
  1418. /* XXX add to this log_fn the exit node's nickname? */
  1419. log_info(domain,TOR_SOCKET_T_FORMAT": end cell (%s) for stream %d. "
  1420. "Removing stream.",
  1421. conn->base_.s,
  1422. stream_end_reason_to_string(reason),
  1423. conn->stream_id);
  1424. if (conn->base_.type == CONN_TYPE_AP) {
  1425. entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
  1426. if (entry_conn->socks_request &&
  1427. !entry_conn->socks_request->has_finished)
  1428. log_warn(LD_BUG,
  1429. "open stream hasn't sent socks answer yet? Closing.");
  1430. }
  1431. /* We just *got* an end; no reason to send one. */
  1432. conn->edge_has_sent_end = 1;
  1433. if (!conn->end_reason)
  1434. conn->end_reason = reason | END_STREAM_REASON_FLAG_REMOTE;
  1435. if (!conn->base_.marked_for_close) {
  1436. /* only mark it if not already marked. it's possible to
  1437. * get the 'end' right around when the client hangs up on us. */
  1438. connection_mark_and_flush(TO_CONN(conn));
  1439. }
  1440. return 0;
  1441. case RELAY_COMMAND_EXTEND:
  1442. case RELAY_COMMAND_EXTEND2: {
  1443. static uint64_t total_n_extend=0, total_nonearly=0;
  1444. total_n_extend++;
  1445. if (rh.stream_id) {
  1446. log_fn(LOG_PROTOCOL_WARN, domain,
  1447. "'extend' cell received for non-zero stream. Dropping.");
  1448. return 0;
  1449. }
  1450. if (cell->command != CELL_RELAY_EARLY &&
  1451. !networkstatus_get_param(NULL,"AllowNonearlyExtend",0,0,1)) {
  1452. #define EARLY_WARNING_INTERVAL 3600
  1453. static ratelim_t early_warning_limit =
  1454. RATELIM_INIT(EARLY_WARNING_INTERVAL);
  1455. char *m;
  1456. if (cell->command == CELL_RELAY) {
  1457. ++total_nonearly;
  1458. if ((m = rate_limit_log(&early_warning_limit, approx_time()))) {
  1459. double percentage = ((double)total_nonearly)/total_n_extend;
  1460. percentage *= 100;
  1461. log_fn(LOG_PROTOCOL_WARN, domain, "EXTEND cell received, "
  1462. "but not via RELAY_EARLY. Dropping.%s", m);
  1463. log_fn(LOG_PROTOCOL_WARN, domain, " (We have dropped %.02f%% of "
  1464. "all EXTEND cells for this reason)", percentage);
  1465. tor_free(m);
  1466. }
  1467. } else {
  1468. log_fn(LOG_WARN, domain,
  1469. "EXTEND cell received, in a cell with type %d! Dropping.",
  1470. cell->command);
  1471. }
  1472. return 0;
  1473. }
  1474. return circuit_extend(cell, circ);
  1475. }
  1476. case RELAY_COMMAND_EXTENDED:
  1477. case RELAY_COMMAND_EXTENDED2:
  1478. if (!layer_hint) {
  1479. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1480. "'extended' unsupported at non-origin. Dropping.");
  1481. return 0;
  1482. }
  1483. log_debug(domain,"Got an extended cell! Yay.");
  1484. {
  1485. extended_cell_t extended_cell;
  1486. if (extended_cell_parse(&extended_cell, rh.command,
  1487. (const uint8_t*)cell->payload+RELAY_HEADER_SIZE,
  1488. rh.length)<0) {
  1489. log_warn(LD_PROTOCOL,
  1490. "Can't parse EXTENDED cell; killing circuit.");
  1491. return -END_CIRC_REASON_TORPROTOCOL;
  1492. }
  1493. if ((reason = circuit_finish_handshake(TO_ORIGIN_CIRCUIT(circ),
  1494. &extended_cell.created_cell)) < 0) {
  1495. log_warn(domain,"circuit_finish_handshake failed.");
  1496. return reason;
  1497. }
  1498. }
  1499. if ((reason=circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ)))<0) {
  1500. log_info(domain,"circuit_send_next_onion_skin() failed.");
  1501. return reason;
  1502. }
  1503. return 0;
  1504. case RELAY_COMMAND_TRUNCATE:
  1505. if (layer_hint) {
  1506. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  1507. "'truncate' unsupported at origin. Dropping.");
  1508. return 0;
  1509. }
  1510. if (circ->n_hop) {
  1511. if (circ->n_chan)
  1512. log_warn(LD_BUG, "n_chan and n_hop set on the same circuit!");
  1513. extend_info_free(circ->n_hop);
  1514. circ->n_hop = NULL;
  1515. tor_free(circ->n_chan_create_cell);
  1516. circuit_set_state(circ, CIRCUIT_STATE_OPEN);
  1517. }
  1518. if (circ->n_chan) {
  1519. uint8_t trunc_reason = get_uint8(cell->payload + RELAY_HEADER_SIZE);
  1520. circuit_clear_cell_queue(circ, circ->n_chan);
  1521. channel_send_destroy(circ->n_circ_id, circ->n_chan,
  1522. trunc_reason);
  1523. circuit_set_n_circid_chan(circ, 0, NULL);
  1524. }
  1525. log_debug(LD_EXIT, "Processed 'truncate', replying.");
  1526. {
  1527. char payload[1];
  1528. payload[0] = (char)END_CIRC_REASON_REQUESTED;
  1529. relay_send_command_from_edge(0, circ, RELAY_COMMAND_TRUNCATED,
  1530. payload, sizeof(payload), NULL);
  1531. }
  1532. return 0;
  1533. case RELAY_COMMAND_TRUNCATED:
  1534. if (!layer_hint) {
  1535. log_fn(LOG_PROTOCOL_WARN, LD_EXIT,
  1536. "'truncated' unsupported at non-origin. Dropping.");
  1537. return 0;
  1538. }
  1539. circuit_truncated(TO_ORIGIN_CIRCUIT(circ), layer_hint,
  1540. get_uint8(cell->payload + RELAY_HEADER_SIZE));
  1541. return 0;
  1542. case RELAY_COMMAND_CONNECTED:
  1543. if (conn) {
  1544. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1545. "'connected' unsupported while open. Closing circ.");
  1546. return -END_CIRC_REASON_TORPROTOCOL;
  1547. }
  1548. log_info(domain,
  1549. "'connected' received, no conn attached anymore. Ignoring.");
  1550. return 0;
  1551. case RELAY_COMMAND_SENDME:
  1552. if (!rh.stream_id) {
  1553. if (layer_hint) {
  1554. if (layer_hint->package_window + CIRCWINDOW_INCREMENT >
  1555. CIRCWINDOW_START_MAX) {
  1556. static struct ratelim_t exit_warn_ratelim = RATELIM_INIT(600);
  1557. log_fn_ratelim(&exit_warn_ratelim, LOG_WARN, LD_PROTOCOL,
  1558. "Unexpected sendme cell from exit relay. "
  1559. "Closing circ.");
  1560. return -END_CIRC_REASON_TORPROTOCOL;
  1561. }
  1562. layer_hint->package_window += CIRCWINDOW_INCREMENT;
  1563. log_debug(LD_APP,"circ-level sendme at origin, packagewindow %d.",
  1564. layer_hint->package_window);
  1565. circuit_resume_edge_reading(circ, layer_hint);
  1566. } else {
  1567. if (circ->package_window + CIRCWINDOW_INCREMENT >
  1568. CIRCWINDOW_START_MAX) {
  1569. static struct ratelim_t client_warn_ratelim = RATELIM_INIT(600);
  1570. log_fn_ratelim(&client_warn_ratelim, LOG_WARN, LD_PROTOCOL,
  1571. "Unexpected sendme cell from client. "
  1572. "Closing circ (window %d).",
  1573. circ->package_window);
  1574. return -END_CIRC_REASON_TORPROTOCOL;
  1575. }
  1576. circ->package_window += CIRCWINDOW_INCREMENT;
  1577. log_debug(LD_APP,
  1578. "circ-level sendme at non-origin, packagewindow %d.",
  1579. circ->package_window);
  1580. circuit_resume_edge_reading(circ, layer_hint);
  1581. }
  1582. return 0;
  1583. }
  1584. if (!conn) {
  1585. log_info(domain,"sendme cell dropped, unknown stream (streamid %d).",
  1586. rh.stream_id);
  1587. return 0;
  1588. }
  1589. conn->package_window += STREAMWINDOW_INCREMENT;
  1590. log_debug(domain,"stream-level sendme, packagewindow now %d.",
  1591. conn->package_window);
  1592. if (circuit_queue_streams_are_blocked(circ)) {
  1593. /* Still waiting for queue to flush; don't touch conn */
  1594. return 0;
  1595. }
  1596. connection_start_reading(TO_CONN(conn));
  1597. /* handle whatever might still be on the inbuf */
  1598. if (connection_edge_package_raw_inbuf(conn, 1, NULL) < 0) {
  1599. /* (We already sent an end cell if possible) */
  1600. connection_mark_for_close(TO_CONN(conn));
  1601. return 0;
  1602. }
  1603. return 0;
  1604. case RELAY_COMMAND_RESOLVE:
  1605. if (layer_hint) {
  1606. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  1607. "resolve request unsupported at AP; dropping.");
  1608. return 0;
  1609. } else if (conn) {
  1610. log_fn(LOG_PROTOCOL_WARN, domain,
  1611. "resolve request for known stream; dropping.");
  1612. return 0;
  1613. } else if (circ->purpose != CIRCUIT_PURPOSE_OR) {
  1614. log_fn(LOG_PROTOCOL_WARN, domain,
  1615. "resolve request on circ with purpose %d; dropping",
  1616. circ->purpose);
  1617. return 0;
  1618. }
  1619. connection_exit_begin_resolve(cell, TO_OR_CIRCUIT(circ));
  1620. return 0;
  1621. case RELAY_COMMAND_RESOLVED:
  1622. if (conn) {
  1623. log_fn(LOG_PROTOCOL_WARN, domain,
  1624. "'resolved' unsupported while open. Closing circ.");
  1625. return -END_CIRC_REASON_TORPROTOCOL;
  1626. }
  1627. log_info(domain,
  1628. "'resolved' received, no conn attached anymore. Ignoring.");
  1629. return 0;
  1630. case RELAY_COMMAND_ESTABLISH_INTRO:
  1631. case RELAY_COMMAND_ESTABLISH_RENDEZVOUS:
  1632. case RELAY_COMMAND_INTRODUCE1:
  1633. case RELAY_COMMAND_INTRODUCE2:
  1634. case RELAY_COMMAND_INTRODUCE_ACK:
  1635. case RELAY_COMMAND_RENDEZVOUS1:
  1636. case RELAY_COMMAND_RENDEZVOUS2:
  1637. case RELAY_COMMAND_INTRO_ESTABLISHED:
  1638. case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
  1639. rend_process_relay_cell(circ, layer_hint,
  1640. rh.command, rh.length,
  1641. cell->payload+RELAY_HEADER_SIZE);
  1642. return 0;
  1643. }
  1644. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  1645. "Received unknown relay command %d. Perhaps the other side is using "
  1646. "a newer version of Tor? Dropping.",
  1647. rh.command);
  1648. return 0; /* for forward compatibility, don't kill the circuit */
  1649. }
  1650. /** How many relay_data cells have we built, ever? */
  1651. uint64_t stats_n_data_cells_packaged = 0;
  1652. /** How many bytes of data have we put in relay_data cells have we built,
  1653. * ever? This would be RELAY_PAYLOAD_SIZE*stats_n_data_cells_packaged if
  1654. * every relay cell we ever sent were completely full of data. */
  1655. uint64_t stats_n_data_bytes_packaged = 0;
  1656. /** How many relay_data cells have we received, ever? */
  1657. uint64_t stats_n_data_cells_received = 0;
  1658. /** How many bytes of data have we received relay_data cells, ever? This would
  1659. * be RELAY_PAYLOAD_SIZE*stats_n_data_cells_packaged if every relay cell we
  1660. * ever received were completely full of data. */
  1661. uint64_t stats_n_data_bytes_received = 0;
  1662. /** If <b>conn</b> has an entire relay payload of bytes on its inbuf (or
  1663. * <b>package_partial</b> is true), and the appropriate package windows aren't
  1664. * empty, grab a cell and send it down the circuit.
  1665. *
  1666. * If *<b>max_cells</b> is given, package no more than max_cells. Decrement
  1667. * *<b>max_cells</b> by the number of cells packaged.
  1668. *
  1669. * Return -1 (and send a RELAY_COMMAND_END cell if necessary) if conn should
  1670. * be marked for close, else return 0.
  1671. */
  1672. int
  1673. connection_edge_package_raw_inbuf(edge_connection_t *conn, int package_partial,
  1674. int *max_cells)
  1675. {
  1676. size_t bytes_to_process, length;
  1677. char payload[CELL_PAYLOAD_SIZE];
  1678. circuit_t *circ;
  1679. const unsigned domain = conn->base_.type == CONN_TYPE_AP ? LD_APP : LD_EXIT;
  1680. int sending_from_optimistic = 0;
  1681. entry_connection_t *entry_conn =
  1682. conn->base_.type == CONN_TYPE_AP ? EDGE_TO_ENTRY_CONN(conn) : NULL;
  1683. const int sending_optimistically =
  1684. entry_conn &&
  1685. conn->base_.type == CONN_TYPE_AP &&
  1686. conn->base_.state != AP_CONN_STATE_OPEN;
  1687. crypt_path_t *cpath_layer = conn->cpath_layer;
  1688. tor_assert(conn);
  1689. if (conn->base_.marked_for_close) {
  1690. log_warn(LD_BUG,
  1691. "called on conn that's already marked for close at %s:%d.",
  1692. conn->base_.marked_for_close_file, conn->base_.marked_for_close);
  1693. return 0;
  1694. }
  1695. if (max_cells && *max_cells <= 0)
  1696. return 0;
  1697. repeat_connection_edge_package_raw_inbuf:
  1698. circ = circuit_get_by_edge_conn(conn);
  1699. if (!circ) {
  1700. log_info(domain,"conn has no circuit! Closing.");
  1701. conn->end_reason = END_STREAM_REASON_CANT_ATTACH;
  1702. return -1;
  1703. }
  1704. if (circuit_consider_stop_edge_reading(circ, cpath_layer))
  1705. return 0;
  1706. if (conn->package_window <= 0) {
  1707. log_info(domain,"called with package_window %d. Skipping.",
  1708. conn->package_window);
  1709. connection_stop_reading(TO_CONN(conn));
  1710. return 0;
  1711. }
  1712. sending_from_optimistic = entry_conn &&
  1713. entry_conn->sending_optimistic_data != NULL;
  1714. if (PREDICT_UNLIKELY(sending_from_optimistic)) {
  1715. bytes_to_process = generic_buffer_len(entry_conn->sending_optimistic_data);
  1716. if (PREDICT_UNLIKELY(!bytes_to_process)) {
  1717. log_warn(LD_BUG, "sending_optimistic_data was non-NULL but empty");
  1718. bytes_to_process = connection_get_inbuf_len(TO_CONN(conn));
  1719. sending_from_optimistic = 0;
  1720. }
  1721. } else {
  1722. bytes_to_process = connection_get_inbuf_len(TO_CONN(conn));
  1723. }
  1724. if (!bytes_to_process)
  1725. return 0;
  1726. if (!package_partial && bytes_to_process < RELAY_PAYLOAD_SIZE)
  1727. return 0;
  1728. if (bytes_to_process > RELAY_PAYLOAD_SIZE) {
  1729. length = RELAY_PAYLOAD_SIZE;
  1730. } else {
  1731. length = bytes_to_process;
  1732. }
  1733. stats_n_data_bytes_packaged += length;
  1734. stats_n_data_cells_packaged += 1;
  1735. if (PREDICT_UNLIKELY(sending_from_optimistic)) {
  1736. /* XXXX We could be more efficient here by sometimes packing
  1737. * previously-sent optimistic data in the same cell with data
  1738. * from the inbuf. */
  1739. generic_buffer_get(entry_conn->sending_optimistic_data, payload, length);
  1740. if (!generic_buffer_len(entry_conn->sending_optimistic_data)) {
  1741. generic_buffer_free(entry_conn->sending_optimistic_data);
  1742. entry_conn->sending_optimistic_data = NULL;
  1743. }
  1744. } else {
  1745. connection_fetch_from_buf(payload, length, TO_CONN(conn));
  1746. }
  1747. log_debug(domain,TOR_SOCKET_T_FORMAT": Packaging %d bytes (%d waiting).",
  1748. conn->base_.s,
  1749. (int)length, (int)connection_get_inbuf_len(TO_CONN(conn)));
  1750. if (sending_optimistically && !sending_from_optimistic) {
  1751. /* This is new optimistic data; remember it in case we need to detach and
  1752. retry */
  1753. if (!entry_conn->pending_optimistic_data)
  1754. entry_conn->pending_optimistic_data = generic_buffer_new();
  1755. generic_buffer_add(entry_conn->pending_optimistic_data, payload, length);
  1756. }
  1757. if (connection_edge_send_command(conn, RELAY_COMMAND_DATA,
  1758. payload, length) < 0 )
  1759. /* circuit got marked for close, don't continue, don't need to mark conn */
  1760. return 0;
  1761. if (!cpath_layer) { /* non-rendezvous exit */
  1762. tor_assert(circ->package_window > 0);
  1763. circ->package_window--;
  1764. } else { /* we're an AP, or an exit on a rendezvous circ */
  1765. tor_assert(cpath_layer->package_window > 0);
  1766. cpath_layer->package_window--;
  1767. }
  1768. if (--conn->package_window <= 0) { /* is it 0 after decrement? */
  1769. connection_stop_reading(TO_CONN(conn));
  1770. log_debug(domain,"conn->package_window reached 0.");
  1771. circuit_consider_stop_edge_reading(circ, cpath_layer);
  1772. return 0; /* don't process the inbuf any more */
  1773. }
  1774. log_debug(domain,"conn->package_window is now %d",conn->package_window);
  1775. if (max_cells) {
  1776. *max_cells -= 1;
  1777. if (*max_cells <= 0)
  1778. return 0;
  1779. }
  1780. /* handle more if there's more, or return 0 if there isn't */
  1781. goto repeat_connection_edge_package_raw_inbuf;
  1782. }
  1783. /** Called when we've just received a relay data cell, when
  1784. * we've just finished flushing all bytes to stream <b>conn</b>,
  1785. * or when we've flushed *some* bytes to the stream <b>conn</b>.
  1786. *
  1787. * If conn->outbuf is not too full, and our deliver window is
  1788. * low, send back a suitable number of stream-level sendme cells.
  1789. */
  1790. void
  1791. connection_edge_consider_sending_sendme(edge_connection_t *conn)
  1792. {
  1793. circuit_t *circ;
  1794. if (connection_outbuf_too_full(TO_CONN(conn)))
  1795. return;
  1796. circ = circuit_get_by_edge_conn(conn);
  1797. if (!circ) {
  1798. /* this can legitimately happen if the destroy has already
  1799. * arrived and torn down the circuit */
  1800. log_info(LD_APP,"No circuit associated with conn. Skipping.");
  1801. return;
  1802. }
  1803. while (conn->deliver_window <= STREAMWINDOW_START - STREAMWINDOW_INCREMENT) {
  1804. log_debug(conn->base_.type == CONN_TYPE_AP ?LD_APP:LD_EXIT,
  1805. "Outbuf %d, Queuing stream sendme.",
  1806. (int)conn->base_.outbuf_flushlen);
  1807. conn->deliver_window += STREAMWINDOW_INCREMENT;
  1808. if (connection_edge_send_command(conn, RELAY_COMMAND_SENDME,
  1809. NULL, 0) < 0) {
  1810. log_warn(LD_APP,"connection_edge_send_command failed. Skipping.");
  1811. return; /* the circuit's closed, don't continue */
  1812. }
  1813. }
  1814. }
  1815. /** The circuit <b>circ</b> has received a circuit-level sendme
  1816. * (on hop <b>layer_hint</b>, if we're the OP). Go through all the
  1817. * attached streams and let them resume reading and packaging, if
  1818. * their stream windows allow it.
  1819. */
  1820. static void
  1821. circuit_resume_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
  1822. {
  1823. if (circuit_queue_streams_are_blocked(circ)) {
  1824. log_debug(layer_hint?LD_APP:LD_EXIT,"Too big queue, no resuming");
  1825. return;
  1826. }
  1827. log_debug(layer_hint?LD_APP:LD_EXIT,"resuming");
  1828. if (CIRCUIT_IS_ORIGIN(circ))
  1829. circuit_resume_edge_reading_helper(TO_ORIGIN_CIRCUIT(circ)->p_streams,
  1830. circ, layer_hint);
  1831. else
  1832. circuit_resume_edge_reading_helper(TO_OR_CIRCUIT(circ)->n_streams,
  1833. circ, layer_hint);
  1834. }
  1835. void
  1836. stream_choice_seed_weak_rng(void)
  1837. {
  1838. crypto_seed_weak_rng(&stream_choice_rng);
  1839. }
  1840. /** A helper function for circuit_resume_edge_reading() above.
  1841. * The arguments are the same, except that <b>conn</b> is the head
  1842. * of a linked list of edge streams that should each be considered.
  1843. */
  1844. static int
  1845. circuit_resume_edge_reading_helper(edge_connection_t *first_conn,
  1846. circuit_t *circ,
  1847. crypt_path_t *layer_hint)
  1848. {
  1849. edge_connection_t *conn;
  1850. int n_packaging_streams, n_streams_left;
  1851. int packaged_this_round;
  1852. int cells_on_queue;
  1853. int cells_per_conn;
  1854. edge_connection_t *chosen_stream = NULL;
  1855. int max_to_package;
  1856. if (first_conn == NULL) {
  1857. /* Don't bother to try to do the rest of this if there are no connections
  1858. * to resume. */
  1859. return 0;
  1860. }
  1861. /* How many cells do we have space for? It will be the minimum of
  1862. * the number needed to exhaust the package window, and the minimum
  1863. * needed to fill the cell queue. */
  1864. max_to_package = circ->package_window;
  1865. if (CIRCUIT_IS_ORIGIN(circ)) {
  1866. cells_on_queue = circ->n_chan_cells.n;
  1867. } else {
  1868. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  1869. cells_on_queue = or_circ->p_chan_cells.n;
  1870. }
  1871. if (CELL_QUEUE_HIGHWATER_SIZE - cells_on_queue < max_to_package)
  1872. max_to_package = CELL_QUEUE_HIGHWATER_SIZE - cells_on_queue;
  1873. /* Once we used to start listening on the streams in the order they
  1874. * appeared in the linked list. That leads to starvation on the
  1875. * streams that appeared later on the list, since the first streams
  1876. * would always get to read first. Instead, we just pick a random
  1877. * stream on the list, and enable reading for streams starting at that
  1878. * point (and wrapping around as if the list were circular). It would
  1879. * probably be better to actually remember which streams we've
  1880. * serviced in the past, but this is simple and effective. */
  1881. /* Select a stream uniformly at random from the linked list. We
  1882. * don't need cryptographic randomness here. */
  1883. {
  1884. int num_streams = 0;
  1885. for (conn = first_conn; conn; conn = conn->next_stream) {
  1886. num_streams++;
  1887. if (tor_weak_random_one_in_n(&stream_choice_rng, num_streams)) {
  1888. chosen_stream = conn;
  1889. }
  1890. /* Invariant: chosen_stream has been chosen uniformly at random from
  1891. * among the first num_streams streams on first_conn.
  1892. *
  1893. * (Note that we iterate over every stream on the circuit, so that after
  1894. * we've considered the first stream, we've chosen it with P=1; and
  1895. * after we consider the second stream, we've switched to it with P=1/2
  1896. * and stayed with the first stream with P=1/2; and after we've
  1897. * considered the third stream, we've switched to it with P=1/3 and
  1898. * remained with one of the first two streams with P=(2/3), giving each
  1899. * one P=(1/2)(2/3) )=(1/3).) */
  1900. }
  1901. }
  1902. /* Count how many non-marked streams there are that have anything on
  1903. * their inbuf, and enable reading on all of the connections. */
  1904. n_packaging_streams = 0;
  1905. /* Activate reading starting from the chosen stream */
  1906. for (conn=chosen_stream; conn; conn = conn->next_stream) {
  1907. /* Start reading for the streams starting from here */
  1908. if (conn->base_.marked_for_close || conn->package_window <= 0)
  1909. continue;
  1910. if (!layer_hint || conn->cpath_layer == layer_hint) {
  1911. connection_start_reading(TO_CONN(conn));
  1912. if (connection_get_inbuf_len(TO_CONN(conn)) > 0)
  1913. ++n_packaging_streams;
  1914. }
  1915. }
  1916. /* Go back and do the ones we skipped, circular-style */
  1917. for (conn = first_conn; conn != chosen_stream; conn = conn->next_stream) {
  1918. if (conn->base_.marked_for_close || conn->package_window <= 0)
  1919. continue;
  1920. if (!layer_hint || conn->cpath_layer == layer_hint) {
  1921. connection_start_reading(TO_CONN(conn));
  1922. if (connection_get_inbuf_len(TO_CONN(conn)) > 0)
  1923. ++n_packaging_streams;
  1924. }
  1925. }
  1926. if (n_packaging_streams == 0) /* avoid divide-by-zero */
  1927. return 0;
  1928. again:
  1929. cells_per_conn = CEIL_DIV(max_to_package, n_packaging_streams);
  1930. packaged_this_round = 0;
  1931. n_streams_left = 0;
  1932. /* Iterate over all connections. Package up to cells_per_conn cells on
  1933. * each. Update packaged_this_round with the total number of cells
  1934. * packaged, and n_streams_left with the number that still have data to
  1935. * package.
  1936. */
  1937. for (conn=first_conn; conn; conn=conn->next_stream) {
  1938. if (conn->base_.marked_for_close || conn->package_window <= 0)
  1939. continue;
  1940. if (!layer_hint || conn->cpath_layer == layer_hint) {
  1941. int n = cells_per_conn, r;
  1942. /* handle whatever might still be on the inbuf */
  1943. r = connection_edge_package_raw_inbuf(conn, 1, &n);
  1944. /* Note how many we packaged */
  1945. packaged_this_round += (cells_per_conn-n);
  1946. if (r<0) {
  1947. /* Problem while packaging. (We already sent an end cell if
  1948. * possible) */
  1949. connection_mark_for_close(TO_CONN(conn));
  1950. continue;
  1951. }
  1952. /* If there's still data to read, we'll be coming back to this stream. */
  1953. if (connection_get_inbuf_len(TO_CONN(conn)))
  1954. ++n_streams_left;
  1955. /* If the circuit won't accept any more data, return without looking
  1956. * at any more of the streams. Any connections that should be stopped
  1957. * have already been stopped by connection_edge_package_raw_inbuf. */
  1958. if (circuit_consider_stop_edge_reading(circ, layer_hint))
  1959. return -1;
  1960. /* XXXX should we also stop immediately if we fill up the cell queue?
  1961. * Probably. */
  1962. }
  1963. }
  1964. /* If we made progress, and we are willing to package more, and there are
  1965. * any streams left that want to package stuff... try again!
  1966. */
  1967. if (packaged_this_round && packaged_this_round < max_to_package &&
  1968. n_streams_left) {
  1969. max_to_package -= packaged_this_round;
  1970. n_packaging_streams = n_streams_left;
  1971. goto again;
  1972. }
  1973. return 0;
  1974. }
  1975. /** Check if the package window for <b>circ</b> is empty (at
  1976. * hop <b>layer_hint</b> if it's defined).
  1977. *
  1978. * If yes, tell edge streams to stop reading and return 1.
  1979. * Else return 0.
  1980. */
  1981. static int
  1982. circuit_consider_stop_edge_reading(circuit_t *circ, crypt_path_t *layer_hint)
  1983. {
  1984. edge_connection_t *conn = NULL;
  1985. unsigned domain = layer_hint ? LD_APP : LD_EXIT;
  1986. if (!layer_hint) {
  1987. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  1988. log_debug(domain,"considering circ->package_window %d",
  1989. circ->package_window);
  1990. if (circ->package_window <= 0) {
  1991. log_debug(domain,"yes, not-at-origin. stopped.");
  1992. for (conn = or_circ->n_streams; conn; conn=conn->next_stream)
  1993. connection_stop_reading(TO_CONN(conn));
  1994. return 1;
  1995. }
  1996. return 0;
  1997. }
  1998. /* else, layer hint is defined, use it */
  1999. log_debug(domain,"considering layer_hint->package_window %d",
  2000. layer_hint->package_window);
  2001. if (layer_hint->package_window <= 0) {
  2002. log_debug(domain,"yes, at-origin. stopped.");
  2003. for (conn = TO_ORIGIN_CIRCUIT(circ)->p_streams; conn;
  2004. conn=conn->next_stream) {
  2005. if (conn->cpath_layer == layer_hint)
  2006. connection_stop_reading(TO_CONN(conn));
  2007. }
  2008. return 1;
  2009. }
  2010. return 0;
  2011. }
  2012. /** Check if the deliver_window for circuit <b>circ</b> (at hop
  2013. * <b>layer_hint</b> if it's defined) is low enough that we should
  2014. * send a circuit-level sendme back down the circuit. If so, send
  2015. * enough sendmes that the window would be overfull if we sent any
  2016. * more.
  2017. */
  2018. static void
  2019. circuit_consider_sending_sendme(circuit_t *circ, crypt_path_t *layer_hint)
  2020. {
  2021. // log_fn(LOG_INFO,"Considering: layer_hint is %s",
  2022. // layer_hint ? "defined" : "null");
  2023. while ((layer_hint ? layer_hint->deliver_window : circ->deliver_window) <=
  2024. CIRCWINDOW_START - CIRCWINDOW_INCREMENT) {
  2025. log_debug(LD_CIRC,"Queuing circuit sendme.");
  2026. if (layer_hint)
  2027. layer_hint->deliver_window += CIRCWINDOW_INCREMENT;
  2028. else
  2029. circ->deliver_window += CIRCWINDOW_INCREMENT;
  2030. if (relay_send_command_from_edge(0, circ, RELAY_COMMAND_SENDME,
  2031. NULL, 0, layer_hint) < 0) {
  2032. log_warn(LD_CIRC,
  2033. "relay_send_command_from_edge failed. Circuit's closed.");
  2034. return; /* the circuit's closed, don't continue */
  2035. }
  2036. }
  2037. }
  2038. #ifdef ACTIVE_CIRCUITS_PARANOIA
  2039. #define assert_cmux_ok_paranoid(chan) \
  2040. assert_circuit_mux_okay(chan)
  2041. #else
  2042. #define assert_cmux_ok_paranoid(chan)
  2043. #endif
  2044. /** The total number of cells we have allocated from the memory pool. */
  2045. static size_t total_cells_allocated = 0;
  2046. /** A memory pool to allocate packed_cell_t objects. */
  2047. static mp_pool_t *cell_pool = NULL;
  2048. /** Allocate structures to hold cells. */
  2049. void
  2050. init_cell_pool(void)
  2051. {
  2052. tor_assert(!cell_pool);
  2053. cell_pool = mp_pool_new(sizeof(packed_cell_t), 128*1024);
  2054. }
  2055. /** Free all storage used to hold cells (and insertion times/commands if we
  2056. * measure cell statistics and/or if CELL_STATS events are enabled). */
  2057. void
  2058. free_cell_pool(void)
  2059. {
  2060. /* Maybe we haven't called init_cell_pool yet; need to check for it. */
  2061. if (cell_pool) {
  2062. mp_pool_destroy(cell_pool);
  2063. cell_pool = NULL;
  2064. }
  2065. }
  2066. /** Free excess storage in cell pool. */
  2067. void
  2068. clean_cell_pool(void)
  2069. {
  2070. tor_assert(cell_pool);
  2071. mp_pool_clean(cell_pool, 0, 1);
  2072. }
  2073. /** Release storage held by <b>cell</b>. */
  2074. static INLINE void
  2075. packed_cell_free_unchecked(packed_cell_t *cell)
  2076. {
  2077. --total_cells_allocated;
  2078. mp_pool_release(cell);
  2079. }
  2080. /** Allocate and return a new packed_cell_t. */
  2081. STATIC packed_cell_t *
  2082. packed_cell_new(void)
  2083. {
  2084. ++total_cells_allocated;
  2085. return mp_pool_get(cell_pool);
  2086. }
  2087. /** Return a packed cell used outside by channel_t lower layer */
  2088. void
  2089. packed_cell_free(packed_cell_t *cell)
  2090. {
  2091. if (!cell)
  2092. return;
  2093. packed_cell_free_unchecked(cell);
  2094. }
  2095. /** Log current statistics for cell pool allocation at log level
  2096. * <b>severity</b>. */
  2097. void
  2098. dump_cell_pool_usage(int severity)
  2099. {
  2100. circuit_t *c;
  2101. int n_circs = 0;
  2102. int n_cells = 0;
  2103. TOR_LIST_FOREACH(c, circuit_get_global_list(), head) {
  2104. n_cells += c->n_chan_cells.n;
  2105. if (!CIRCUIT_IS_ORIGIN(c))
  2106. n_cells += TO_OR_CIRCUIT(c)->p_chan_cells.n;
  2107. ++n_circs;
  2108. }
  2109. tor_log(severity, LD_MM,
  2110. "%d cells allocated on %d circuits. %d cells leaked.",
  2111. n_cells, n_circs, (int)total_cells_allocated - n_cells);
  2112. mp_pool_log_status(cell_pool, severity);
  2113. }
  2114. /** Allocate a new copy of packed <b>cell</b>. */
  2115. static INLINE packed_cell_t *
  2116. packed_cell_copy(const cell_t *cell, int wide_circ_ids)
  2117. {
  2118. packed_cell_t *c = packed_cell_new();
  2119. cell_pack(c, cell, wide_circ_ids);
  2120. return c;
  2121. }
  2122. /** Append <b>cell</b> to the end of <b>queue</b>. */
  2123. void
  2124. cell_queue_append(cell_queue_t *queue, packed_cell_t *cell)
  2125. {
  2126. TOR_SIMPLEQ_INSERT_TAIL(&queue->head, cell, next);
  2127. ++queue->n;
  2128. }
  2129. /** Append a newly allocated copy of <b>cell</b> to the end of the
  2130. * <b>exitward</b> (or app-ward) <b>queue</b> of <b>circ</b>. If
  2131. * <b>use_stats</b> is true, record statistics about the cell.
  2132. */
  2133. void
  2134. cell_queue_append_packed_copy(circuit_t *circ, cell_queue_t *queue,
  2135. int exitward, const cell_t *cell,
  2136. int wide_circ_ids, int use_stats)
  2137. {
  2138. struct timeval now;
  2139. packed_cell_t *copy = packed_cell_copy(cell, wide_circ_ids);
  2140. (void)circ;
  2141. (void)exitward;
  2142. (void)use_stats;
  2143. tor_gettimeofday_cached_monotonic(&now);
  2144. copy->inserted_time = (uint32_t)tv_to_msec(&now);
  2145. cell_queue_append(queue, copy);
  2146. }
  2147. /** Initialize <b>queue</b> as an empty cell queue. */
  2148. void
  2149. cell_queue_init(cell_queue_t *queue)
  2150. {
  2151. memset(queue, 0, sizeof(cell_queue_t));
  2152. TOR_SIMPLEQ_INIT(&queue->head);
  2153. }
  2154. /** Remove and free every cell in <b>queue</b>. */
  2155. void
  2156. cell_queue_clear(cell_queue_t *queue)
  2157. {
  2158. packed_cell_t *cell;
  2159. while ((cell = TOR_SIMPLEQ_FIRST(&queue->head))) {
  2160. TOR_SIMPLEQ_REMOVE_HEAD(&queue->head, next);
  2161. packed_cell_free_unchecked(cell);
  2162. }
  2163. TOR_SIMPLEQ_INIT(&queue->head);
  2164. queue->n = 0;
  2165. }
  2166. /** Extract and return the cell at the head of <b>queue</b>; return NULL if
  2167. * <b>queue</b> is empty. */
  2168. STATIC packed_cell_t *
  2169. cell_queue_pop(cell_queue_t *queue)
  2170. {
  2171. packed_cell_t *cell = TOR_SIMPLEQ_FIRST(&queue->head);
  2172. if (!cell)
  2173. return NULL;
  2174. TOR_SIMPLEQ_REMOVE_HEAD(&queue->head, next);
  2175. --queue->n;
  2176. return cell;
  2177. }
  2178. /** Return the total number of bytes used for each packed_cell in a queue.
  2179. * Approximate. */
  2180. size_t
  2181. packed_cell_mem_cost(void)
  2182. {
  2183. return sizeof(packed_cell_t) + MP_POOL_ITEM_OVERHEAD;
  2184. }
  2185. /** DOCDOC */
  2186. STATIC size_t
  2187. cell_queues_get_total_allocation(void)
  2188. {
  2189. return total_cells_allocated * packed_cell_mem_cost();
  2190. }
  2191. /** Check whether we've got too much space used for cells. If so,
  2192. * call the OOM handler and return 1. Otherwise, return 0. */
  2193. STATIC int
  2194. cell_queues_check_size(void)
  2195. {
  2196. size_t alloc = cell_queues_get_total_allocation();
  2197. alloc += buf_get_total_allocation();
  2198. if (alloc >= get_options()->MaxMemInQueues) {
  2199. circuits_handle_oom(alloc);
  2200. return 1;
  2201. }
  2202. return 0;
  2203. }
  2204. /**
  2205. * Update the number of cells available on the circuit's n_chan or p_chan's
  2206. * circuit mux.
  2207. */
  2208. void
  2209. update_circuit_on_cmux_(circuit_t *circ, cell_direction_t direction,
  2210. const char *file, int lineno)
  2211. {
  2212. channel_t *chan = NULL;
  2213. or_circuit_t *or_circ = NULL;
  2214. circuitmux_t *cmux = NULL;
  2215. tor_assert(circ);
  2216. /* Okay, get the channel */
  2217. if (direction == CELL_DIRECTION_OUT) {
  2218. chan = circ->n_chan;
  2219. } else {
  2220. or_circ = TO_OR_CIRCUIT(circ);
  2221. chan = or_circ->p_chan;
  2222. }
  2223. tor_assert(chan);
  2224. tor_assert(chan->cmux);
  2225. /* Now get the cmux */
  2226. cmux = chan->cmux;
  2227. /* Cmux sanity check */
  2228. if (! circuitmux_is_circuit_attached(cmux, circ)) {
  2229. log_warn(LD_BUG, "called on non-attachd circuit from %s:%d",
  2230. file, lineno);
  2231. return;
  2232. }
  2233. tor_assert(circuitmux_attached_circuit_direction(cmux, circ) == direction);
  2234. assert_cmux_ok_paranoid(chan);
  2235. /* Update the number of cells we have for the circuit mux */
  2236. if (direction == CELL_DIRECTION_OUT) {
  2237. circuitmux_set_num_cells(cmux, circ, circ->n_chan_cells.n);
  2238. } else {
  2239. circuitmux_set_num_cells(cmux, circ, or_circ->p_chan_cells.n);
  2240. }
  2241. assert_cmux_ok_paranoid(chan);
  2242. }
  2243. /** Remove all circuits from the cmux on <b>chan</b>.
  2244. *
  2245. * If <b>circuits_out</b> is non-NULL, add all detached circuits to
  2246. * <b>circuits_out</b>.
  2247. **/
  2248. void
  2249. channel_unlink_all_circuits(channel_t *chan, smartlist_t *circuits_out)
  2250. {
  2251. tor_assert(chan);
  2252. tor_assert(chan->cmux);
  2253. circuitmux_detach_all_circuits(chan->cmux, circuits_out);
  2254. chan->num_n_circuits = 0;
  2255. chan->num_p_circuits = 0;
  2256. }
  2257. /** Block (if <b>block</b> is true) or unblock (if <b>block</b> is false)
  2258. * every edge connection that is using <b>circ</b> to write to <b>chan</b>,
  2259. * and start or stop reading as appropriate.
  2260. *
  2261. * If <b>stream_id</b> is nonzero, block only the edge connection whose
  2262. * stream_id matches it.
  2263. *
  2264. * Returns the number of streams whose status we changed.
  2265. */
  2266. static int
  2267. set_streams_blocked_on_circ(circuit_t *circ, channel_t *chan,
  2268. int block, streamid_t stream_id)
  2269. {
  2270. edge_connection_t *edge = NULL;
  2271. int n = 0;
  2272. if (circ->n_chan == chan) {
  2273. circ->streams_blocked_on_n_chan = block;
  2274. if (CIRCUIT_IS_ORIGIN(circ))
  2275. edge = TO_ORIGIN_CIRCUIT(circ)->p_streams;
  2276. } else {
  2277. circ->streams_blocked_on_p_chan = block;
  2278. tor_assert(!CIRCUIT_IS_ORIGIN(circ));
  2279. edge = TO_OR_CIRCUIT(circ)->n_streams;
  2280. }
  2281. for (; edge; edge = edge->next_stream) {
  2282. connection_t *conn = TO_CONN(edge);
  2283. if (stream_id && edge->stream_id != stream_id)
  2284. continue;
  2285. if (edge->edge_blocked_on_circ != block) {
  2286. ++n;
  2287. edge->edge_blocked_on_circ = block;
  2288. }
  2289. if (!conn->read_event && !HAS_BUFFEREVENT(conn)) {
  2290. /* This connection is a placeholder for something; probably a DNS
  2291. * request. It can't actually stop or start reading.*/
  2292. continue;
  2293. }
  2294. if (block) {
  2295. if (connection_is_reading(conn))
  2296. connection_stop_reading(conn);
  2297. } else {
  2298. /* Is this right? */
  2299. if (!connection_is_reading(conn))
  2300. connection_start_reading(conn);
  2301. }
  2302. }
  2303. return n;
  2304. }
  2305. /** Extract the command from a packed cell. */
  2306. static uint8_t
  2307. packed_cell_get_command(const packed_cell_t *cell, int wide_circ_ids)
  2308. {
  2309. if (wide_circ_ids) {
  2310. return get_uint8(cell->body+4);
  2311. } else {
  2312. return get_uint8(cell->body+2);
  2313. }
  2314. }
  2315. /** Pull as many cells as possible (but no more than <b>max</b>) from the
  2316. * queue of the first active circuit on <b>chan</b>, and write them to
  2317. * <b>chan</b>-&gt;outbuf. Return the number of cells written. Advance
  2318. * the active circuit pointer to the next active circuit in the ring. */
  2319. int
  2320. channel_flush_from_first_active_circuit(channel_t *chan, int max)
  2321. {
  2322. circuitmux_t *cmux = NULL;
  2323. int n_flushed = 0;
  2324. cell_queue_t *queue, *destroy_queue=NULL;
  2325. circuit_t *circ;
  2326. or_circuit_t *or_circ;
  2327. int streams_blocked;
  2328. packed_cell_t *cell;
  2329. /* Get the cmux */
  2330. tor_assert(chan);
  2331. tor_assert(chan->cmux);
  2332. cmux = chan->cmux;
  2333. /* Main loop: pick a circuit, send a cell, update the cmux */
  2334. while (n_flushed < max) {
  2335. circ = circuitmux_get_first_active_circuit(cmux, &destroy_queue);
  2336. if (destroy_queue) {
  2337. /* this code is duplicated from some of the logic below. Ugly! XXXX */
  2338. tor_assert(destroy_queue->n > 0);
  2339. cell = cell_queue_pop(destroy_queue);
  2340. channel_write_packed_cell(chan, cell);
  2341. /* Update the cmux destroy counter */
  2342. circuitmux_notify_xmit_destroy(cmux);
  2343. cell = NULL;
  2344. ++n_flushed;
  2345. continue;
  2346. }
  2347. /* If it returns NULL, no cells left to send */
  2348. if (!circ) break;
  2349. assert_cmux_ok_paranoid(chan);
  2350. if (circ->n_chan == chan) {
  2351. queue = &circ->n_chan_cells;
  2352. streams_blocked = circ->streams_blocked_on_n_chan;
  2353. } else {
  2354. or_circ = TO_OR_CIRCUIT(circ);
  2355. tor_assert(or_circ->p_chan == chan);
  2356. queue = &TO_OR_CIRCUIT(circ)->p_chan_cells;
  2357. streams_blocked = circ->streams_blocked_on_p_chan;
  2358. }
  2359. /* Circuitmux told us this was active, so it should have cells */
  2360. tor_assert(queue->n > 0);
  2361. /*
  2362. * Get just one cell here; once we've sent it, that can change the circuit
  2363. * selection, so we have to loop around for another even if this circuit
  2364. * has more than one.
  2365. */
  2366. cell = cell_queue_pop(queue);
  2367. /* Calculate the exact time that this cell has spent in the queue. */
  2368. if (get_options()->CellStatistics ||
  2369. get_options()->TestingEnableCellStatsEvent) {
  2370. uint32_t msec_waiting;
  2371. struct timeval tvnow;
  2372. tor_gettimeofday_cached(&tvnow);
  2373. msec_waiting = ((uint32_t)tv_to_msec(&tvnow)) - cell->inserted_time;
  2374. if (get_options()->CellStatistics && !CIRCUIT_IS_ORIGIN(circ)) {
  2375. or_circ = TO_OR_CIRCUIT(circ);
  2376. or_circ->total_cell_waiting_time += msec_waiting;
  2377. or_circ->processed_cells++;
  2378. }
  2379. if (get_options()->TestingEnableCellStatsEvent) {
  2380. uint8_t command = packed_cell_get_command(cell, chan->wide_circ_ids);
  2381. testing_cell_stats_entry_t *ent =
  2382. tor_malloc_zero(sizeof(testing_cell_stats_entry_t));
  2383. ent->command = command;
  2384. ent->waiting_time = msec_waiting / 10;
  2385. ent->removed = 1;
  2386. if (circ->n_chan == chan)
  2387. ent->exitward = 1;
  2388. if (!circ->testing_cell_stats)
  2389. circ->testing_cell_stats = smartlist_new();
  2390. smartlist_add(circ->testing_cell_stats, ent);
  2391. }
  2392. }
  2393. /* If we just flushed our queue and this circuit is used for a
  2394. * tunneled directory request, possibly advance its state. */
  2395. if (queue->n == 0 && chan->dirreq_id)
  2396. geoip_change_dirreq_state(chan->dirreq_id,
  2397. DIRREQ_TUNNELED,
  2398. DIRREQ_CIRC_QUEUE_FLUSHED);
  2399. /* Now send the cell */
  2400. channel_write_packed_cell(chan, cell);
  2401. cell = NULL;
  2402. /*
  2403. * Don't packed_cell_free_unchecked(cell) here because the channel will
  2404. * do so when it gets out of the channel queue (probably already did, in
  2405. * which case that was an immediate double-free bug).
  2406. */
  2407. /* Update the counter */
  2408. ++n_flushed;
  2409. /*
  2410. * Now update the cmux; tell it we've just sent a cell, and how many
  2411. * we have left.
  2412. */
  2413. circuitmux_notify_xmit_cells(cmux, circ, 1);
  2414. circuitmux_set_num_cells(cmux, circ, queue->n);
  2415. if (queue->n == 0)
  2416. log_debug(LD_GENERAL, "Made a circuit inactive.");
  2417. /* Is the cell queue low enough to unblock all the streams that are waiting
  2418. * to write to this circuit? */
  2419. if (streams_blocked && queue->n <= CELL_QUEUE_LOWWATER_SIZE)
  2420. set_streams_blocked_on_circ(circ, chan, 0, 0); /* unblock streams */
  2421. /* If n_flushed < max still, loop around and pick another circuit */
  2422. }
  2423. /* Okay, we're done sending now */
  2424. assert_cmux_ok_paranoid(chan);
  2425. return n_flushed;
  2426. }
  2427. #if 0
  2428. /** Indicate the current preferred cap for middle circuits; zero disables
  2429. * the cap. Right now it's just a constant, ORCIRC_MAX_MIDDLE_CELLS, but
  2430. * the logic in append_cell_to_circuit_queue() is written to be correct
  2431. * if we want to base it on a consensus param or something that might change
  2432. * in the future.
  2433. */
  2434. static int
  2435. get_max_middle_cells(void)
  2436. {
  2437. return ORCIRC_MAX_MIDDLE_CELLS;
  2438. }
  2439. #endif
  2440. /** Add <b>cell</b> to the queue of <b>circ</b> writing to <b>chan</b>
  2441. * transmitting in <b>direction</b>. */
  2442. void
  2443. append_cell_to_circuit_queue(circuit_t *circ, channel_t *chan,
  2444. cell_t *cell, cell_direction_t direction,
  2445. streamid_t fromstream)
  2446. {
  2447. or_circuit_t *orcirc = NULL;
  2448. cell_queue_t *queue;
  2449. int streams_blocked;
  2450. #if 0
  2451. uint32_t tgt_max_middle_cells, p_len, n_len, tmp, hard_max_middle_cells;
  2452. #endif
  2453. int exitward;
  2454. if (circ->marked_for_close)
  2455. return;
  2456. exitward = (direction == CELL_DIRECTION_OUT);
  2457. if (exitward) {
  2458. queue = &circ->n_chan_cells;
  2459. streams_blocked = circ->streams_blocked_on_n_chan;
  2460. } else {
  2461. orcirc = TO_OR_CIRCUIT(circ);
  2462. queue = &orcirc->p_chan_cells;
  2463. streams_blocked = circ->streams_blocked_on_p_chan;
  2464. }
  2465. /*
  2466. * Disabling this for now because of a possible guard discovery attack
  2467. */
  2468. #if 0
  2469. /* Are we a middle circuit about to exceed ORCIRC_MAX_MIDDLE_CELLS? */
  2470. if ((circ->n_chan != NULL) && CIRCUIT_IS_ORCIRC(circ)) {
  2471. orcirc = TO_OR_CIRCUIT(circ);
  2472. if (orcirc->p_chan) {
  2473. /* We are a middle circuit if we have both n_chan and p_chan */
  2474. /* We'll need to know the current preferred maximum */
  2475. tgt_max_middle_cells = get_max_middle_cells();
  2476. if (tgt_max_middle_cells > 0) {
  2477. /* Do we need to initialize middle_max_cells? */
  2478. if (orcirc->max_middle_cells == 0) {
  2479. orcirc->max_middle_cells = tgt_max_middle_cells;
  2480. } else {
  2481. if (tgt_max_middle_cells > orcirc->max_middle_cells) {
  2482. /* If we want to increase the cap, we can do so right away */
  2483. orcirc->max_middle_cells = tgt_max_middle_cells;
  2484. } else if (tgt_max_middle_cells < orcirc->max_middle_cells) {
  2485. /*
  2486. * If we're shrinking the cap, we can't shrink past either queue;
  2487. * compare tgt_max_middle_cells rather than tgt_max_middle_cells *
  2488. * ORCIRC_MAX_MIDDLE_KILL_THRESH so the queues don't shrink enough
  2489. * to generate spurious warnings, either.
  2490. */
  2491. n_len = circ->n_chan_cells.n;
  2492. p_len = orcirc->p_chan_cells.n;
  2493. tmp = tgt_max_middle_cells;
  2494. if (tmp < n_len) tmp = n_len;
  2495. if (tmp < p_len) tmp = p_len;
  2496. orcirc->max_middle_cells = tmp;
  2497. }
  2498. /* else no change */
  2499. }
  2500. } else {
  2501. /* tgt_max_middle_cells == 0 indicates we should disable the cap */
  2502. orcirc->max_middle_cells = 0;
  2503. }
  2504. /* Now we know orcirc->max_middle_cells is set correctly */
  2505. if (orcirc->max_middle_cells > 0) {
  2506. hard_max_middle_cells =
  2507. (uint32_t)(((double)orcirc->max_middle_cells) *
  2508. ORCIRC_MAX_MIDDLE_KILL_THRESH);
  2509. if ((unsigned)queue->n + 1 >= hard_max_middle_cells) {
  2510. /* Queueing this cell would put queue over the kill theshold */
  2511. log_warn(LD_CIRC,
  2512. "Got a cell exceeding the hard cap of %u in the "
  2513. "%s direction on middle circ ID %u on chan ID "
  2514. U64_FORMAT "; killing the circuit.",
  2515. hard_max_middle_cells,
  2516. (direction == CELL_DIRECTION_OUT) ? "n" : "p",
  2517. (direction == CELL_DIRECTION_OUT) ?
  2518. circ->n_circ_id : orcirc->p_circ_id,
  2519. U64_PRINTF_ARG(
  2520. (direction == CELL_DIRECTION_OUT) ?
  2521. circ->n_chan->global_identifier :
  2522. orcirc->p_chan->global_identifier));
  2523. circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
  2524. return;
  2525. } else if ((unsigned)queue->n + 1 == orcirc->max_middle_cells) {
  2526. /* Only use ==, not >= for this test so we don't spam the log */
  2527. log_warn(LD_CIRC,
  2528. "While trying to queue a cell, reached the soft cap of %u "
  2529. "in the %s direction on middle circ ID %u "
  2530. "on chan ID " U64_FORMAT ".",
  2531. orcirc->max_middle_cells,
  2532. (direction == CELL_DIRECTION_OUT) ? "n" : "p",
  2533. (direction == CELL_DIRECTION_OUT) ?
  2534. circ->n_circ_id : orcirc->p_circ_id,
  2535. U64_PRINTF_ARG(
  2536. (direction == CELL_DIRECTION_OUT) ?
  2537. circ->n_chan->global_identifier :
  2538. orcirc->p_chan->global_identifier));
  2539. }
  2540. }
  2541. }
  2542. }
  2543. #endif
  2544. cell_queue_append_packed_copy(circ, queue, exitward, cell,
  2545. chan->wide_circ_ids, 1);
  2546. if (PREDICT_UNLIKELY(cell_queues_check_size())) {
  2547. /* We ran the OOM handler */
  2548. if (circ->marked_for_close)
  2549. return;
  2550. }
  2551. /* If we have too many cells on the circuit, we should stop reading from
  2552. * the edge streams for a while. */
  2553. if (!streams_blocked && queue->n >= CELL_QUEUE_HIGHWATER_SIZE)
  2554. set_streams_blocked_on_circ(circ, chan, 1, 0); /* block streams */
  2555. if (streams_blocked && fromstream) {
  2556. /* This edge connection is apparently not blocked; block it. */
  2557. set_streams_blocked_on_circ(circ, chan, 1, fromstream);
  2558. }
  2559. update_circuit_on_cmux(circ, direction);
  2560. if (queue->n == 1) {
  2561. /* This was the first cell added to the queue. We just made this
  2562. * circuit active. */
  2563. log_debug(LD_GENERAL, "Made a circuit active.");
  2564. }
  2565. if (!channel_has_queued_writes(chan)) {
  2566. /* There is no data at all waiting to be sent on the outbuf. Add a
  2567. * cell, so that we can notice when it gets flushed, flushed_some can
  2568. * get called, and we can start putting more data onto the buffer then.
  2569. */
  2570. log_debug(LD_GENERAL, "Primed a buffer.");
  2571. channel_flush_from_first_active_circuit(chan, 1);
  2572. }
  2573. }
  2574. /** Append an encoded value of <b>addr</b> to <b>payload_out</b>, which must
  2575. * have at least 18 bytes of free space. The encoding is, as specified in
  2576. * tor-spec.txt:
  2577. * RESOLVED_TYPE_IPV4 or RESOLVED_TYPE_IPV6 [1 byte]
  2578. * LENGTH [1 byte]
  2579. * ADDRESS [length bytes]
  2580. * Return the number of bytes added, or -1 on error */
  2581. int
  2582. append_address_to_payload(uint8_t *payload_out, const tor_addr_t *addr)
  2583. {
  2584. uint32_t a;
  2585. switch (tor_addr_family(addr)) {
  2586. case AF_INET:
  2587. payload_out[0] = RESOLVED_TYPE_IPV4;
  2588. payload_out[1] = 4;
  2589. a = tor_addr_to_ipv4n(addr);
  2590. memcpy(payload_out+2, &a, 4);
  2591. return 6;
  2592. case AF_INET6:
  2593. payload_out[0] = RESOLVED_TYPE_IPV6;
  2594. payload_out[1] = 16;
  2595. memcpy(payload_out+2, tor_addr_to_in6_addr8(addr), 16);
  2596. return 18;
  2597. case AF_UNSPEC:
  2598. default:
  2599. return -1;
  2600. }
  2601. }
  2602. /** Given <b>payload_len</b> bytes at <b>payload</b>, starting with an address
  2603. * encoded as by append_address_to_payload(), try to decode the address into
  2604. * *<b>addr_out</b>. Return the next byte in the payload after the address on
  2605. * success, or NULL on failure. */
  2606. const uint8_t *
  2607. decode_address_from_payload(tor_addr_t *addr_out, const uint8_t *payload,
  2608. int payload_len)
  2609. {
  2610. if (payload_len < 2)
  2611. return NULL;
  2612. if (payload_len < 2+payload[1])
  2613. return NULL;
  2614. switch (payload[0]) {
  2615. case RESOLVED_TYPE_IPV4:
  2616. if (payload[1] != 4)
  2617. return NULL;
  2618. tor_addr_from_ipv4n(addr_out, get_uint32(payload+2));
  2619. break;
  2620. case RESOLVED_TYPE_IPV6:
  2621. if (payload[1] != 16)
  2622. return NULL;
  2623. tor_addr_from_ipv6_bytes(addr_out, (char*)(payload+2));
  2624. break;
  2625. default:
  2626. tor_addr_make_unspec(addr_out);
  2627. break;
  2628. }
  2629. return payload + 2 + payload[1];
  2630. }
  2631. /** Remove all the cells queued on <b>circ</b> for <b>chan</b>. */
  2632. void
  2633. circuit_clear_cell_queue(circuit_t *circ, channel_t *chan)
  2634. {
  2635. cell_queue_t *queue;
  2636. cell_direction_t direction;
  2637. if (circ->n_chan == chan) {
  2638. queue = &circ->n_chan_cells;
  2639. direction = CELL_DIRECTION_OUT;
  2640. } else {
  2641. or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
  2642. tor_assert(orcirc->p_chan == chan);
  2643. queue = &orcirc->p_chan_cells;
  2644. direction = CELL_DIRECTION_IN;
  2645. }
  2646. /* Clear the queue */
  2647. cell_queue_clear(queue);
  2648. /* Update the cell counter in the cmux */
  2649. if (chan->cmux && circuitmux_is_circuit_attached(chan->cmux, circ))
  2650. update_circuit_on_cmux(circ, direction);
  2651. }
  2652. /** Fail with an assert if the circuit mux on chan is corrupt
  2653. */
  2654. void
  2655. assert_circuit_mux_okay(channel_t *chan)
  2656. {
  2657. tor_assert(chan);
  2658. tor_assert(chan->cmux);
  2659. circuitmux_assert_okay(chan->cmux);
  2660. }
  2661. /** Return 1 if we shouldn't restart reading on this circuit, even if
  2662. * we get a SENDME. Else return 0.
  2663. */
  2664. static int
  2665. circuit_queue_streams_are_blocked(circuit_t *circ)
  2666. {
  2667. if (CIRCUIT_IS_ORIGIN(circ)) {
  2668. return circ->streams_blocked_on_n_chan;
  2669. } else {
  2670. return circ->streams_blocked_on_p_chan;
  2671. }
  2672. }