relay.c 106 KB

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