relay.c 104 KB

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