relay.c 97 KB

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