relay.c 104 KB

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