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