connection.c 162 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858
  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 connection.c
  8. * \brief General high-level functions to handle reading and writing
  9. * on connections.
  10. **/
  11. #define CONNECTION_PRIVATE
  12. #include "or.h"
  13. #include "buffers.h"
  14. /*
  15. * Define this so we get channel internal functions, since we're implementing
  16. * part of a subclass (channel_tls_t).
  17. */
  18. #define TOR_CHANNEL_INTERNAL_
  19. #define CONNECTION_PRIVATE
  20. #include "channel.h"
  21. #include "channeltls.h"
  22. #include "circuitbuild.h"
  23. #include "circuitlist.h"
  24. #include "circuituse.h"
  25. #include "config.h"
  26. #include "connection.h"
  27. #include "connection_edge.h"
  28. #include "connection_or.h"
  29. #include "control.h"
  30. #include "cpuworker.h"
  31. #include "directory.h"
  32. #include "dirserv.h"
  33. #include "dns.h"
  34. #include "dnsserv.h"
  35. #include "entrynodes.h"
  36. #include "ext_orport.h"
  37. #include "geoip.h"
  38. #include "main.h"
  39. #include "policies.h"
  40. #include "reasons.h"
  41. #include "relay.h"
  42. #include "rendclient.h"
  43. #include "rendcommon.h"
  44. #include "rephist.h"
  45. #include "router.h"
  46. #include "transports.h"
  47. #include "routerparse.h"
  48. #include "transports.h"
  49. #ifdef USE_BUFFEREVENTS
  50. #include <event2/event.h>
  51. #endif
  52. #ifdef HAVE_PWD_H
  53. #include <pwd.h>
  54. #endif
  55. static connection_t *connection_listener_new(
  56. const struct sockaddr *listensockaddr,
  57. socklen_t listensocklen, int type,
  58. const char *address,
  59. const port_cfg_t *portcfg);
  60. static void connection_init(time_t now, connection_t *conn, int type,
  61. int socket_family);
  62. static int connection_init_accepted_conn(connection_t *conn,
  63. const listener_connection_t *listener);
  64. static int connection_handle_listener_read(connection_t *conn, int new_type);
  65. #ifndef USE_BUFFEREVENTS
  66. static int connection_bucket_should_increase(int bucket,
  67. or_connection_t *conn);
  68. #endif
  69. static int connection_finished_flushing(connection_t *conn);
  70. static int connection_flushed_some(connection_t *conn);
  71. static int connection_finished_connecting(connection_t *conn);
  72. static int connection_reached_eof(connection_t *conn);
  73. static int connection_read_to_buf(connection_t *conn, ssize_t *max_to_read,
  74. int *socket_error);
  75. static int connection_process_inbuf(connection_t *conn, int package_partial);
  76. static void client_check_address_changed(tor_socket_t sock);
  77. static void set_constrained_socket_buffers(tor_socket_t sock, int size);
  78. static const char *connection_proxy_state_to_string(int state);
  79. static int connection_read_https_proxy_response(connection_t *conn);
  80. static void connection_send_socks5_connect(connection_t *conn);
  81. static const char *proxy_type_to_string(int proxy_type);
  82. static int get_proxy_type(void);
  83. /** The last addresses that our network interface seemed to have been
  84. * binding to. We use this as one way to detect when our IP changes.
  85. *
  86. * XXX024 We should really use the entire list of interfaces here.
  87. **/
  88. static tor_addr_t *last_interface_ipv4 = NULL;
  89. /* DOCDOC last_interface_ipv6 */
  90. static tor_addr_t *last_interface_ipv6 = NULL;
  91. /** A list of tor_addr_t for addresses we've used in outgoing connections.
  92. * Used to detect IP address changes. */
  93. static smartlist_t *outgoing_addrs = NULL;
  94. #define CASE_ANY_LISTENER_TYPE \
  95. case CONN_TYPE_OR_LISTENER: \
  96. case CONN_TYPE_EXT_OR_LISTENER: \
  97. case CONN_TYPE_AP_LISTENER: \
  98. case CONN_TYPE_DIR_LISTENER: \
  99. case CONN_TYPE_CONTROL_LISTENER: \
  100. case CONN_TYPE_AP_TRANS_LISTENER: \
  101. case CONN_TYPE_AP_NATD_LISTENER: \
  102. case CONN_TYPE_AP_DNS_LISTENER
  103. /**************************************************************/
  104. /**
  105. * Return the human-readable name for the connection type <b>type</b>
  106. */
  107. const char *
  108. conn_type_to_string(int type)
  109. {
  110. static char buf[64];
  111. switch (type) {
  112. case CONN_TYPE_OR_LISTENER: return "OR listener";
  113. case CONN_TYPE_OR: return "OR";
  114. case CONN_TYPE_EXIT: return "Exit";
  115. case CONN_TYPE_AP_LISTENER: return "Socks listener";
  116. case CONN_TYPE_AP_TRANS_LISTENER:
  117. return "Transparent pf/netfilter listener";
  118. case CONN_TYPE_AP_NATD_LISTENER: return "Transparent natd listener";
  119. case CONN_TYPE_AP_DNS_LISTENER: return "DNS listener";
  120. case CONN_TYPE_AP: return "Socks";
  121. case CONN_TYPE_DIR_LISTENER: return "Directory listener";
  122. case CONN_TYPE_DIR: return "Directory";
  123. case CONN_TYPE_CPUWORKER: return "CPU worker";
  124. case CONN_TYPE_CONTROL_LISTENER: return "Control listener";
  125. case CONN_TYPE_CONTROL: return "Control";
  126. case CONN_TYPE_EXT_OR: return "Extended OR";
  127. case CONN_TYPE_EXT_OR_LISTENER: return "Extended OR listener";
  128. default:
  129. log_warn(LD_BUG, "unknown connection type %d", type);
  130. tor_snprintf(buf, sizeof(buf), "unknown [%d]", type);
  131. return buf;
  132. }
  133. }
  134. /**
  135. * Return the human-readable name for the connection state <b>state</b>
  136. * for the connection type <b>type</b>
  137. */
  138. const char *
  139. conn_state_to_string(int type, int state)
  140. {
  141. static char buf[96];
  142. switch (type) {
  143. CASE_ANY_LISTENER_TYPE:
  144. if (state == LISTENER_STATE_READY)
  145. return "ready";
  146. break;
  147. case CONN_TYPE_OR:
  148. switch (state) {
  149. case OR_CONN_STATE_CONNECTING: return "connect()ing";
  150. case OR_CONN_STATE_PROXY_HANDSHAKING: return "handshaking (proxy)";
  151. case OR_CONN_STATE_TLS_HANDSHAKING: return "handshaking (TLS)";
  152. case OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING:
  153. return "renegotiating (TLS, v2 handshake)";
  154. case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING:
  155. return "waiting for renegotiation or V3 handshake";
  156. case OR_CONN_STATE_OR_HANDSHAKING_V2:
  157. return "handshaking (Tor, v2 handshake)";
  158. case OR_CONN_STATE_OR_HANDSHAKING_V3:
  159. return "handshaking (Tor, v3 handshake)";
  160. case OR_CONN_STATE_OPEN: return "open";
  161. }
  162. break;
  163. case CONN_TYPE_EXT_OR:
  164. switch (state) {
  165. case EXT_OR_CONN_STATE_AUTH_WAIT_AUTH_TYPE:
  166. return "waiting for authentication type";
  167. case EXT_OR_CONN_STATE_AUTH_WAIT_CLIENT_NONCE:
  168. return "waiting for client nonce";
  169. case EXT_OR_CONN_STATE_AUTH_WAIT_CLIENT_HASH:
  170. return "waiting for client hash";
  171. case EXT_OR_CONN_STATE_OPEN: return "open";
  172. case EXT_OR_CONN_STATE_FLUSHING: return "flushing final OKAY";
  173. }
  174. break;
  175. case CONN_TYPE_EXIT:
  176. switch (state) {
  177. case EXIT_CONN_STATE_RESOLVING: return "waiting for dest info";
  178. case EXIT_CONN_STATE_CONNECTING: return "connecting";
  179. case EXIT_CONN_STATE_OPEN: return "open";
  180. case EXIT_CONN_STATE_RESOLVEFAILED: return "resolve failed";
  181. }
  182. break;
  183. case CONN_TYPE_AP:
  184. switch (state) {
  185. case AP_CONN_STATE_SOCKS_WAIT: return "waiting for socks info";
  186. case AP_CONN_STATE_NATD_WAIT: return "waiting for natd dest info";
  187. case AP_CONN_STATE_RENDDESC_WAIT: return "waiting for rendezvous desc";
  188. case AP_CONN_STATE_CONTROLLER_WAIT: return "waiting for controller";
  189. case AP_CONN_STATE_CIRCUIT_WAIT: return "waiting for circuit";
  190. case AP_CONN_STATE_CONNECT_WAIT: return "waiting for connect response";
  191. case AP_CONN_STATE_RESOLVE_WAIT: return "waiting for resolve response";
  192. case AP_CONN_STATE_OPEN: return "open";
  193. }
  194. break;
  195. case CONN_TYPE_DIR:
  196. switch (state) {
  197. case DIR_CONN_STATE_CONNECTING: return "connecting";
  198. case DIR_CONN_STATE_CLIENT_SENDING: return "client sending";
  199. case DIR_CONN_STATE_CLIENT_READING: return "client reading";
  200. case DIR_CONN_STATE_CLIENT_FINISHED: return "client finished";
  201. case DIR_CONN_STATE_SERVER_COMMAND_WAIT: return "waiting for command";
  202. case DIR_CONN_STATE_SERVER_WRITING: return "writing";
  203. }
  204. break;
  205. case CONN_TYPE_CPUWORKER:
  206. switch (state) {
  207. case CPUWORKER_STATE_IDLE: return "idle";
  208. case CPUWORKER_STATE_BUSY_ONION: return "busy with onion";
  209. }
  210. break;
  211. case CONN_TYPE_CONTROL:
  212. switch (state) {
  213. case CONTROL_CONN_STATE_OPEN: return "open (protocol v1)";
  214. case CONTROL_CONN_STATE_NEEDAUTH:
  215. return "waiting for authentication (protocol v1)";
  216. }
  217. break;
  218. }
  219. log_warn(LD_BUG, "unknown connection state %d (type %d)", state, type);
  220. tor_snprintf(buf, sizeof(buf),
  221. "unknown state [%d] on unknown [%s] connection",
  222. state, conn_type_to_string(type));
  223. return buf;
  224. }
  225. #ifdef USE_BUFFEREVENTS
  226. /** Return true iff the connection's type is one that can use a
  227. bufferevent-based implementation. */
  228. int
  229. connection_type_uses_bufferevent(connection_t *conn)
  230. {
  231. switch (conn->type) {
  232. case CONN_TYPE_AP:
  233. case CONN_TYPE_EXIT:
  234. case CONN_TYPE_DIR:
  235. case CONN_TYPE_CONTROL:
  236. case CONN_TYPE_OR:
  237. case CONN_TYPE_EXT_OR:
  238. case CONN_TYPE_CPUWORKER:
  239. return 1;
  240. default:
  241. return 0;
  242. }
  243. }
  244. #endif
  245. /** Allocate and return a new dir_connection_t, initialized as by
  246. * connection_init(). */
  247. dir_connection_t *
  248. dir_connection_new(int socket_family)
  249. {
  250. dir_connection_t *dir_conn = tor_malloc_zero(sizeof(dir_connection_t));
  251. connection_init(time(NULL), TO_CONN(dir_conn), CONN_TYPE_DIR, socket_family);
  252. return dir_conn;
  253. }
  254. /** Allocate and return a new or_connection_t, initialized as by
  255. * connection_init().
  256. *
  257. * Set timestamp_last_added_nonpadding to now.
  258. *
  259. * Assign a pseudorandom next_circ_id between 0 and 2**15.
  260. *
  261. * Initialize active_circuit_pqueue.
  262. *
  263. * Set active_circuit_pqueue_last_recalibrated to current cell_ewma tick.
  264. */
  265. or_connection_t *
  266. or_connection_new(int type, int socket_family)
  267. {
  268. or_connection_t *or_conn = tor_malloc_zero(sizeof(or_connection_t));
  269. time_t now = time(NULL);
  270. tor_assert(type == CONN_TYPE_OR || type == CONN_TYPE_EXT_OR);
  271. connection_init(now, TO_CONN(or_conn), type, socket_family);
  272. or_conn->timestamp_last_added_nonpadding = time(NULL);
  273. if (type == CONN_TYPE_EXT_OR)
  274. connection_or_set_ext_or_identifier(or_conn);
  275. return or_conn;
  276. }
  277. /** Allocate and return a new entry_connection_t, initialized as by
  278. * connection_init().
  279. *
  280. * Allocate space to store the socks_request.
  281. */
  282. entry_connection_t *
  283. entry_connection_new(int type, int socket_family)
  284. {
  285. entry_connection_t *entry_conn = tor_malloc_zero(sizeof(entry_connection_t));
  286. tor_assert(type == CONN_TYPE_AP);
  287. connection_init(time(NULL), ENTRY_TO_CONN(entry_conn), type, socket_family);
  288. entry_conn->socks_request = socks_request_new();
  289. /* If this is coming from a listener, we'll set it up based on the listener
  290. * in a little while. Otherwise, we're doing this as a linked connection
  291. * of some kind, and we should set it up here based on the socket family */
  292. if (socket_family == AF_INET)
  293. entry_conn->ipv4_traffic_ok = 1;
  294. else if (socket_family == AF_INET6)
  295. entry_conn->ipv6_traffic_ok = 1;
  296. return entry_conn;
  297. }
  298. /** Allocate and return a new edge_connection_t, initialized as by
  299. * connection_init(). */
  300. edge_connection_t *
  301. edge_connection_new(int type, int socket_family)
  302. {
  303. edge_connection_t *edge_conn = tor_malloc_zero(sizeof(edge_connection_t));
  304. tor_assert(type == CONN_TYPE_EXIT);
  305. connection_init(time(NULL), TO_CONN(edge_conn), type, socket_family);
  306. return edge_conn;
  307. }
  308. /** Allocate and return a new control_connection_t, initialized as by
  309. * connection_init(). */
  310. control_connection_t *
  311. control_connection_new(int socket_family)
  312. {
  313. control_connection_t *control_conn =
  314. tor_malloc_zero(sizeof(control_connection_t));
  315. connection_init(time(NULL),
  316. TO_CONN(control_conn), CONN_TYPE_CONTROL, socket_family);
  317. return control_conn;
  318. }
  319. /** Allocate and return a new listener_connection_t, initialized as by
  320. * connection_init(). */
  321. listener_connection_t *
  322. listener_connection_new(int type, int socket_family)
  323. {
  324. listener_connection_t *listener_conn =
  325. tor_malloc_zero(sizeof(listener_connection_t));
  326. connection_init(time(NULL), TO_CONN(listener_conn), type, socket_family);
  327. return listener_conn;
  328. }
  329. /** Allocate, initialize, and return a new connection_t subtype of <b>type</b>
  330. * to make or receive connections of address family <b>socket_family</b>. The
  331. * type should be one of the CONN_TYPE_* constants. */
  332. connection_t *
  333. connection_new(int type, int socket_family)
  334. {
  335. switch (type) {
  336. case CONN_TYPE_OR:
  337. case CONN_TYPE_EXT_OR:
  338. return TO_CONN(or_connection_new(type, socket_family));
  339. case CONN_TYPE_EXIT:
  340. return TO_CONN(edge_connection_new(type, socket_family));
  341. case CONN_TYPE_AP:
  342. return ENTRY_TO_CONN(entry_connection_new(type, socket_family));
  343. case CONN_TYPE_DIR:
  344. return TO_CONN(dir_connection_new(socket_family));
  345. case CONN_TYPE_CONTROL:
  346. return TO_CONN(control_connection_new(socket_family));
  347. CASE_ANY_LISTENER_TYPE:
  348. return TO_CONN(listener_connection_new(type, socket_family));
  349. default: {
  350. connection_t *conn = tor_malloc_zero(sizeof(connection_t));
  351. connection_init(time(NULL), conn, type, socket_family);
  352. return conn;
  353. }
  354. }
  355. }
  356. /** Initializes conn. (you must call connection_add() to link it into the main
  357. * array).
  358. *
  359. * Set conn-\>magic to the correct value.
  360. *
  361. * Set conn-\>type to <b>type</b>. Set conn-\>s and conn-\>conn_array_index to
  362. * -1 to signify they are not yet assigned.
  363. *
  364. * Initialize conn's timestamps to now.
  365. */
  366. static void
  367. connection_init(time_t now, connection_t *conn, int type, int socket_family)
  368. {
  369. static uint64_t n_connections_allocated = 1;
  370. switch (type) {
  371. case CONN_TYPE_OR:
  372. case CONN_TYPE_EXT_OR:
  373. conn->magic = OR_CONNECTION_MAGIC;
  374. break;
  375. case CONN_TYPE_EXIT:
  376. conn->magic = EDGE_CONNECTION_MAGIC;
  377. break;
  378. case CONN_TYPE_AP:
  379. conn->magic = ENTRY_CONNECTION_MAGIC;
  380. break;
  381. case CONN_TYPE_DIR:
  382. conn->magic = DIR_CONNECTION_MAGIC;
  383. break;
  384. case CONN_TYPE_CONTROL:
  385. conn->magic = CONTROL_CONNECTION_MAGIC;
  386. break;
  387. CASE_ANY_LISTENER_TYPE:
  388. conn->magic = LISTENER_CONNECTION_MAGIC;
  389. break;
  390. default:
  391. conn->magic = BASE_CONNECTION_MAGIC;
  392. break;
  393. }
  394. conn->s = TOR_INVALID_SOCKET; /* give it a default of 'not used' */
  395. conn->conn_array_index = -1; /* also default to 'not used' */
  396. conn->global_identifier = n_connections_allocated++;
  397. conn->type = type;
  398. conn->socket_family = socket_family;
  399. #ifndef USE_BUFFEREVENTS
  400. if (!connection_is_listener(conn)) {
  401. /* listeners never use their buf */
  402. conn->inbuf = buf_new();
  403. conn->outbuf = buf_new();
  404. }
  405. #endif
  406. conn->timestamp_created = now;
  407. conn->timestamp_lastread = now;
  408. conn->timestamp_lastwritten = now;
  409. }
  410. /** Create a link between <b>conn_a</b> and <b>conn_b</b>. */
  411. void
  412. connection_link_connections(connection_t *conn_a, connection_t *conn_b)
  413. {
  414. tor_assert(! SOCKET_OK(conn_a->s));
  415. tor_assert(! SOCKET_OK(conn_b->s));
  416. conn_a->linked = 1;
  417. conn_b->linked = 1;
  418. conn_a->linked_conn = conn_b;
  419. conn_b->linked_conn = conn_a;
  420. }
  421. /** Deallocate memory used by <b>conn</b>. Deallocate its buffers if
  422. * necessary, close its socket if necessary, and mark the directory as dirty
  423. * if <b>conn</b> is an OR or OP connection.
  424. */
  425. STATIC void
  426. connection_free_(connection_t *conn)
  427. {
  428. void *mem;
  429. size_t memlen;
  430. if (!conn)
  431. return;
  432. switch (conn->type) {
  433. case CONN_TYPE_OR:
  434. case CONN_TYPE_EXT_OR:
  435. tor_assert(conn->magic == OR_CONNECTION_MAGIC);
  436. mem = TO_OR_CONN(conn);
  437. memlen = sizeof(or_connection_t);
  438. break;
  439. case CONN_TYPE_AP:
  440. tor_assert(conn->magic == ENTRY_CONNECTION_MAGIC);
  441. mem = TO_ENTRY_CONN(conn);
  442. memlen = sizeof(entry_connection_t);
  443. break;
  444. case CONN_TYPE_EXIT:
  445. tor_assert(conn->magic == EDGE_CONNECTION_MAGIC);
  446. mem = TO_EDGE_CONN(conn);
  447. memlen = sizeof(edge_connection_t);
  448. break;
  449. case CONN_TYPE_DIR:
  450. tor_assert(conn->magic == DIR_CONNECTION_MAGIC);
  451. mem = TO_DIR_CONN(conn);
  452. memlen = sizeof(dir_connection_t);
  453. break;
  454. case CONN_TYPE_CONTROL:
  455. tor_assert(conn->magic == CONTROL_CONNECTION_MAGIC);
  456. mem = TO_CONTROL_CONN(conn);
  457. memlen = sizeof(control_connection_t);
  458. break;
  459. CASE_ANY_LISTENER_TYPE:
  460. tor_assert(conn->magic == LISTENER_CONNECTION_MAGIC);
  461. mem = TO_LISTENER_CONN(conn);
  462. memlen = sizeof(listener_connection_t);
  463. break;
  464. default:
  465. tor_assert(conn->magic == BASE_CONNECTION_MAGIC);
  466. mem = conn;
  467. memlen = sizeof(connection_t);
  468. break;
  469. }
  470. if (conn->linked) {
  471. log_info(LD_GENERAL, "Freeing linked %s connection [%s] with %d "
  472. "bytes on inbuf, %d on outbuf.",
  473. conn_type_to_string(conn->type),
  474. conn_state_to_string(conn->type, conn->state),
  475. (int)connection_get_inbuf_len(conn),
  476. (int)connection_get_outbuf_len(conn));
  477. }
  478. if (!connection_is_listener(conn)) {
  479. buf_free(conn->inbuf);
  480. buf_free(conn->outbuf);
  481. } else {
  482. if (conn->socket_family == AF_UNIX) {
  483. /* For now only control ports can be Unix domain sockets
  484. * and listeners at the same time */
  485. tor_assert(conn->type == CONN_TYPE_CONTROL_LISTENER);
  486. if (unlink(conn->address) < 0 && errno != ENOENT) {
  487. log_warn(LD_NET, "Could not unlink %s: %s", conn->address,
  488. strerror(errno));
  489. }
  490. }
  491. }
  492. tor_free(conn->address);
  493. if (connection_speaks_cells(conn)) {
  494. or_connection_t *or_conn = TO_OR_CONN(conn);
  495. tor_tls_free(or_conn->tls);
  496. or_conn->tls = NULL;
  497. or_handshake_state_free(or_conn->handshake_state);
  498. or_conn->handshake_state = NULL;
  499. tor_free(or_conn->nickname);
  500. if (or_conn->chan) {
  501. /* Owww, this shouldn't happen, but... */
  502. log_info(LD_CHANNEL,
  503. "Freeing orconn at %p, saw channel %p with ID "
  504. U64_FORMAT " left un-NULLed",
  505. or_conn, TLS_CHAN_TO_BASE(or_conn->chan),
  506. U64_PRINTF_ARG(
  507. TLS_CHAN_TO_BASE(or_conn->chan)->global_identifier));
  508. if (!(TLS_CHAN_TO_BASE(or_conn->chan)->state == CHANNEL_STATE_CLOSED ||
  509. TLS_CHAN_TO_BASE(or_conn->chan)->state == CHANNEL_STATE_ERROR)) {
  510. channel_close_for_error(TLS_CHAN_TO_BASE(or_conn->chan));
  511. }
  512. or_conn->chan->conn = NULL;
  513. or_conn->chan = NULL;
  514. }
  515. }
  516. if (conn->type == CONN_TYPE_AP) {
  517. entry_connection_t *entry_conn = TO_ENTRY_CONN(conn);
  518. tor_free(entry_conn->chosen_exit_name);
  519. tor_free(entry_conn->original_dest_address);
  520. if (entry_conn->socks_request)
  521. socks_request_free(entry_conn->socks_request);
  522. if (entry_conn->pending_optimistic_data) {
  523. generic_buffer_free(entry_conn->pending_optimistic_data);
  524. }
  525. if (entry_conn->sending_optimistic_data) {
  526. generic_buffer_free(entry_conn->sending_optimistic_data);
  527. }
  528. }
  529. if (CONN_IS_EDGE(conn)) {
  530. rend_data_free(TO_EDGE_CONN(conn)->rend_data);
  531. }
  532. if (conn->type == CONN_TYPE_CONTROL) {
  533. control_connection_t *control_conn = TO_CONTROL_CONN(conn);
  534. tor_free(control_conn->safecookie_client_hash);
  535. tor_free(control_conn->incoming_cmd);
  536. }
  537. tor_free(conn->read_event); /* Probably already freed by connection_free. */
  538. tor_free(conn->write_event); /* Probably already freed by connection_free. */
  539. IF_HAS_BUFFEREVENT(conn, {
  540. /* This was a workaround to handle bugs in some old versions of libevent
  541. * where callbacks can occur after calling bufferevent_free(). Setting
  542. * the callbacks to NULL prevented this. It shouldn't be necessary any
  543. * more, but let's not tempt fate for now. */
  544. bufferevent_setcb(conn->bufev, NULL, NULL, NULL, NULL);
  545. bufferevent_free(conn->bufev);
  546. conn->bufev = NULL;
  547. });
  548. if (conn->type == CONN_TYPE_DIR) {
  549. dir_connection_t *dir_conn = TO_DIR_CONN(conn);
  550. tor_free(dir_conn->requested_resource);
  551. tor_zlib_free(dir_conn->zlib_state);
  552. if (dir_conn->fingerprint_stack) {
  553. SMARTLIST_FOREACH(dir_conn->fingerprint_stack, char *, cp, tor_free(cp));
  554. smartlist_free(dir_conn->fingerprint_stack);
  555. }
  556. cached_dir_decref(dir_conn->cached_dir);
  557. rend_data_free(dir_conn->rend_data);
  558. }
  559. if (SOCKET_OK(conn->s)) {
  560. log_debug(LD_NET,"closing fd %d.",(int)conn->s);
  561. tor_close_socket(conn->s);
  562. conn->s = TOR_INVALID_SOCKET;
  563. }
  564. if (conn->type == CONN_TYPE_OR &&
  565. !tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest)) {
  566. log_warn(LD_BUG, "called on OR conn with non-zeroed identity_digest");
  567. connection_or_remove_from_identity_map(TO_OR_CONN(conn));
  568. }
  569. if (conn->type == CONN_TYPE_OR || conn->type == CONN_TYPE_EXT_OR) {
  570. connection_or_remove_from_ext_or_id_map(TO_OR_CONN(conn));
  571. tor_free(TO_OR_CONN(conn)->ext_or_conn_id);
  572. tor_free(TO_OR_CONN(conn)->ext_or_auth_correct_client_hash);
  573. tor_free(TO_OR_CONN(conn)->ext_or_transport);
  574. }
  575. #ifdef USE_BUFFEREVENTS
  576. if (conn->type == CONN_TYPE_OR && TO_OR_CONN(conn)->bucket_cfg) {
  577. ev_token_bucket_cfg_free(TO_OR_CONN(conn)->bucket_cfg);
  578. TO_OR_CONN(conn)->bucket_cfg = NULL;
  579. }
  580. #endif
  581. memwipe(mem, 0xCC, memlen); /* poison memory */
  582. tor_free(mem);
  583. }
  584. /** Make sure <b>conn</b> isn't in any of the global conn lists; then free it.
  585. */
  586. void
  587. connection_free(connection_t *conn)
  588. {
  589. if (!conn)
  590. return;
  591. tor_assert(!connection_is_on_closeable_list(conn));
  592. tor_assert(!connection_in_array(conn));
  593. if (conn->linked_conn) {
  594. log_err(LD_BUG, "Called with conn->linked_conn still set.");
  595. tor_fragile_assert();
  596. conn->linked_conn->linked_conn = NULL;
  597. if (! conn->linked_conn->marked_for_close &&
  598. conn->linked_conn->reading_from_linked_conn)
  599. connection_start_reading(conn->linked_conn);
  600. conn->linked_conn = NULL;
  601. }
  602. if (connection_speaks_cells(conn)) {
  603. if (!tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest)) {
  604. connection_or_remove_from_identity_map(TO_OR_CONN(conn));
  605. }
  606. }
  607. if (conn->type == CONN_TYPE_CONTROL) {
  608. connection_control_closed(TO_CONTROL_CONN(conn));
  609. }
  610. connection_unregister_events(conn);
  611. connection_free_(conn);
  612. }
  613. /**
  614. * Called when we're about to finally unlink and free a connection:
  615. * perform necessary accounting and cleanup
  616. * - Directory conns that failed to fetch a rendezvous descriptor
  617. * need to inform pending rendezvous streams.
  618. * - OR conns need to call rep_hist_note_*() to record status.
  619. * - AP conns need to send a socks reject if necessary.
  620. * - Exit conns need to call connection_dns_remove() if necessary.
  621. * - AP and Exit conns need to send an end cell if they can.
  622. * - DNS conns need to fail any resolves that are pending on them.
  623. * - OR and edge connections need to be unlinked from circuits.
  624. */
  625. void
  626. connection_about_to_close_connection(connection_t *conn)
  627. {
  628. tor_assert(conn->marked_for_close);
  629. switch (conn->type) {
  630. case CONN_TYPE_DIR:
  631. connection_dir_about_to_close(TO_DIR_CONN(conn));
  632. break;
  633. case CONN_TYPE_OR:
  634. case CONN_TYPE_EXT_OR:
  635. connection_or_about_to_close(TO_OR_CONN(conn));
  636. break;
  637. case CONN_TYPE_AP:
  638. connection_ap_about_to_close(TO_ENTRY_CONN(conn));
  639. break;
  640. case CONN_TYPE_EXIT:
  641. connection_exit_about_to_close(TO_EDGE_CONN(conn));
  642. break;
  643. }
  644. }
  645. /** Return true iff connection_close_immediate() has been called on this
  646. * connection. */
  647. #define CONN_IS_CLOSED(c) \
  648. ((c)->linked ? ((c)->linked_conn_is_closed) : (! SOCKET_OK(c->s)))
  649. /** Close the underlying socket for <b>conn</b>, so we don't try to
  650. * flush it. Must be used in conjunction with (right before)
  651. * connection_mark_for_close().
  652. */
  653. void
  654. connection_close_immediate(connection_t *conn)
  655. {
  656. assert_connection_ok(conn,0);
  657. if (CONN_IS_CLOSED(conn)) {
  658. log_err(LD_BUG,"Attempt to close already-closed connection.");
  659. tor_fragile_assert();
  660. return;
  661. }
  662. if (conn->outbuf_flushlen) {
  663. log_info(LD_NET,"fd %d, type %s, state %s, %d bytes on outbuf.",
  664. (int)conn->s, conn_type_to_string(conn->type),
  665. conn_state_to_string(conn->type, conn->state),
  666. (int)conn->outbuf_flushlen);
  667. }
  668. connection_unregister_events(conn);
  669. if (SOCKET_OK(conn->s))
  670. tor_close_socket(conn->s);
  671. conn->s = TOR_INVALID_SOCKET;
  672. if (conn->linked)
  673. conn->linked_conn_is_closed = 1;
  674. if (conn->outbuf)
  675. buf_clear(conn->outbuf);
  676. conn->outbuf_flushlen = 0;
  677. }
  678. /** Mark <b>conn</b> to be closed next time we loop through
  679. * conn_close_if_marked() in main.c. */
  680. void
  681. connection_mark_for_close_(connection_t *conn, int line, const char *file)
  682. {
  683. assert_connection_ok(conn,0);
  684. tor_assert(line);
  685. tor_assert(line < 1<<16); /* marked_for_close can only fit a uint16_t. */
  686. tor_assert(file);
  687. if (conn->type == CONN_TYPE_OR) {
  688. /*
  689. * An or_connection should have been closed through one of the channel-
  690. * aware functions in connection_or.c. We'll assume this is an error
  691. * close and do that, and log a bug warning.
  692. */
  693. log_warn(LD_CHANNEL | LD_BUG,
  694. "Something tried to close an or_connection_t without going "
  695. "through channels at %s:%d",
  696. file, line);
  697. connection_or_close_for_error(TO_OR_CONN(conn), 0);
  698. } else {
  699. /* Pass it down to the real function */
  700. connection_mark_for_close_internal_(conn, line, file);
  701. }
  702. }
  703. /** Mark <b>conn</b> to be closed next time we loop through
  704. * conn_close_if_marked() in main.c; the _internal version bypasses the
  705. * CONN_TYPE_OR checks; this should be called when you either are sure that
  706. * if this is an or_connection_t the controlling channel has been notified
  707. * (e.g. with connection_or_notify_error()), or you actually are the
  708. * connection_or_close_for_error() or connection_or_close_normally function.
  709. * For all other cases, use connection_mark_and_flush() instead, which
  710. * checks for or_connection_t properly, instead. See below.
  711. */
  712. void
  713. connection_mark_for_close_internal_(connection_t *conn,
  714. int line, const char *file)
  715. {
  716. assert_connection_ok(conn,0);
  717. tor_assert(line);
  718. tor_assert(line < 1<<16); /* marked_for_close can only fit a uint16_t. */
  719. tor_assert(file);
  720. if (conn->marked_for_close) {
  721. log_warn(LD_BUG,"Duplicate call to connection_mark_for_close at %s:%d"
  722. " (first at %s:%d)", file, line, conn->marked_for_close_file,
  723. conn->marked_for_close);
  724. tor_fragile_assert();
  725. return;
  726. }
  727. if (conn->type == CONN_TYPE_OR) {
  728. /*
  729. * Bad news if this happens without telling the controlling channel; do
  730. * this so we can find things that call this wrongly when the asserts hit.
  731. */
  732. log_debug(LD_CHANNEL,
  733. "Calling connection_mark_for_close_internal_() on an OR conn "
  734. "at %s:%d",
  735. file, line);
  736. }
  737. conn->marked_for_close = line;
  738. conn->marked_for_close_file = file;
  739. add_connection_to_closeable_list(conn);
  740. /* in case we're going to be held-open-til-flushed, reset
  741. * the number of seconds since last successful write, so
  742. * we get our whole 15 seconds */
  743. conn->timestamp_lastwritten = time(NULL);
  744. }
  745. /** Find each connection that has hold_open_until_flushed set to
  746. * 1 but hasn't written in the past 15 seconds, and set
  747. * hold_open_until_flushed to 0. This means it will get cleaned
  748. * up in the next loop through close_if_marked() in main.c.
  749. */
  750. void
  751. connection_expire_held_open(void)
  752. {
  753. time_t now;
  754. smartlist_t *conns = get_connection_array();
  755. now = time(NULL);
  756. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  757. /* If we've been holding the connection open, but we haven't written
  758. * for 15 seconds...
  759. */
  760. if (conn->hold_open_until_flushed) {
  761. tor_assert(conn->marked_for_close);
  762. if (now - conn->timestamp_lastwritten >= 15) {
  763. int severity;
  764. if (conn->type == CONN_TYPE_EXIT ||
  765. (conn->type == CONN_TYPE_DIR &&
  766. conn->purpose == DIR_PURPOSE_SERVER))
  767. severity = LOG_INFO;
  768. else
  769. severity = LOG_NOTICE;
  770. log_fn(severity, LD_NET,
  771. "Giving up on marked_for_close conn that's been flushing "
  772. "for 15s (fd %d, type %s, state %s).",
  773. (int)conn->s, conn_type_to_string(conn->type),
  774. conn_state_to_string(conn->type, conn->state));
  775. conn->hold_open_until_flushed = 0;
  776. }
  777. }
  778. } SMARTLIST_FOREACH_END(conn);
  779. }
  780. #if defined(HAVE_SYS_UN_H) || defined(RUNNING_DOXYGEN)
  781. /** Create an AF_UNIX listenaddr struct.
  782. * <b>listenaddress</b> provides the path to the Unix socket.
  783. *
  784. * Eventually <b>listenaddress</b> will also optionally contain user, group,
  785. * and file permissions for the new socket. But not yet. XXX
  786. * Also, since we do not create the socket here the information doesn't help
  787. * here.
  788. *
  789. * If not NULL <b>readable_address</b> will contain a copy of the path part of
  790. * <b>listenaddress</b>.
  791. *
  792. * The listenaddr struct has to be freed by the caller.
  793. */
  794. static struct sockaddr_un *
  795. create_unix_sockaddr(const char *listenaddress, char **readable_address,
  796. socklen_t *len_out)
  797. {
  798. struct sockaddr_un *sockaddr = NULL;
  799. sockaddr = tor_malloc_zero(sizeof(struct sockaddr_un));
  800. sockaddr->sun_family = AF_UNIX;
  801. if (strlcpy(sockaddr->sun_path, listenaddress, sizeof(sockaddr->sun_path))
  802. >= sizeof(sockaddr->sun_path)) {
  803. log_warn(LD_CONFIG, "Unix socket path '%s' is too long to fit.",
  804. escaped(listenaddress));
  805. tor_free(sockaddr);
  806. return NULL;
  807. }
  808. if (readable_address)
  809. *readable_address = tor_strdup(listenaddress);
  810. *len_out = sizeof(struct sockaddr_un);
  811. return sockaddr;
  812. }
  813. #else
  814. static struct sockaddr *
  815. create_unix_sockaddr(const char *listenaddress, char **readable_address,
  816. socklen_t *len_out)
  817. {
  818. (void)listenaddress;
  819. (void)readable_address;
  820. log_fn(LOG_ERR, LD_BUG,
  821. "Unix domain sockets not supported, yet we tried to create one.");
  822. *len_out = 0;
  823. tor_fragile_assert();
  824. return NULL;
  825. }
  826. #endif /* HAVE_SYS_UN_H */
  827. /** Warn that an accept or a connect has failed because we're running up
  828. * against our ulimit. Rate-limit these warnings so that we don't spam
  829. * the log. */
  830. static void
  831. warn_too_many_conns(void)
  832. {
  833. #define WARN_TOO_MANY_CONNS_INTERVAL (6*60*60)
  834. static ratelim_t last_warned = RATELIM_INIT(WARN_TOO_MANY_CONNS_INTERVAL);
  835. char *m;
  836. if ((m = rate_limit_log(&last_warned, approx_time()))) {
  837. int n_conns = get_n_open_sockets();
  838. log_warn(LD_NET,"Failing because we have %d connections already. Please "
  839. "raise your ulimit -n.%s", n_conns, m);
  840. tor_free(m);
  841. control_event_general_status(LOG_WARN, "TOO_MANY_CONNECTIONS CURRENT=%d",
  842. n_conns);
  843. }
  844. }
  845. #ifdef HAVE_SYS_UN_H
  846. /** Check whether we should be willing to open an AF_UNIX socket in
  847. * <b>path</b>. Return 0 if we should go ahead and -1 if we shouldn't. */
  848. static int
  849. check_location_for_unix_socket(const or_options_t *options, const char *path)
  850. {
  851. int r = -1;
  852. char *p = tor_strdup(path);
  853. cpd_check_t flags = CPD_CHECK_MODE_ONLY;
  854. if (get_parent_directory(p)<0 || p[0] != '/') {
  855. log_warn(LD_GENERAL, "Bad unix socket address '%s'. Tor does not support "
  856. "relative paths for unix sockets.", path);
  857. goto done;
  858. }
  859. if (options->ControlSocketsGroupWritable)
  860. flags |= CPD_GROUP_OK;
  861. if (check_private_dir(p, flags, options->User) < 0) {
  862. char *escpath, *escdir;
  863. escpath = esc_for_log(path);
  864. escdir = esc_for_log(p);
  865. log_warn(LD_GENERAL, "Before Tor can create a control socket in %s, the "
  866. "directory %s needs to exist, and to be accessible only by the "
  867. "user%s account that is running Tor. (On some Unix systems, "
  868. "anybody who can list a socket can connect to it, so Tor is "
  869. "being careful.)", escpath, escdir,
  870. options->ControlSocketsGroupWritable ? " and group" : "");
  871. tor_free(escpath);
  872. tor_free(escdir);
  873. goto done;
  874. }
  875. r = 0;
  876. done:
  877. tor_free(p);
  878. return r;
  879. }
  880. #endif
  881. /** Tell the TCP stack that it shouldn't wait for a long time after
  882. * <b>sock</b> has closed before reusing its port. */
  883. static void
  884. make_socket_reuseable(tor_socket_t sock)
  885. {
  886. #ifdef _WIN32
  887. (void) sock;
  888. #else
  889. int one=1;
  890. /* REUSEADDR on normal places means you can rebind to the port
  891. * right after somebody else has let it go. But REUSEADDR on win32
  892. * means you can bind to the port _even when somebody else
  893. * already has it bound_. So, don't do that on Win32. */
  894. if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*) &one,
  895. (socklen_t)sizeof(one)) == -1) {
  896. log_warn(LD_NET, "Error setting SO_REUSEADDR flag: %s",
  897. tor_socket_strerror(errno));
  898. }
  899. #endif
  900. }
  901. /** Max backlog to pass to listen. We start at */
  902. static int listen_limit = INT_MAX;
  903. /* Listen on <b>fd</b> with appropriate backlog. Return as for listen. */
  904. static int
  905. tor_listen(tor_socket_t fd)
  906. {
  907. int r;
  908. if ((r = listen(fd, listen_limit)) < 0) {
  909. if (listen_limit == SOMAXCONN)
  910. return r;
  911. if ((r = listen(fd, SOMAXCONN)) == 0) {
  912. listen_limit = SOMAXCONN;
  913. log_warn(LD_NET, "Setting listen backlog to INT_MAX connections "
  914. "didn't work, but SOMAXCONN did. Lowering backlog limit.");
  915. }
  916. }
  917. return r;
  918. }
  919. /** Bind a new non-blocking socket listening to the socket described
  920. * by <b>listensockaddr</b>.
  921. *
  922. * <b>address</b> is only used for logging purposes and to add the information
  923. * to the conn.
  924. */
  925. static connection_t *
  926. connection_listener_new(const struct sockaddr *listensockaddr,
  927. socklen_t socklen,
  928. int type, const char *address,
  929. const port_cfg_t *port_cfg)
  930. {
  931. listener_connection_t *lis_conn;
  932. connection_t *conn = NULL;
  933. tor_socket_t s = TOR_INVALID_SOCKET; /* the socket we're going to make */
  934. or_options_t const *options = get_options();
  935. #if defined(HAVE_PWD_H) && defined(HAVE_SYS_UN_H)
  936. struct passwd *pw = NULL;
  937. #endif
  938. uint16_t usePort = 0, gotPort = 0;
  939. int start_reading = 0;
  940. static int global_next_session_group = SESSION_GROUP_FIRST_AUTO;
  941. tor_addr_t addr;
  942. if (get_n_open_sockets() >= get_options()->ConnLimit_-1) {
  943. warn_too_many_conns();
  944. return NULL;
  945. }
  946. if (listensockaddr->sa_family == AF_INET ||
  947. listensockaddr->sa_family == AF_INET6) {
  948. int is_tcp = (type != CONN_TYPE_AP_DNS_LISTENER);
  949. if (is_tcp)
  950. start_reading = 1;
  951. tor_addr_from_sockaddr(&addr, listensockaddr, &usePort);
  952. log_notice(LD_NET, "Opening %s on %s",
  953. conn_type_to_string(type), fmt_addrport(&addr, usePort));
  954. s = tor_open_socket_nonblocking(tor_addr_family(&addr),
  955. is_tcp ? SOCK_STREAM : SOCK_DGRAM,
  956. is_tcp ? IPPROTO_TCP: IPPROTO_UDP);
  957. if (!SOCKET_OK(s)) {
  958. log_warn(LD_NET,"Socket creation failed: %s",
  959. tor_socket_strerror(tor_socket_errno(-1)));
  960. goto err;
  961. }
  962. make_socket_reuseable(s);
  963. #if defined USE_TRANSPARENT && defined(IP_TRANSPARENT)
  964. if (options->TransProxyType_parsed == TPT_TPROXY &&
  965. type == CONN_TYPE_AP_TRANS_LISTENER) {
  966. int one = 1;
  967. if (setsockopt(s, SOL_IP, IP_TRANSPARENT, &one, sizeof(one)) < 0) {
  968. const char *extra = "";
  969. int e = tor_socket_errno(s);
  970. if (e == EPERM)
  971. extra = "TransTPROXY requires root privileges or similar"
  972. " capabilities.";
  973. log_warn(LD_NET, "Error setting IP_TRANSPARENT flag: %s.%s",
  974. tor_socket_strerror(e), extra);
  975. }
  976. }
  977. #endif
  978. #ifdef IPV6_V6ONLY
  979. if (listensockaddr->sa_family == AF_INET6) {
  980. #ifdef _WIN32
  981. /* In Redmond, this kind of thing passes for standards-conformance. */
  982. DWORD one = 1;
  983. #else
  984. int one = 1;
  985. #endif
  986. /* We need to set IPV6_V6ONLY so that this socket can't get used for
  987. * IPv4 connections. */
  988. if (setsockopt(s,IPPROTO_IPV6, IPV6_V6ONLY,
  989. (void*)&one, sizeof(one)) < 0) {
  990. int e = tor_socket_errno(s);
  991. log_warn(LD_NET, "Error setting IPV6_V6ONLY flag: %s",
  992. tor_socket_strerror(e));
  993. /* Keep going; probably not harmful. */
  994. }
  995. }
  996. #endif
  997. if (bind(s,listensockaddr,socklen) < 0) {
  998. const char *helpfulhint = "";
  999. int e = tor_socket_errno(s);
  1000. if (ERRNO_IS_EADDRINUSE(e))
  1001. helpfulhint = ". Is Tor already running?";
  1002. log_warn(LD_NET, "Could not bind to %s:%u: %s%s", address, usePort,
  1003. tor_socket_strerror(e), helpfulhint);
  1004. goto err;
  1005. }
  1006. if (is_tcp) {
  1007. if (tor_listen(s) < 0) {
  1008. log_warn(LD_NET, "Could not listen on %s:%u: %s", address, usePort,
  1009. tor_socket_strerror(tor_socket_errno(s)));
  1010. goto err;
  1011. }
  1012. }
  1013. if (usePort != 0) {
  1014. gotPort = usePort;
  1015. } else {
  1016. tor_addr_t addr2;
  1017. struct sockaddr_storage ss;
  1018. socklen_t ss_len=sizeof(ss);
  1019. if (getsockname(s, (struct sockaddr*)&ss, &ss_len)<0) {
  1020. log_warn(LD_NET, "getsockname() couldn't learn address for %s: %s",
  1021. conn_type_to_string(type),
  1022. tor_socket_strerror(tor_socket_errno(s)));
  1023. gotPort = 0;
  1024. }
  1025. tor_addr_from_sockaddr(&addr2, (struct sockaddr*)&ss, &gotPort);
  1026. }
  1027. #ifdef HAVE_SYS_UN_H
  1028. } else if (listensockaddr->sa_family == AF_UNIX) {
  1029. start_reading = 1;
  1030. /* For now only control ports can be Unix domain sockets
  1031. * and listeners at the same time */
  1032. tor_assert(type == CONN_TYPE_CONTROL_LISTENER);
  1033. if (check_location_for_unix_socket(options, address) < 0)
  1034. goto err;
  1035. log_notice(LD_NET, "Opening %s on %s",
  1036. conn_type_to_string(type), address);
  1037. tor_addr_make_unspec(&addr);
  1038. if (unlink(address) < 0 && errno != ENOENT) {
  1039. log_warn(LD_NET, "Could not unlink %s: %s", address,
  1040. strerror(errno));
  1041. goto err;
  1042. }
  1043. s = tor_open_socket_nonblocking(AF_UNIX, SOCK_STREAM, 0);
  1044. if (! SOCKET_OK(s)) {
  1045. log_warn(LD_NET,"Socket creation failed: %s.", strerror(errno));
  1046. goto err;
  1047. }
  1048. if (bind(s, listensockaddr, (socklen_t)sizeof(struct sockaddr_un)) == -1) {
  1049. log_warn(LD_NET,"Bind to %s failed: %s.", address,
  1050. tor_socket_strerror(tor_socket_errno(s)));
  1051. goto err;
  1052. }
  1053. #ifdef HAVE_PWD_H
  1054. if (options->User) {
  1055. pw = getpwnam(options->User);
  1056. if (pw == NULL) {
  1057. log_warn(LD_NET,"Unable to chown() %s socket: user %s not found.",
  1058. address, options->User);
  1059. goto err;
  1060. } else if (chown(address, pw->pw_uid, pw->pw_gid) < 0) {
  1061. log_warn(LD_NET,"Unable to chown() %s socket: %s.",
  1062. address, strerror(errno));
  1063. goto err;
  1064. }
  1065. }
  1066. #endif
  1067. if (options->ControlSocketsGroupWritable) {
  1068. /* We need to use chmod; fchmod doesn't work on sockets on all
  1069. * platforms. */
  1070. if (chmod(address, 0660) < 0) {
  1071. log_warn(LD_FS,"Unable to make %s group-writable.", address);
  1072. goto err;
  1073. }
  1074. }
  1075. if (listen(s, SOMAXCONN) < 0) {
  1076. log_warn(LD_NET, "Could not listen on %s: %s", address,
  1077. tor_socket_strerror(tor_socket_errno(s)));
  1078. goto err;
  1079. }
  1080. #else
  1081. (void)options;
  1082. #endif /* HAVE_SYS_UN_H */
  1083. } else {
  1084. log_err(LD_BUG, "Got unexpected address family %d.",
  1085. listensockaddr->sa_family);
  1086. tor_assert(0);
  1087. }
  1088. lis_conn = listener_connection_new(type, listensockaddr->sa_family);
  1089. conn = TO_CONN(lis_conn);
  1090. conn->socket_family = listensockaddr->sa_family;
  1091. conn->s = s;
  1092. s = TOR_INVALID_SOCKET; /* Prevent double-close */
  1093. conn->address = tor_strdup(address);
  1094. conn->port = gotPort;
  1095. tor_addr_copy(&conn->addr, &addr);
  1096. if (port_cfg->isolation_flags) {
  1097. lis_conn->isolation_flags = port_cfg->isolation_flags;
  1098. if (port_cfg->session_group >= 0) {
  1099. lis_conn->session_group = port_cfg->session_group;
  1100. } else {
  1101. /* This can wrap after around INT_MAX listeners are opened. But I don't
  1102. * believe that matters, since you would need to open a ridiculous
  1103. * number of listeners while keeping the early ones open before you ever
  1104. * hit this. An OR with a dozen ports open, for example, would have to
  1105. * close and re-open its listeners every second for 4 years nonstop.
  1106. */
  1107. lis_conn->session_group = global_next_session_group--;
  1108. }
  1109. }
  1110. if (type == CONN_TYPE_AP_LISTENER) {
  1111. lis_conn->socks_ipv4_traffic = port_cfg->ipv4_traffic;
  1112. lis_conn->socks_ipv6_traffic = port_cfg->ipv6_traffic;
  1113. lis_conn->socks_prefer_ipv6 = port_cfg->prefer_ipv6;
  1114. } else {
  1115. lis_conn->socks_ipv4_traffic = 1;
  1116. lis_conn->socks_ipv6_traffic = 1;
  1117. }
  1118. lis_conn->cache_ipv4_answers = port_cfg->cache_ipv4_answers;
  1119. lis_conn->cache_ipv6_answers = port_cfg->cache_ipv6_answers;
  1120. lis_conn->use_cached_ipv4_answers = port_cfg->use_cached_ipv4_answers;
  1121. lis_conn->use_cached_ipv6_answers = port_cfg->use_cached_ipv6_answers;
  1122. lis_conn->prefer_ipv6_virtaddr = port_cfg->prefer_ipv6_virtaddr;
  1123. lis_conn->socks_prefer_no_auth = port_cfg->socks_prefer_no_auth;
  1124. if (connection_add(conn) < 0) { /* no space, forget it */
  1125. log_warn(LD_NET,"connection_add for listener failed. Giving up.");
  1126. goto err;
  1127. }
  1128. log_fn(usePort==gotPort ? LOG_DEBUG : LOG_NOTICE, LD_NET,
  1129. "%s listening on port %u.",
  1130. conn_type_to_string(type), gotPort);
  1131. conn->state = LISTENER_STATE_READY;
  1132. if (start_reading) {
  1133. connection_start_reading(conn);
  1134. } else {
  1135. tor_assert(type == CONN_TYPE_AP_DNS_LISTENER);
  1136. dnsserv_configure_listener(conn);
  1137. }
  1138. return conn;
  1139. err:
  1140. if (SOCKET_OK(s))
  1141. tor_close_socket(s);
  1142. if (conn)
  1143. connection_free(conn);
  1144. return NULL;
  1145. }
  1146. /** Do basic sanity checking on a newly received socket. Return 0
  1147. * if it looks ok, else return -1.
  1148. *
  1149. * Notably, some TCP stacks can erroneously have accept() return successfully
  1150. * with socklen 0, when the client sends an RST before the accept call (as
  1151. * nmap does). We want to detect that, and not go on with the connection.
  1152. */
  1153. static int
  1154. check_sockaddr(const struct sockaddr *sa, int len, int level)
  1155. {
  1156. int ok = 1;
  1157. if (sa->sa_family == AF_INET) {
  1158. struct sockaddr_in *sin=(struct sockaddr_in*)sa;
  1159. if (len != sizeof(struct sockaddr_in)) {
  1160. log_fn(level, LD_NET, "Length of address not as expected: %d vs %d",
  1161. len,(int)sizeof(struct sockaddr_in));
  1162. ok = 0;
  1163. }
  1164. if (sin->sin_addr.s_addr == 0 || sin->sin_port == 0) {
  1165. log_fn(level, LD_NET,
  1166. "Address for new connection has address/port equal to zero.");
  1167. ok = 0;
  1168. }
  1169. } else if (sa->sa_family == AF_INET6) {
  1170. struct sockaddr_in6 *sin6=(struct sockaddr_in6*)sa;
  1171. if (len != sizeof(struct sockaddr_in6)) {
  1172. log_fn(level, LD_NET, "Length of address not as expected: %d vs %d",
  1173. len,(int)sizeof(struct sockaddr_in6));
  1174. ok = 0;
  1175. }
  1176. if (tor_mem_is_zero((void*)sin6->sin6_addr.s6_addr, 16) ||
  1177. sin6->sin6_port == 0) {
  1178. log_fn(level, LD_NET,
  1179. "Address for new connection has address/port equal to zero.");
  1180. ok = 0;
  1181. }
  1182. } else {
  1183. ok = 0;
  1184. }
  1185. return ok ? 0 : -1;
  1186. }
  1187. /** Check whether the socket family from an accepted socket <b>got</b> is the
  1188. * same as the one that <b>listener</b> is waiting for. If it isn't, log
  1189. * a useful message and return -1. Else return 0.
  1190. *
  1191. * This is annoying, but can apparently happen on some Darwins. */
  1192. static int
  1193. check_sockaddr_family_match(sa_family_t got, connection_t *listener)
  1194. {
  1195. if (got != listener->socket_family) {
  1196. log_info(LD_BUG, "A listener connection returned a socket with a "
  1197. "mismatched family. %s for addr_family %d gave us a socket "
  1198. "with address family %d. Dropping.",
  1199. conn_type_to_string(listener->type),
  1200. (int)listener->socket_family,
  1201. (int)got);
  1202. return -1;
  1203. }
  1204. return 0;
  1205. }
  1206. /** The listener connection <b>conn</b> told poll() it wanted to read.
  1207. * Call accept() on conn-\>s, and add the new connection if necessary.
  1208. */
  1209. static int
  1210. connection_handle_listener_read(connection_t *conn, int new_type)
  1211. {
  1212. tor_socket_t news; /* the new socket */
  1213. connection_t *newconn;
  1214. /* information about the remote peer when connecting to other routers */
  1215. struct sockaddr_storage addrbuf;
  1216. struct sockaddr *remote = (struct sockaddr*)&addrbuf;
  1217. /* length of the remote address. Must be whatever accept() needs. */
  1218. socklen_t remotelen = (socklen_t)sizeof(addrbuf);
  1219. const or_options_t *options = get_options();
  1220. tor_assert((size_t)remotelen >= sizeof(struct sockaddr_in));
  1221. memset(&addrbuf, 0, sizeof(addrbuf));
  1222. news = tor_accept_socket_nonblocking(conn->s,remote,&remotelen);
  1223. if (!SOCKET_OK(news)) { /* accept() error */
  1224. int e = tor_socket_errno(conn->s);
  1225. if (ERRNO_IS_ACCEPT_EAGAIN(e)) {
  1226. return 0; /* he hung up before we could accept(). that's fine. */
  1227. } else if (ERRNO_IS_ACCEPT_RESOURCE_LIMIT(e)) {
  1228. warn_too_many_conns();
  1229. return 0;
  1230. }
  1231. /* else there was a real error. */
  1232. log_warn(LD_NET,"accept() failed: %s. Closing listener.",
  1233. tor_socket_strerror(e));
  1234. connection_mark_for_close(conn);
  1235. return -1;
  1236. }
  1237. log_debug(LD_NET,
  1238. "Connection accepted on socket %d (child of fd %d).",
  1239. (int)news,(int)conn->s);
  1240. make_socket_reuseable(news);
  1241. if (options->ConstrainedSockets)
  1242. set_constrained_socket_buffers(news, (int)options->ConstrainedSockSize);
  1243. if (check_sockaddr_family_match(remote->sa_family, conn) < 0) {
  1244. tor_close_socket(news);
  1245. return 0;
  1246. }
  1247. if (conn->socket_family == AF_INET || conn->socket_family == AF_INET6) {
  1248. tor_addr_t addr;
  1249. uint16_t port;
  1250. if (check_sockaddr(remote, remotelen, LOG_INFO)<0) {
  1251. log_info(LD_NET,
  1252. "accept() returned a strange address; closing connection.");
  1253. tor_close_socket(news);
  1254. return 0;
  1255. }
  1256. tor_addr_from_sockaddr(&addr, remote, &port);
  1257. /* process entrance policies here, before we even create the connection */
  1258. if (new_type == CONN_TYPE_AP) {
  1259. /* check sockspolicy to see if we should accept it */
  1260. if (socks_policy_permits_address(&addr) == 0) {
  1261. log_notice(LD_APP,
  1262. "Denying socks connection from untrusted address %s.",
  1263. fmt_and_decorate_addr(&addr));
  1264. tor_close_socket(news);
  1265. return 0;
  1266. }
  1267. }
  1268. if (new_type == CONN_TYPE_DIR) {
  1269. /* check dirpolicy to see if we should accept it */
  1270. if (dir_policy_permits_address(&addr) == 0) {
  1271. log_notice(LD_DIRSERV,"Denying dir connection from address %s.",
  1272. fmt_and_decorate_addr(&addr));
  1273. tor_close_socket(news);
  1274. return 0;
  1275. }
  1276. }
  1277. newconn = connection_new(new_type, conn->socket_family);
  1278. newconn->s = news;
  1279. /* remember the remote address */
  1280. tor_addr_copy(&newconn->addr, &addr);
  1281. newconn->port = port;
  1282. newconn->address = tor_dup_addr(&addr);
  1283. if (new_type == CONN_TYPE_AP) {
  1284. TO_ENTRY_CONN(newconn)->socks_request->socks_prefer_no_auth =
  1285. TO_LISTENER_CONN(conn)->socks_prefer_no_auth;
  1286. }
  1287. if (new_type == CONN_TYPE_CONTROL) {
  1288. log_notice(LD_CONTROL, "New control connection opened from %s.",
  1289. fmt_and_decorate_addr(&addr));
  1290. }
  1291. } else if (conn->socket_family == AF_UNIX) {
  1292. /* For now only control ports can be Unix domain sockets
  1293. * and listeners at the same time */
  1294. tor_assert(conn->type == CONN_TYPE_CONTROL_LISTENER);
  1295. tor_assert(new_type == CONN_TYPE_CONTROL);
  1296. log_notice(LD_CONTROL, "New control connection opened.");
  1297. newconn = connection_new(new_type, conn->socket_family);
  1298. newconn->s = news;
  1299. /* remember the remote address -- do we have anything sane to put here? */
  1300. tor_addr_make_unspec(&newconn->addr);
  1301. newconn->port = 1;
  1302. newconn->address = tor_strdup(conn->address);
  1303. } else {
  1304. tor_assert(0);
  1305. };
  1306. if (connection_add(newconn) < 0) { /* no space, forget it */
  1307. connection_free(newconn);
  1308. return 0; /* no need to tear down the parent */
  1309. }
  1310. if (connection_init_accepted_conn(newconn, TO_LISTENER_CONN(conn)) < 0) {
  1311. if (! newconn->marked_for_close)
  1312. connection_mark_for_close(newconn);
  1313. return 0;
  1314. }
  1315. return 0;
  1316. }
  1317. /** Initialize states for newly accepted connection <b>conn</b>.
  1318. * If conn is an OR, start the TLS handshake.
  1319. * If conn is a transparent AP, get its original destination
  1320. * and place it in circuit_wait.
  1321. */
  1322. static int
  1323. connection_init_accepted_conn(connection_t *conn,
  1324. const listener_connection_t *listener)
  1325. {
  1326. int rv;
  1327. connection_start_reading(conn);
  1328. switch (conn->type) {
  1329. case CONN_TYPE_EXT_OR:
  1330. /* Initiate Extended ORPort authentication. */
  1331. return connection_ext_or_start_auth(TO_OR_CONN(conn));
  1332. case CONN_TYPE_OR:
  1333. control_event_or_conn_status(TO_OR_CONN(conn), OR_CONN_EVENT_NEW, 0);
  1334. rv = connection_tls_start_handshake(TO_OR_CONN(conn), 1);
  1335. if (rv < 0) {
  1336. connection_or_close_for_error(TO_OR_CONN(conn), 0);
  1337. }
  1338. return rv;
  1339. break;
  1340. case CONN_TYPE_AP:
  1341. TO_ENTRY_CONN(conn)->isolation_flags = listener->isolation_flags;
  1342. TO_ENTRY_CONN(conn)->session_group = listener->session_group;
  1343. TO_ENTRY_CONN(conn)->nym_epoch = get_signewnym_epoch();
  1344. TO_ENTRY_CONN(conn)->socks_request->listener_type = listener->base_.type;
  1345. TO_ENTRY_CONN(conn)->ipv4_traffic_ok = listener->socks_ipv4_traffic;
  1346. TO_ENTRY_CONN(conn)->ipv6_traffic_ok = listener->socks_ipv6_traffic;
  1347. TO_ENTRY_CONN(conn)->prefer_ipv6_traffic = listener->socks_prefer_ipv6;
  1348. TO_ENTRY_CONN(conn)->cache_ipv4_answers = listener->cache_ipv4_answers;
  1349. TO_ENTRY_CONN(conn)->cache_ipv6_answers = listener->cache_ipv6_answers;
  1350. TO_ENTRY_CONN(conn)->use_cached_ipv4_answers =
  1351. listener->use_cached_ipv4_answers;
  1352. TO_ENTRY_CONN(conn)->use_cached_ipv6_answers =
  1353. listener->use_cached_ipv6_answers;
  1354. TO_ENTRY_CONN(conn)->prefer_ipv6_virtaddr =
  1355. listener->prefer_ipv6_virtaddr;
  1356. switch (TO_CONN(listener)->type) {
  1357. case CONN_TYPE_AP_LISTENER:
  1358. conn->state = AP_CONN_STATE_SOCKS_WAIT;
  1359. break;
  1360. case CONN_TYPE_AP_TRANS_LISTENER:
  1361. TO_ENTRY_CONN(conn)->is_transparent_ap = 1;
  1362. conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  1363. return connection_ap_process_transparent(TO_ENTRY_CONN(conn));
  1364. case CONN_TYPE_AP_NATD_LISTENER:
  1365. TO_ENTRY_CONN(conn)->is_transparent_ap = 1;
  1366. conn->state = AP_CONN_STATE_NATD_WAIT;
  1367. break;
  1368. }
  1369. break;
  1370. case CONN_TYPE_DIR:
  1371. conn->purpose = DIR_PURPOSE_SERVER;
  1372. conn->state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
  1373. break;
  1374. case CONN_TYPE_CONTROL:
  1375. conn->state = CONTROL_CONN_STATE_NEEDAUTH;
  1376. break;
  1377. }
  1378. return 0;
  1379. }
  1380. /** Take conn, make a nonblocking socket; try to connect to
  1381. * addr:port (they arrive in *host order*). If fail, return -1 and if
  1382. * applicable put your best guess about errno into *<b>socket_error</b>.
  1383. * Else assign s to conn-\>s: if connected return 1, if EAGAIN return 0.
  1384. *
  1385. * address is used to make the logs useful.
  1386. *
  1387. * On success, add conn to the list of polled connections.
  1388. */
  1389. int
  1390. connection_connect(connection_t *conn, const char *address,
  1391. const tor_addr_t *addr, uint16_t port, int *socket_error)
  1392. {
  1393. tor_socket_t s;
  1394. int inprogress = 0;
  1395. struct sockaddr_storage addrbuf;
  1396. struct sockaddr *dest_addr;
  1397. int dest_addr_len;
  1398. const or_options_t *options = get_options();
  1399. int protocol_family;
  1400. if (get_n_open_sockets() >= get_options()->ConnLimit_-1) {
  1401. warn_too_many_conns();
  1402. *socket_error = SOCK_ERRNO(ENOBUFS);
  1403. return -1;
  1404. }
  1405. if (tor_addr_family(addr) == AF_INET6)
  1406. protocol_family = PF_INET6;
  1407. else
  1408. protocol_family = PF_INET;
  1409. if (get_options()->DisableNetwork) {
  1410. /* We should never even try to connect anyplace if DisableNetwork is set.
  1411. * Warn if we do, and refuse to make the connection. */
  1412. static ratelim_t disablenet_violated = RATELIM_INIT(30*60);
  1413. *socket_error = SOCK_ERRNO(ENETUNREACH);
  1414. log_fn_ratelim(&disablenet_violated, LOG_WARN, LD_BUG,
  1415. "Tried to open a socket with DisableNetwork set.");
  1416. tor_fragile_assert();
  1417. return -1;
  1418. }
  1419. s = tor_open_socket_nonblocking(protocol_family,SOCK_STREAM,IPPROTO_TCP);
  1420. if (! SOCKET_OK(s)) {
  1421. *socket_error = tor_socket_errno(-1);
  1422. log_warn(LD_NET,"Error creating network socket: %s",
  1423. tor_socket_strerror(*socket_error));
  1424. return -1;
  1425. }
  1426. make_socket_reuseable(s);
  1427. if (!tor_addr_is_loopback(addr)) {
  1428. const tor_addr_t *ext_addr = NULL;
  1429. if (protocol_family == AF_INET &&
  1430. !tor_addr_is_null(&options->OutboundBindAddressIPv4_))
  1431. ext_addr = &options->OutboundBindAddressIPv4_;
  1432. else if (protocol_family == AF_INET6 &&
  1433. !tor_addr_is_null(&options->OutboundBindAddressIPv6_))
  1434. ext_addr = &options->OutboundBindAddressIPv6_;
  1435. if (ext_addr) {
  1436. struct sockaddr_storage ext_addr_sa;
  1437. socklen_t ext_addr_len = 0;
  1438. memset(&ext_addr_sa, 0, sizeof(ext_addr_sa));
  1439. ext_addr_len = tor_addr_to_sockaddr(ext_addr, 0,
  1440. (struct sockaddr *) &ext_addr_sa,
  1441. sizeof(ext_addr_sa));
  1442. if (ext_addr_len == 0) {
  1443. log_warn(LD_NET,
  1444. "Error converting OutboundBindAddress %s into sockaddr. "
  1445. "Ignoring.", fmt_and_decorate_addr(ext_addr));
  1446. } else {
  1447. if (bind(s, (struct sockaddr *) &ext_addr_sa, ext_addr_len) < 0) {
  1448. *socket_error = tor_socket_errno(s);
  1449. log_warn(LD_NET,"Error binding network socket to %s: %s",
  1450. fmt_and_decorate_addr(ext_addr),
  1451. tor_socket_strerror(*socket_error));
  1452. tor_close_socket(s);
  1453. return -1;
  1454. }
  1455. }
  1456. }
  1457. }
  1458. if (options->ConstrainedSockets)
  1459. set_constrained_socket_buffers(s, (int)options->ConstrainedSockSize);
  1460. memset(&addrbuf,0,sizeof(addrbuf));
  1461. dest_addr = (struct sockaddr*) &addrbuf;
  1462. dest_addr_len = tor_addr_to_sockaddr(addr, port, dest_addr, sizeof(addrbuf));
  1463. tor_assert(dest_addr_len > 0);
  1464. log_debug(LD_NET, "Connecting to %s:%u.",
  1465. escaped_safe_str_client(address), port);
  1466. if (connect(s, dest_addr, (socklen_t)dest_addr_len) < 0) {
  1467. int e = tor_socket_errno(s);
  1468. if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
  1469. /* yuck. kill it. */
  1470. *socket_error = e;
  1471. log_info(LD_NET,
  1472. "connect() to %s:%u failed: %s",
  1473. escaped_safe_str_client(address),
  1474. port, tor_socket_strerror(e));
  1475. tor_close_socket(s);
  1476. return -1;
  1477. } else {
  1478. inprogress = 1;
  1479. }
  1480. }
  1481. /* it succeeded. we're connected. */
  1482. log_fn(inprogress?LOG_DEBUG:LOG_INFO, LD_NET,
  1483. "Connection to %s:%u %s (sock "TOR_SOCKET_T_FORMAT").",
  1484. escaped_safe_str_client(address),
  1485. port, inprogress?"in progress":"established", s);
  1486. conn->s = s;
  1487. if (connection_add_connecting(conn) < 0) {
  1488. /* no space, forget it */
  1489. *socket_error = SOCK_ERRNO(ENOBUFS);
  1490. return -1;
  1491. }
  1492. return inprogress ? 0 : 1;
  1493. }
  1494. /** Convert state number to string representation for logging purposes.
  1495. */
  1496. static const char *
  1497. connection_proxy_state_to_string(int state)
  1498. {
  1499. static const char *unknown = "???";
  1500. static const char *states[] = {
  1501. "PROXY_NONE",
  1502. "PROXY_INFANT",
  1503. "PROXY_HTTPS_WANT_CONNECT_OK",
  1504. "PROXY_SOCKS4_WANT_CONNECT_OK",
  1505. "PROXY_SOCKS5_WANT_AUTH_METHOD_NONE",
  1506. "PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929",
  1507. "PROXY_SOCKS5_WANT_AUTH_RFC1929_OK",
  1508. "PROXY_SOCKS5_WANT_CONNECT_OK",
  1509. "PROXY_CONNECTED",
  1510. };
  1511. if (state < PROXY_NONE || state > PROXY_CONNECTED)
  1512. return unknown;
  1513. return states[state];
  1514. }
  1515. /** Returns the global proxy type used by tor. Use this function for
  1516. * logging or high-level purposes, don't use it to fill the
  1517. * <b>proxy_type</b> field of or_connection_t; use the actual proxy
  1518. * protocol instead.*/
  1519. static int
  1520. get_proxy_type(void)
  1521. {
  1522. const or_options_t *options = get_options();
  1523. if (options->HTTPSProxy)
  1524. return PROXY_CONNECT;
  1525. else if (options->Socks4Proxy)
  1526. return PROXY_SOCKS4;
  1527. else if (options->Socks5Proxy)
  1528. return PROXY_SOCKS5;
  1529. else if (options->ClientTransportPlugin)
  1530. return PROXY_PLUGGABLE;
  1531. else
  1532. return PROXY_NONE;
  1533. }
  1534. /* One byte for the version, one for the command, two for the
  1535. port, and four for the addr... and, one more for the
  1536. username NUL: */
  1537. #define SOCKS4_STANDARD_BUFFER_SIZE (1 + 1 + 2 + 4 + 1)
  1538. /** Write a proxy request of <b>type</b> (socks4, socks5, https) to conn
  1539. * for conn->addr:conn->port, authenticating with the auth details given
  1540. * in the configuration (if available). SOCKS 5 and HTTP CONNECT proxies
  1541. * support authentication.
  1542. *
  1543. * Returns -1 if conn->addr is incompatible with the proxy protocol, and
  1544. * 0 otherwise.
  1545. *
  1546. * Use connection_read_proxy_handshake() to complete the handshake.
  1547. */
  1548. int
  1549. connection_proxy_connect(connection_t *conn, int type)
  1550. {
  1551. const or_options_t *options;
  1552. tor_assert(conn);
  1553. options = get_options();
  1554. switch (type) {
  1555. case PROXY_CONNECT: {
  1556. char buf[1024];
  1557. char *base64_authenticator=NULL;
  1558. const char *authenticator = options->HTTPSProxyAuthenticator;
  1559. /* Send HTTP CONNECT and authentication (if available) in
  1560. * one request */
  1561. if (authenticator) {
  1562. base64_authenticator = alloc_http_authenticator(authenticator);
  1563. if (!base64_authenticator)
  1564. log_warn(LD_OR, "Encoding https authenticator failed");
  1565. }
  1566. if (base64_authenticator) {
  1567. const char *addrport = fmt_addrport(&conn->addr, conn->port);
  1568. tor_snprintf(buf, sizeof(buf), "CONNECT %s HTTP/1.1\r\n"
  1569. "Host: %s\r\n"
  1570. "Proxy-Authorization: Basic %s\r\n\r\n",
  1571. addrport,
  1572. addrport,
  1573. base64_authenticator);
  1574. tor_free(base64_authenticator);
  1575. } else {
  1576. tor_snprintf(buf, sizeof(buf), "CONNECT %s HTTP/1.0\r\n\r\n",
  1577. fmt_addrport(&conn->addr, conn->port));
  1578. }
  1579. connection_write_to_buf(buf, strlen(buf), conn);
  1580. conn->proxy_state = PROXY_HTTPS_WANT_CONNECT_OK;
  1581. break;
  1582. }
  1583. case PROXY_SOCKS4: {
  1584. unsigned char *buf;
  1585. uint16_t portn;
  1586. uint32_t ip4addr;
  1587. size_t buf_size = 0;
  1588. char *socks_args_string = NULL;
  1589. /* Send a SOCKS4 connect request */
  1590. if (tor_addr_family(&conn->addr) != AF_INET) {
  1591. log_warn(LD_NET, "SOCKS4 client is incompatible with IPv6");
  1592. return -1;
  1593. }
  1594. { /* If we are here because we are trying to connect to a
  1595. pluggable transport proxy, check if we have any SOCKS
  1596. arguments to transmit. If we do, compress all arguments to
  1597. a single string in 'socks_args_string': */
  1598. if (get_proxy_type() == PROXY_PLUGGABLE) {
  1599. socks_args_string =
  1600. pt_get_socks_args_for_proxy_addrport(&conn->addr, conn->port);
  1601. if (socks_args_string)
  1602. log_debug(LD_NET, "Sending out '%s' as our SOCKS argument string.",
  1603. socks_args_string);
  1604. }
  1605. }
  1606. { /* Figure out the buffer size we need for the SOCKS message: */
  1607. buf_size = SOCKS4_STANDARD_BUFFER_SIZE;
  1608. /* If we have a SOCKS argument string, consider its size when
  1609. calculating the buffer size: */
  1610. if (socks_args_string)
  1611. buf_size += strlen(socks_args_string);
  1612. }
  1613. buf = tor_malloc_zero(buf_size);
  1614. ip4addr = tor_addr_to_ipv4n(&conn->addr);
  1615. portn = htons(conn->port);
  1616. buf[0] = 4; /* version */
  1617. buf[1] = SOCKS_COMMAND_CONNECT; /* command */
  1618. memcpy(buf + 2, &portn, 2); /* port */
  1619. memcpy(buf + 4, &ip4addr, 4); /* addr */
  1620. /* Next packet field is the userid. If we have pluggable
  1621. transport SOCKS arguments, we have to embed them
  1622. there. Otherwise, we use an empty userid. */
  1623. if (socks_args_string) { /* place the SOCKS args string: */
  1624. tor_assert(strlen(socks_args_string) > 0);
  1625. tor_assert(buf_size >=
  1626. SOCKS4_STANDARD_BUFFER_SIZE + strlen(socks_args_string));
  1627. strlcpy((char *)buf + 8, socks_args_string, buf_size - 8);
  1628. tor_free(socks_args_string);
  1629. } else {
  1630. buf[8] = 0; /* no userid */
  1631. }
  1632. connection_write_to_buf((char *)buf, buf_size, conn);
  1633. tor_free(buf);
  1634. conn->proxy_state = PROXY_SOCKS4_WANT_CONNECT_OK;
  1635. break;
  1636. }
  1637. case PROXY_SOCKS5: {
  1638. unsigned char buf[4]; /* fields: vers, num methods, method list */
  1639. /* Send a SOCKS5 greeting (connect request must wait) */
  1640. buf[0] = 5; /* version */
  1641. /* We have to use SOCKS5 authentication, if we have a
  1642. Socks5ProxyUsername or if we want to pass arguments to our
  1643. pluggable transport proxy: */
  1644. if ((options->Socks5ProxyUsername) ||
  1645. (get_proxy_type() == PROXY_PLUGGABLE &&
  1646. (get_socks_args_by_bridge_addrport(&conn->addr, conn->port)))) {
  1647. /* number of auth methods */
  1648. buf[1] = 2;
  1649. buf[2] = 0x00; /* no authentication */
  1650. buf[3] = 0x02; /* rfc1929 Username/Passwd auth */
  1651. conn->proxy_state = PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929;
  1652. } else {
  1653. buf[1] = 1;
  1654. buf[2] = 0x00; /* no authentication */
  1655. conn->proxy_state = PROXY_SOCKS5_WANT_AUTH_METHOD_NONE;
  1656. }
  1657. connection_write_to_buf((char *)buf, 2 + buf[1], conn);
  1658. break;
  1659. }
  1660. default:
  1661. log_err(LD_BUG, "Invalid proxy protocol, %d", type);
  1662. tor_fragile_assert();
  1663. return -1;
  1664. }
  1665. log_debug(LD_NET, "set state %s",
  1666. connection_proxy_state_to_string(conn->proxy_state));
  1667. return 0;
  1668. }
  1669. /** Read conn's inbuf. If the http response from the proxy is all
  1670. * here, make sure it's good news, then return 1. If it's bad news,
  1671. * return -1. Else return 0 and hope for better luck next time.
  1672. */
  1673. static int
  1674. connection_read_https_proxy_response(connection_t *conn)
  1675. {
  1676. char *headers;
  1677. char *reason=NULL;
  1678. int status_code;
  1679. time_t date_header;
  1680. switch (fetch_from_buf_http(conn->inbuf,
  1681. &headers, MAX_HEADERS_SIZE,
  1682. NULL, NULL, 10000, 0)) {
  1683. case -1: /* overflow */
  1684. log_warn(LD_PROTOCOL,
  1685. "Your https proxy sent back an oversized response. Closing.");
  1686. return -1;
  1687. case 0:
  1688. log_info(LD_NET,"https proxy response not all here yet. Waiting.");
  1689. return 0;
  1690. /* case 1, fall through */
  1691. }
  1692. if (parse_http_response(headers, &status_code, &date_header,
  1693. NULL, &reason) < 0) {
  1694. log_warn(LD_NET,
  1695. "Unparseable headers from proxy (connecting to '%s'). Closing.",
  1696. conn->address);
  1697. tor_free(headers);
  1698. return -1;
  1699. }
  1700. tor_free(headers);
  1701. if (!reason) reason = tor_strdup("[no reason given]");
  1702. if (status_code == 200) {
  1703. log_info(LD_NET,
  1704. "HTTPS connect to '%s' successful! (200 %s) Starting TLS.",
  1705. conn->address, escaped(reason));
  1706. tor_free(reason);
  1707. return 1;
  1708. }
  1709. /* else, bad news on the status code */
  1710. switch (status_code) {
  1711. case 403:
  1712. log_warn(LD_NET,
  1713. "The https proxy refused to allow connection to %s "
  1714. "(status code %d, %s). Closing.",
  1715. conn->address, status_code, escaped(reason));
  1716. break;
  1717. default:
  1718. log_warn(LD_NET,
  1719. "The https proxy sent back an unexpected status code %d (%s). "
  1720. "Closing.",
  1721. status_code, escaped(reason));
  1722. break;
  1723. }
  1724. tor_free(reason);
  1725. return -1;
  1726. }
  1727. /** Send SOCKS5 CONNECT command to <b>conn</b>, copying <b>conn->addr</b>
  1728. * and <b>conn->port</b> into the request.
  1729. */
  1730. static void
  1731. connection_send_socks5_connect(connection_t *conn)
  1732. {
  1733. unsigned char buf[1024];
  1734. size_t reqsize = 6;
  1735. uint16_t port = htons(conn->port);
  1736. buf[0] = 5; /* version */
  1737. buf[1] = SOCKS_COMMAND_CONNECT; /* command */
  1738. buf[2] = 0; /* reserved */
  1739. if (tor_addr_family(&conn->addr) == AF_INET) {
  1740. uint32_t addr = tor_addr_to_ipv4n(&conn->addr);
  1741. buf[3] = 1;
  1742. reqsize += 4;
  1743. memcpy(buf + 4, &addr, 4);
  1744. memcpy(buf + 8, &port, 2);
  1745. } else { /* AF_INET6 */
  1746. buf[3] = 4;
  1747. reqsize += 16;
  1748. memcpy(buf + 4, tor_addr_to_in6(&conn->addr), 16);
  1749. memcpy(buf + 20, &port, 2);
  1750. }
  1751. connection_write_to_buf((char *)buf, reqsize, conn);
  1752. conn->proxy_state = PROXY_SOCKS5_WANT_CONNECT_OK;
  1753. }
  1754. /** Wrapper around fetch_from_(buf/evbuffer)_socks_client: see those functions
  1755. * for documentation of its behavior. */
  1756. static int
  1757. connection_fetch_from_buf_socks_client(connection_t *conn,
  1758. int state, char **reason)
  1759. {
  1760. IF_HAS_BUFFEREVENT(conn, {
  1761. struct evbuffer *input = bufferevent_get_input(conn->bufev);
  1762. return fetch_from_evbuffer_socks_client(input, state, reason);
  1763. }) ELSE_IF_NO_BUFFEREVENT {
  1764. return fetch_from_buf_socks_client(conn->inbuf, state, reason);
  1765. }
  1766. }
  1767. /** Call this from connection_*_process_inbuf() to advance the proxy
  1768. * handshake.
  1769. *
  1770. * No matter what proxy protocol is used, if this function returns 1, the
  1771. * handshake is complete, and the data remaining on inbuf may contain the
  1772. * start of the communication with the requested server.
  1773. *
  1774. * Returns 0 if the current buffer contains an incomplete response, and -1
  1775. * on error.
  1776. */
  1777. int
  1778. connection_read_proxy_handshake(connection_t *conn)
  1779. {
  1780. int ret = 0;
  1781. char *reason = NULL;
  1782. log_debug(LD_NET, "enter state %s",
  1783. connection_proxy_state_to_string(conn->proxy_state));
  1784. switch (conn->proxy_state) {
  1785. case PROXY_HTTPS_WANT_CONNECT_OK:
  1786. ret = connection_read_https_proxy_response(conn);
  1787. if (ret == 1)
  1788. conn->proxy_state = PROXY_CONNECTED;
  1789. break;
  1790. case PROXY_SOCKS4_WANT_CONNECT_OK:
  1791. ret = connection_fetch_from_buf_socks_client(conn,
  1792. conn->proxy_state,
  1793. &reason);
  1794. if (ret == 1)
  1795. conn->proxy_state = PROXY_CONNECTED;
  1796. break;
  1797. case PROXY_SOCKS5_WANT_AUTH_METHOD_NONE:
  1798. ret = connection_fetch_from_buf_socks_client(conn,
  1799. conn->proxy_state,
  1800. &reason);
  1801. /* no auth needed, do connect */
  1802. if (ret == 1) {
  1803. connection_send_socks5_connect(conn);
  1804. ret = 0;
  1805. }
  1806. break;
  1807. case PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929:
  1808. ret = connection_fetch_from_buf_socks_client(conn,
  1809. conn->proxy_state,
  1810. &reason);
  1811. /* send auth if needed, otherwise do connect */
  1812. if (ret == 1) {
  1813. connection_send_socks5_connect(conn);
  1814. ret = 0;
  1815. } else if (ret == 2) {
  1816. unsigned char buf[1024];
  1817. size_t reqsize, usize, psize;
  1818. const char *user, *pass;
  1819. char *socks_args_string = NULL;
  1820. if (get_proxy_type() == PROXY_PLUGGABLE) {
  1821. socks_args_string =
  1822. pt_get_socks_args_for_proxy_addrport(&conn->addr, conn->port);
  1823. if (!socks_args_string) {
  1824. log_warn(LD_NET, "Could not create SOCKS args string.");
  1825. ret = -1;
  1826. break;
  1827. }
  1828. log_debug(LD_NET, "SOCKS5 arguments: %s", socks_args_string);
  1829. tor_assert(strlen(socks_args_string) > 0);
  1830. tor_assert(strlen(socks_args_string) <= MAX_SOCKS5_AUTH_SIZE_TOTAL);
  1831. if (strlen(socks_args_string) > MAX_SOCKS5_AUTH_FIELD_SIZE) {
  1832. user = socks_args_string;
  1833. usize = MAX_SOCKS5_AUTH_FIELD_SIZE;
  1834. pass = socks_args_string + MAX_SOCKS5_AUTH_FIELD_SIZE;
  1835. psize = strlen(socks_args_string) - MAX_SOCKS5_AUTH_FIELD_SIZE;
  1836. } else {
  1837. user = socks_args_string;
  1838. usize = strlen(socks_args_string);
  1839. pass = "\0";
  1840. psize = 1;
  1841. }
  1842. } else if (get_options()->Socks5ProxyUsername) {
  1843. user = get_options()->Socks5ProxyUsername;
  1844. pass = get_options()->Socks5ProxyPassword;
  1845. tor_assert(user && pass);
  1846. usize = strlen(user);
  1847. psize = strlen(pass);
  1848. } else {
  1849. log_err(LD_BUG, "We entered %s for no reason!", __func__);
  1850. tor_fragile_assert();
  1851. ret = -1;
  1852. break;
  1853. }
  1854. /* Username and password lengths should have been checked
  1855. above and during torrc parsing. */
  1856. tor_assert(usize <= MAX_SOCKS5_AUTH_FIELD_SIZE &&
  1857. psize <= MAX_SOCKS5_AUTH_FIELD_SIZE);
  1858. reqsize = 3 + usize + psize;
  1859. buf[0] = 1; /* negotiation version */
  1860. buf[1] = usize;
  1861. memcpy(buf + 2, user, usize);
  1862. buf[2 + usize] = psize;
  1863. memcpy(buf + 3 + usize, pass, psize);
  1864. if (socks_args_string)
  1865. tor_free(socks_args_string);
  1866. connection_write_to_buf((char *)buf, reqsize, conn);
  1867. conn->proxy_state = PROXY_SOCKS5_WANT_AUTH_RFC1929_OK;
  1868. ret = 0;
  1869. }
  1870. break;
  1871. case PROXY_SOCKS5_WANT_AUTH_RFC1929_OK:
  1872. ret = connection_fetch_from_buf_socks_client(conn,
  1873. conn->proxy_state,
  1874. &reason);
  1875. /* send the connect request */
  1876. if (ret == 1) {
  1877. connection_send_socks5_connect(conn);
  1878. ret = 0;
  1879. }
  1880. break;
  1881. case PROXY_SOCKS5_WANT_CONNECT_OK:
  1882. ret = connection_fetch_from_buf_socks_client(conn,
  1883. conn->proxy_state,
  1884. &reason);
  1885. if (ret == 1)
  1886. conn->proxy_state = PROXY_CONNECTED;
  1887. break;
  1888. default:
  1889. log_err(LD_BUG, "Invalid proxy_state for reading, %d",
  1890. conn->proxy_state);
  1891. tor_fragile_assert();
  1892. ret = -1;
  1893. break;
  1894. }
  1895. log_debug(LD_NET, "leaving state %s",
  1896. connection_proxy_state_to_string(conn->proxy_state));
  1897. if (ret < 0) {
  1898. if (reason) {
  1899. log_warn(LD_NET, "Proxy Client: unable to connect to %s:%d (%s)",
  1900. conn->address, conn->port, escaped(reason));
  1901. tor_free(reason);
  1902. } else {
  1903. log_warn(LD_NET, "Proxy Client: unable to connect to %s:%d",
  1904. conn->address, conn->port);
  1905. }
  1906. } else if (ret == 1) {
  1907. log_info(LD_NET, "Proxy Client: connection to %s:%d successful",
  1908. conn->address, conn->port);
  1909. }
  1910. return ret;
  1911. }
  1912. /** Given a list of listener connections in <b>old_conns</b>, and list of
  1913. * port_cfg_t entries in <b>ports</b>, open a new listener for every port in
  1914. * <b>ports</b> that does not already have a listener in <b>old_conns</b>.
  1915. *
  1916. * Remove from <b>old_conns</b> every connection that has a corresponding
  1917. * entry in <b>ports</b>. Add to <b>new_conns</b> new every connection we
  1918. * launch.
  1919. *
  1920. * If <b>control_listeners_only</b> is true, then we only open control
  1921. * listeners, and we do not remove any noncontrol listeners from old_conns.
  1922. *
  1923. * Return 0 on success, -1 on failure.
  1924. **/
  1925. static int
  1926. retry_listener_ports(smartlist_t *old_conns,
  1927. const smartlist_t *ports,
  1928. smartlist_t *new_conns,
  1929. int control_listeners_only)
  1930. {
  1931. smartlist_t *launch = smartlist_new();
  1932. int r = 0;
  1933. if (control_listeners_only) {
  1934. SMARTLIST_FOREACH(ports, port_cfg_t *, p, {
  1935. if (p->type == CONN_TYPE_CONTROL_LISTENER)
  1936. smartlist_add(launch, p);
  1937. });
  1938. } else {
  1939. smartlist_add_all(launch, ports);
  1940. }
  1941. /* Iterate through old_conns, comparing it to launch: remove from both lists
  1942. * each pair of elements that corresponds to the same port. */
  1943. SMARTLIST_FOREACH_BEGIN(old_conns, connection_t *, conn) {
  1944. const port_cfg_t *found_port = NULL;
  1945. /* Okay, so this is a listener. Is it configured? */
  1946. SMARTLIST_FOREACH_BEGIN(launch, const port_cfg_t *, wanted) {
  1947. if (conn->type != wanted->type)
  1948. continue;
  1949. if ((conn->socket_family != AF_UNIX && wanted->is_unix_addr) ||
  1950. (conn->socket_family == AF_UNIX && ! wanted->is_unix_addr))
  1951. continue;
  1952. if (wanted->no_listen)
  1953. continue; /* We don't want to open a listener for this one */
  1954. if (wanted->is_unix_addr) {
  1955. if (conn->socket_family == AF_UNIX &&
  1956. !strcmp(wanted->unix_addr, conn->address)) {
  1957. found_port = wanted;
  1958. break;
  1959. }
  1960. } else {
  1961. int port_matches;
  1962. if (wanted->port == CFG_AUTO_PORT) {
  1963. port_matches = 1;
  1964. } else {
  1965. port_matches = (wanted->port == conn->port);
  1966. }
  1967. if (port_matches && tor_addr_eq(&wanted->addr, &conn->addr)) {
  1968. found_port = wanted;
  1969. break;
  1970. }
  1971. }
  1972. } SMARTLIST_FOREACH_END(wanted);
  1973. if (found_port) {
  1974. /* This listener is already running; we don't need to launch it. */
  1975. //log_debug(LD_NET, "Already have %s on %s:%d",
  1976. // conn_type_to_string(found_port->type), conn->address, conn->port);
  1977. smartlist_remove(launch, found_port);
  1978. /* And we can remove the connection from old_conns too. */
  1979. SMARTLIST_DEL_CURRENT(old_conns, conn);
  1980. }
  1981. } SMARTLIST_FOREACH_END(conn);
  1982. /* Now open all the listeners that are configured but not opened. */
  1983. SMARTLIST_FOREACH_BEGIN(launch, const port_cfg_t *, port) {
  1984. struct sockaddr *listensockaddr;
  1985. socklen_t listensocklen = 0;
  1986. char *address=NULL;
  1987. connection_t *conn;
  1988. int real_port = port->port == CFG_AUTO_PORT ? 0 : port->port;
  1989. tor_assert(real_port <= UINT16_MAX);
  1990. if (port->no_listen)
  1991. continue;
  1992. if (port->is_unix_addr) {
  1993. listensockaddr = (struct sockaddr *)
  1994. create_unix_sockaddr(port->unix_addr,
  1995. &address, &listensocklen);
  1996. } else {
  1997. listensockaddr = tor_malloc(sizeof(struct sockaddr_storage));
  1998. listensocklen = tor_addr_to_sockaddr(&port->addr,
  1999. real_port,
  2000. listensockaddr,
  2001. sizeof(struct sockaddr_storage));
  2002. address = tor_dup_addr(&port->addr);
  2003. }
  2004. if (listensockaddr) {
  2005. conn = connection_listener_new(listensockaddr, listensocklen,
  2006. port->type, address, port);
  2007. tor_free(listensockaddr);
  2008. tor_free(address);
  2009. } else {
  2010. conn = NULL;
  2011. }
  2012. if (!conn) {
  2013. r = -1;
  2014. } else {
  2015. if (new_conns)
  2016. smartlist_add(new_conns, conn);
  2017. }
  2018. } SMARTLIST_FOREACH_END(port);
  2019. smartlist_free(launch);
  2020. return r;
  2021. }
  2022. /** Launch listeners for each port you should have open. Only launch
  2023. * listeners who are not already open, and only close listeners we no longer
  2024. * want.
  2025. *
  2026. * Add all old conns that should be closed to <b>replaced_conns</b>.
  2027. * Add all new connections to <b>new_conns</b>.
  2028. *
  2029. * If <b>close_all_noncontrol</b> is true, then we only open control
  2030. * listeners, and we close all other listeners.
  2031. */
  2032. int
  2033. retry_all_listeners(smartlist_t *replaced_conns,
  2034. smartlist_t *new_conns, int close_all_noncontrol)
  2035. {
  2036. smartlist_t *listeners = smartlist_new();
  2037. const or_options_t *options = get_options();
  2038. int retval = 0;
  2039. const uint16_t old_or_port = router_get_advertised_or_port(options);
  2040. const uint16_t old_or_port_ipv6 =
  2041. router_get_advertised_or_port_by_af(options,AF_INET6);
  2042. const uint16_t old_dir_port = router_get_advertised_dir_port(options, 0);
  2043. SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t *, conn) {
  2044. if (connection_is_listener(conn) && !conn->marked_for_close)
  2045. smartlist_add(listeners, conn);
  2046. } SMARTLIST_FOREACH_END(conn);
  2047. if (retry_listener_ports(listeners,
  2048. get_configured_ports(),
  2049. new_conns,
  2050. close_all_noncontrol) < 0)
  2051. retval = -1;
  2052. /* Any members that were still in 'listeners' don't correspond to
  2053. * any configured port. Kill 'em. */
  2054. SMARTLIST_FOREACH_BEGIN(listeners, connection_t *, conn) {
  2055. log_notice(LD_NET, "Closing no-longer-configured %s on %s:%d",
  2056. conn_type_to_string(conn->type), conn->address, conn->port);
  2057. if (replaced_conns) {
  2058. smartlist_add(replaced_conns, conn);
  2059. } else {
  2060. connection_close_immediate(conn);
  2061. connection_mark_for_close(conn);
  2062. }
  2063. } SMARTLIST_FOREACH_END(conn);
  2064. smartlist_free(listeners);
  2065. if (old_or_port != router_get_advertised_or_port(options) ||
  2066. old_or_port_ipv6 != router_get_advertised_or_port_by_af(options,
  2067. AF_INET6) ||
  2068. old_dir_port != router_get_advertised_dir_port(options, 0)) {
  2069. /* Our chosen ORPort or DirPort is not what it used to be: the
  2070. * descriptor we had (if any) should be regenerated. (We won't
  2071. * automatically notice this because of changes in the option,
  2072. * since the value could be "auto".) */
  2073. mark_my_descriptor_dirty("Chosen Or/DirPort changed");
  2074. }
  2075. return retval;
  2076. }
  2077. /** Mark every listener of type other than CONTROL_LISTENER to be closed. */
  2078. void
  2079. connection_mark_all_noncontrol_listeners(void)
  2080. {
  2081. SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t *, conn) {
  2082. if (conn->marked_for_close)
  2083. continue;
  2084. if (conn->type == CONN_TYPE_CONTROL_LISTENER)
  2085. continue;
  2086. if (connection_is_listener(conn))
  2087. connection_mark_for_close(conn);
  2088. } SMARTLIST_FOREACH_END(conn);
  2089. }
  2090. /** Mark every external connection not used for controllers for close. */
  2091. void
  2092. connection_mark_all_noncontrol_connections(void)
  2093. {
  2094. SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t *, conn) {
  2095. if (conn->marked_for_close)
  2096. continue;
  2097. switch (conn->type) {
  2098. case CONN_TYPE_CPUWORKER:
  2099. case CONN_TYPE_CONTROL_LISTENER:
  2100. case CONN_TYPE_CONTROL:
  2101. break;
  2102. case CONN_TYPE_AP:
  2103. connection_mark_unattached_ap(TO_ENTRY_CONN(conn),
  2104. END_STREAM_REASON_HIBERNATING);
  2105. break;
  2106. default:
  2107. connection_mark_for_close(conn);
  2108. break;
  2109. }
  2110. } SMARTLIST_FOREACH_END(conn);
  2111. }
  2112. /** Return 1 if we should apply rate limiting to <b>conn</b>, and 0
  2113. * otherwise.
  2114. * Right now this just checks if it's an internal IP address or an
  2115. * internal connection. We also should, but don't, check if the connection
  2116. * uses pluggable transports, since we should then limit it even if it
  2117. * comes from an internal IP address. */
  2118. static int
  2119. connection_is_rate_limited(connection_t *conn)
  2120. {
  2121. const or_options_t *options = get_options();
  2122. if (conn->linked)
  2123. return 0; /* Internal connection */
  2124. else if (! options->CountPrivateBandwidth &&
  2125. (tor_addr_family(&conn->addr) == AF_UNSPEC || /* no address */
  2126. tor_addr_is_internal(&conn->addr, 0)))
  2127. return 0; /* Internal address */
  2128. else
  2129. return 1;
  2130. }
  2131. #ifdef USE_BUFFEREVENTS
  2132. static struct bufferevent_rate_limit_group *global_rate_limit = NULL;
  2133. #else
  2134. extern int global_read_bucket, global_write_bucket;
  2135. extern int global_relayed_read_bucket, global_relayed_write_bucket;
  2136. /** Did either global write bucket run dry last second? If so,
  2137. * we are likely to run dry again this second, so be stingy with the
  2138. * tokens we just put in. */
  2139. static int write_buckets_empty_last_second = 0;
  2140. #endif
  2141. /** How many seconds of no active local circuits will make the
  2142. * connection revert to the "relayed" bandwidth class? */
  2143. #define CLIENT_IDLE_TIME_FOR_PRIORITY 30
  2144. #ifndef USE_BUFFEREVENTS
  2145. /** Return 1 if <b>conn</b> should use tokens from the "relayed"
  2146. * bandwidth rates, else 0. Currently, only OR conns with bandwidth
  2147. * class 1, and directory conns that are serving data out, count.
  2148. */
  2149. static int
  2150. connection_counts_as_relayed_traffic(connection_t *conn, time_t now)
  2151. {
  2152. if (conn->type == CONN_TYPE_OR &&
  2153. connection_or_client_used(TO_OR_CONN(conn)) +
  2154. CLIENT_IDLE_TIME_FOR_PRIORITY < now)
  2155. return 1;
  2156. if (conn->type == CONN_TYPE_DIR && DIR_CONN_IS_SERVER(conn))
  2157. return 1;
  2158. return 0;
  2159. }
  2160. /** Helper function to decide how many bytes out of <b>global_bucket</b>
  2161. * we're willing to use for this transaction. <b>base</b> is the size
  2162. * of a cell on the network; <b>priority</b> says whether we should
  2163. * write many of them or just a few; and <b>conn_bucket</b> (if
  2164. * non-negative) provides an upper limit for our answer. */
  2165. static ssize_t
  2166. connection_bucket_round_robin(int base, int priority,
  2167. ssize_t global_bucket, ssize_t conn_bucket)
  2168. {
  2169. ssize_t at_most;
  2170. ssize_t num_bytes_high = (priority ? 32 : 16) * base;
  2171. ssize_t num_bytes_low = (priority ? 4 : 2) * base;
  2172. /* Do a rudimentary round-robin so one circuit can't hog a connection.
  2173. * Pick at most 32 cells, at least 4 cells if possible, and if we're in
  2174. * the middle pick 1/8 of the available bandwidth. */
  2175. at_most = global_bucket / 8;
  2176. at_most -= (at_most % base); /* round down */
  2177. if (at_most > num_bytes_high) /* 16 KB, or 8 KB for low-priority */
  2178. at_most = num_bytes_high;
  2179. else if (at_most < num_bytes_low) /* 2 KB, or 1 KB for low-priority */
  2180. at_most = num_bytes_low;
  2181. if (at_most > global_bucket)
  2182. at_most = global_bucket;
  2183. if (conn_bucket >= 0 && at_most > conn_bucket)
  2184. at_most = conn_bucket;
  2185. if (at_most < 0)
  2186. return 0;
  2187. return at_most;
  2188. }
  2189. /** How many bytes at most can we read onto this connection? */
  2190. static ssize_t
  2191. connection_bucket_read_limit(connection_t *conn, time_t now)
  2192. {
  2193. int base = RELAY_PAYLOAD_SIZE;
  2194. int priority = conn->type != CONN_TYPE_DIR;
  2195. int conn_bucket = -1;
  2196. int global_bucket = global_read_bucket;
  2197. if (connection_speaks_cells(conn)) {
  2198. or_connection_t *or_conn = TO_OR_CONN(conn);
  2199. if (conn->state == OR_CONN_STATE_OPEN)
  2200. conn_bucket = or_conn->read_bucket;
  2201. base = get_cell_network_size(or_conn->wide_circ_ids);
  2202. }
  2203. if (!connection_is_rate_limited(conn)) {
  2204. /* be willing to read on local conns even if our buckets are empty */
  2205. return conn_bucket>=0 ? conn_bucket : 1<<14;
  2206. }
  2207. if (connection_counts_as_relayed_traffic(conn, now) &&
  2208. global_relayed_read_bucket <= global_read_bucket)
  2209. global_bucket = global_relayed_read_bucket;
  2210. return connection_bucket_round_robin(base, priority,
  2211. global_bucket, conn_bucket);
  2212. }
  2213. /** How many bytes at most can we write onto this connection? */
  2214. ssize_t
  2215. connection_bucket_write_limit(connection_t *conn, time_t now)
  2216. {
  2217. int base = RELAY_PAYLOAD_SIZE;
  2218. int priority = conn->type != CONN_TYPE_DIR;
  2219. int conn_bucket = (int)conn->outbuf_flushlen;
  2220. int global_bucket = global_write_bucket;
  2221. if (!connection_is_rate_limited(conn)) {
  2222. /* be willing to write to local conns even if our buckets are empty */
  2223. return conn->outbuf_flushlen;
  2224. }
  2225. if (connection_speaks_cells(conn)) {
  2226. /* use the per-conn write limit if it's lower, but if it's less
  2227. * than zero just use zero */
  2228. or_connection_t *or_conn = TO_OR_CONN(conn);
  2229. if (conn->state == OR_CONN_STATE_OPEN)
  2230. if (or_conn->write_bucket < conn_bucket)
  2231. conn_bucket = or_conn->write_bucket >= 0 ?
  2232. or_conn->write_bucket : 0;
  2233. base = get_cell_network_size(or_conn->wide_circ_ids);
  2234. }
  2235. if (connection_counts_as_relayed_traffic(conn, now) &&
  2236. global_relayed_write_bucket <= global_write_bucket)
  2237. global_bucket = global_relayed_write_bucket;
  2238. return connection_bucket_round_robin(base, priority,
  2239. global_bucket, conn_bucket);
  2240. }
  2241. #else
  2242. static ssize_t
  2243. connection_bucket_read_limit(connection_t *conn, time_t now)
  2244. {
  2245. (void) now;
  2246. return bufferevent_get_max_to_read(conn->bufev);
  2247. }
  2248. ssize_t
  2249. connection_bucket_write_limit(connection_t *conn, time_t now)
  2250. {
  2251. (void) now;
  2252. return bufferevent_get_max_to_write(conn->bufev);
  2253. }
  2254. #endif
  2255. /** Return 1 if the global write buckets are low enough that we
  2256. * shouldn't send <b>attempt</b> bytes of low-priority directory stuff
  2257. * out to <b>conn</b>. Else return 0.
  2258. * Priority was 1 for v1 requests (directories and running-routers),
  2259. * and 2 for v2 requests and later (statuses and descriptors).
  2260. *
  2261. * There are a lot of parameters we could use here:
  2262. * - global_relayed_write_bucket. Low is bad.
  2263. * - global_write_bucket. Low is bad.
  2264. * - bandwidthrate. Low is bad.
  2265. * - bandwidthburst. Not a big factor?
  2266. * - attempt. High is bad.
  2267. * - total bytes queued on outbufs. High is bad. But I'm wary of
  2268. * using this, since a few slow-flushing queues will pump up the
  2269. * number without meaning what we meant to mean. What we really
  2270. * mean is "total directory bytes added to outbufs recently", but
  2271. * that's harder to quantify and harder to keep track of.
  2272. */
  2273. int
  2274. global_write_bucket_low(connection_t *conn, size_t attempt, int priority)
  2275. {
  2276. #ifdef USE_BUFFEREVENTS
  2277. ssize_t smaller_bucket = bufferevent_get_max_to_write(conn->bufev);
  2278. #else
  2279. int smaller_bucket = global_write_bucket < global_relayed_write_bucket ?
  2280. global_write_bucket : global_relayed_write_bucket;
  2281. #endif
  2282. if (authdir_mode(get_options()) && priority>1)
  2283. return 0; /* there's always room to answer v2 if we're an auth dir */
  2284. if (!connection_is_rate_limited(conn))
  2285. return 0; /* local conns don't get limited */
  2286. if (smaller_bucket < (int)attempt)
  2287. return 1; /* not enough space no matter the priority */
  2288. #ifndef USE_BUFFEREVENTS
  2289. if (write_buckets_empty_last_second)
  2290. return 1; /* we're already hitting our limits, no more please */
  2291. #endif
  2292. if (priority == 1) { /* old-style v1 query */
  2293. /* Could we handle *two* of these requests within the next two seconds? */
  2294. const or_options_t *options = get_options();
  2295. int64_t can_write = (int64_t)smaller_bucket
  2296. + 2*(options->RelayBandwidthRate ? options->RelayBandwidthRate :
  2297. options->BandwidthRate);
  2298. if (can_write < 2*(int64_t)attempt)
  2299. return 1;
  2300. } else { /* v2 query */
  2301. /* no further constraints yet */
  2302. }
  2303. return 0;
  2304. }
  2305. /** Helper: adjusts our bandwidth history and informs the controller as
  2306. * appropriate, given that we have just read <b>num_read</b> bytes and written
  2307. * <b>num_written</b> bytes on <b>conn</b>. */
  2308. static void
  2309. record_num_bytes_transferred_impl(connection_t *conn,
  2310. time_t now, size_t num_read, size_t num_written)
  2311. {
  2312. /* Count bytes of answering direct and tunneled directory requests */
  2313. if (conn->type == CONN_TYPE_DIR && conn->purpose == DIR_PURPOSE_SERVER) {
  2314. if (num_read > 0)
  2315. rep_hist_note_dir_bytes_read(num_read, now);
  2316. if (num_written > 0)
  2317. rep_hist_note_dir_bytes_written(num_written, now);
  2318. }
  2319. if (!connection_is_rate_limited(conn))
  2320. return; /* local IPs are free */
  2321. if (conn->type == CONN_TYPE_OR)
  2322. rep_hist_note_or_conn_bytes(conn->global_identifier, num_read,
  2323. num_written, now);
  2324. if (num_read > 0) {
  2325. rep_hist_note_bytes_read(num_read, now);
  2326. }
  2327. if (num_written > 0) {
  2328. rep_hist_note_bytes_written(num_written, now);
  2329. }
  2330. if (conn->type == CONN_TYPE_EXIT)
  2331. rep_hist_note_exit_bytes(conn->port, num_written, num_read);
  2332. }
  2333. #ifdef USE_BUFFEREVENTS
  2334. /** Wrapper around fetch_from_(buf/evbuffer)_socks_client: see those functions
  2335. * for documentation of its behavior. */
  2336. static void
  2337. record_num_bytes_transferred(connection_t *conn,
  2338. time_t now, size_t num_read, size_t num_written)
  2339. {
  2340. /* XXX024 check if this is necessary */
  2341. if (num_written >= INT_MAX || num_read >= INT_MAX) {
  2342. log_err(LD_BUG, "Value out of range. num_read=%lu, num_written=%lu, "
  2343. "connection type=%s, state=%s",
  2344. (unsigned long)num_read, (unsigned long)num_written,
  2345. conn_type_to_string(conn->type),
  2346. conn_state_to_string(conn->type, conn->state));
  2347. if (num_written >= INT_MAX) num_written = 1;
  2348. if (num_read >= INT_MAX) num_read = 1;
  2349. tor_fragile_assert();
  2350. }
  2351. record_num_bytes_transferred_impl(conn,now,num_read,num_written);
  2352. }
  2353. #endif
  2354. #ifndef USE_BUFFEREVENTS
  2355. /** Last time at which the global or relay buckets were emptied in msec
  2356. * since midnight. */
  2357. static uint32_t global_relayed_read_emptied = 0,
  2358. global_relayed_write_emptied = 0,
  2359. global_read_emptied = 0,
  2360. global_write_emptied = 0;
  2361. /** Helper: convert given <b>tvnow</b> time value to milliseconds since
  2362. * midnight. */
  2363. static uint32_t
  2364. msec_since_midnight(const struct timeval *tvnow)
  2365. {
  2366. return (uint32_t)(((tvnow->tv_sec % 86400L) * 1000L) +
  2367. ((uint32_t)tvnow->tv_usec / (uint32_t)1000L));
  2368. }
  2369. /** Check if a bucket which had <b>tokens_before</b> tokens and which got
  2370. * <b>tokens_removed</b> tokens removed at timestamp <b>tvnow</b> has run
  2371. * out of tokens, and if so, note the milliseconds since midnight in
  2372. * <b>timestamp_var</b> for the next TB_EMPTY event. */
  2373. void
  2374. connection_buckets_note_empty_ts(uint32_t *timestamp_var,
  2375. int tokens_before, size_t tokens_removed,
  2376. const struct timeval *tvnow)
  2377. {
  2378. if (tokens_before > 0 && (uint32_t)tokens_before <= tokens_removed)
  2379. *timestamp_var = msec_since_midnight(tvnow);
  2380. }
  2381. /** We just read <b>num_read</b> and wrote <b>num_written</b> bytes
  2382. * onto <b>conn</b>. Decrement buckets appropriately. */
  2383. static void
  2384. connection_buckets_decrement(connection_t *conn, time_t now,
  2385. size_t num_read, size_t num_written)
  2386. {
  2387. if (num_written >= INT_MAX || num_read >= INT_MAX) {
  2388. log_err(LD_BUG, "Value out of range. num_read=%lu, num_written=%lu, "
  2389. "connection type=%s, state=%s",
  2390. (unsigned long)num_read, (unsigned long)num_written,
  2391. conn_type_to_string(conn->type),
  2392. conn_state_to_string(conn->type, conn->state));
  2393. if (num_written >= INT_MAX) num_written = 1;
  2394. if (num_read >= INT_MAX) num_read = 1;
  2395. tor_fragile_assert();
  2396. }
  2397. record_num_bytes_transferred_impl(conn, now, num_read, num_written);
  2398. if (!connection_is_rate_limited(conn))
  2399. return; /* local IPs are free */
  2400. /* If one or more of our token buckets ran dry just now, note the
  2401. * timestamp for TB_EMPTY events. */
  2402. if (get_options()->TestingEnableTbEmptyEvent) {
  2403. struct timeval tvnow;
  2404. tor_gettimeofday_cached(&tvnow);
  2405. if (connection_counts_as_relayed_traffic(conn, now)) {
  2406. connection_buckets_note_empty_ts(&global_relayed_read_emptied,
  2407. global_relayed_read_bucket, num_read, &tvnow);
  2408. connection_buckets_note_empty_ts(&global_relayed_write_emptied,
  2409. global_relayed_write_bucket, num_written, &tvnow);
  2410. }
  2411. connection_buckets_note_empty_ts(&global_read_emptied,
  2412. global_read_bucket, num_read, &tvnow);
  2413. connection_buckets_note_empty_ts(&global_write_emptied,
  2414. global_write_bucket, num_written, &tvnow);
  2415. if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
  2416. or_connection_t *or_conn = TO_OR_CONN(conn);
  2417. connection_buckets_note_empty_ts(&or_conn->read_emptied_time,
  2418. or_conn->read_bucket, num_read, &tvnow);
  2419. connection_buckets_note_empty_ts(&or_conn->write_emptied_time,
  2420. or_conn->write_bucket, num_written, &tvnow);
  2421. }
  2422. }
  2423. if (connection_counts_as_relayed_traffic(conn, now)) {
  2424. global_relayed_read_bucket -= (int)num_read;
  2425. global_relayed_write_bucket -= (int)num_written;
  2426. }
  2427. global_read_bucket -= (int)num_read;
  2428. global_write_bucket -= (int)num_written;
  2429. if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
  2430. TO_OR_CONN(conn)->read_bucket -= (int)num_read;
  2431. TO_OR_CONN(conn)->write_bucket -= (int)num_written;
  2432. }
  2433. }
  2434. /** If we have exhausted our global buckets, or the buckets for conn,
  2435. * stop reading. */
  2436. static void
  2437. connection_consider_empty_read_buckets(connection_t *conn)
  2438. {
  2439. const char *reason;
  2440. if (!connection_is_rate_limited(conn))
  2441. return; /* Always okay. */
  2442. if (global_read_bucket <= 0) {
  2443. reason = "global read bucket exhausted. Pausing.";
  2444. } else if (connection_counts_as_relayed_traffic(conn, approx_time()) &&
  2445. global_relayed_read_bucket <= 0) {
  2446. reason = "global relayed read bucket exhausted. Pausing.";
  2447. } else if (connection_speaks_cells(conn) &&
  2448. conn->state == OR_CONN_STATE_OPEN &&
  2449. TO_OR_CONN(conn)->read_bucket <= 0) {
  2450. reason = "connection read bucket exhausted. Pausing.";
  2451. } else
  2452. return; /* all good, no need to stop it */
  2453. LOG_FN_CONN(conn, (LOG_DEBUG, LD_NET, "%s", reason));
  2454. conn->read_blocked_on_bw = 1;
  2455. connection_stop_reading(conn);
  2456. }
  2457. /** If we have exhausted our global buckets, or the buckets for conn,
  2458. * stop writing. */
  2459. static void
  2460. connection_consider_empty_write_buckets(connection_t *conn)
  2461. {
  2462. const char *reason;
  2463. if (!connection_is_rate_limited(conn))
  2464. return; /* Always okay. */
  2465. if (global_write_bucket <= 0) {
  2466. reason = "global write bucket exhausted. Pausing.";
  2467. } else if (connection_counts_as_relayed_traffic(conn, approx_time()) &&
  2468. global_relayed_write_bucket <= 0) {
  2469. reason = "global relayed write bucket exhausted. Pausing.";
  2470. } else if (connection_speaks_cells(conn) &&
  2471. conn->state == OR_CONN_STATE_OPEN &&
  2472. TO_OR_CONN(conn)->write_bucket <= 0) {
  2473. reason = "connection write bucket exhausted. Pausing.";
  2474. } else
  2475. return; /* all good, no need to stop it */
  2476. LOG_FN_CONN(conn, (LOG_DEBUG, LD_NET, "%s", reason));
  2477. conn->write_blocked_on_bw = 1;
  2478. connection_stop_writing(conn);
  2479. }
  2480. /** Initialize the global read bucket to options-\>BandwidthBurst. */
  2481. void
  2482. connection_bucket_init(void)
  2483. {
  2484. const or_options_t *options = get_options();
  2485. /* start it at max traffic */
  2486. global_read_bucket = (int)options->BandwidthBurst;
  2487. global_write_bucket = (int)options->BandwidthBurst;
  2488. if (options->RelayBandwidthRate) {
  2489. global_relayed_read_bucket = (int)options->RelayBandwidthBurst;
  2490. global_relayed_write_bucket = (int)options->RelayBandwidthBurst;
  2491. } else {
  2492. global_relayed_read_bucket = (int)options->BandwidthBurst;
  2493. global_relayed_write_bucket = (int)options->BandwidthBurst;
  2494. }
  2495. }
  2496. /** Refill a single <b>bucket</b> called <b>name</b> with bandwidth rate per
  2497. * second <b>rate</b> and bandwidth burst <b>burst</b>, assuming that
  2498. * <b>milliseconds_elapsed</b> milliseconds have passed since the last
  2499. * call. */
  2500. static void
  2501. connection_bucket_refill_helper(int *bucket, int rate, int burst,
  2502. int milliseconds_elapsed,
  2503. const char *name)
  2504. {
  2505. int starting_bucket = *bucket;
  2506. if (starting_bucket < burst && milliseconds_elapsed > 0) {
  2507. int64_t incr = (((int64_t)rate) * milliseconds_elapsed) / 1000;
  2508. if ((burst - starting_bucket) < incr) {
  2509. *bucket = burst; /* We would overflow the bucket; just set it to
  2510. * the maximum. */
  2511. } else {
  2512. *bucket += (int)incr;
  2513. if (*bucket > burst || *bucket < starting_bucket) {
  2514. /* If we overflow the burst, or underflow our starting bucket,
  2515. * cap the bucket value to burst. */
  2516. /* XXXX this might be redundant now, but it doesn't show up
  2517. * in profiles. Remove it after analysis. */
  2518. *bucket = burst;
  2519. }
  2520. }
  2521. log_debug(LD_NET,"%s now %d.", name, *bucket);
  2522. }
  2523. }
  2524. /** Helper: return the time in milliseconds since <b>last_empty_time</b>
  2525. * when a bucket ran empty that previously had <b>tokens_before</b> tokens
  2526. * now has <b>tokens_after</b> tokens after refilling at timestamp
  2527. * <b>tvnow</b>, capped at <b>milliseconds_elapsed</b> milliseconds since
  2528. * last refilling that bucket. Return 0 if the bucket has not been empty
  2529. * since the last refill or has not been refilled. */
  2530. uint32_t
  2531. bucket_millis_empty(int tokens_before, uint32_t last_empty_time,
  2532. int tokens_after, int milliseconds_elapsed,
  2533. const struct timeval *tvnow)
  2534. {
  2535. uint32_t result = 0, refilled;
  2536. if (tokens_before <= 0 && tokens_after > tokens_before) {
  2537. refilled = msec_since_midnight(tvnow);
  2538. result = (uint32_t)((refilled + 86400L * 1000L - last_empty_time) %
  2539. (86400L * 1000L));
  2540. if (result > (uint32_t)milliseconds_elapsed)
  2541. result = (uint32_t)milliseconds_elapsed;
  2542. }
  2543. return result;
  2544. }
  2545. /** Time has passed; increment buckets appropriately. */
  2546. void
  2547. connection_bucket_refill(int milliseconds_elapsed, time_t now)
  2548. {
  2549. const or_options_t *options = get_options();
  2550. smartlist_t *conns = get_connection_array();
  2551. int bandwidthrate, bandwidthburst, relayrate, relayburst;
  2552. int prev_global_read = global_read_bucket;
  2553. int prev_global_write = global_write_bucket;
  2554. int prev_relay_read = global_relayed_read_bucket;
  2555. int prev_relay_write = global_relayed_write_bucket;
  2556. struct timeval tvnow; /*< Only used if TB_EMPTY events are enabled. */
  2557. bandwidthrate = (int)options->BandwidthRate;
  2558. bandwidthburst = (int)options->BandwidthBurst;
  2559. if (options->RelayBandwidthRate) {
  2560. relayrate = (int)options->RelayBandwidthRate;
  2561. relayburst = (int)options->RelayBandwidthBurst;
  2562. } else {
  2563. relayrate = bandwidthrate;
  2564. relayburst = bandwidthburst;
  2565. }
  2566. tor_assert(milliseconds_elapsed >= 0);
  2567. write_buckets_empty_last_second =
  2568. global_relayed_write_bucket <= 0 || global_write_bucket <= 0;
  2569. /* refill the global buckets */
  2570. connection_bucket_refill_helper(&global_read_bucket,
  2571. bandwidthrate, bandwidthburst,
  2572. milliseconds_elapsed,
  2573. "global_read_bucket");
  2574. connection_bucket_refill_helper(&global_write_bucket,
  2575. bandwidthrate, bandwidthburst,
  2576. milliseconds_elapsed,
  2577. "global_write_bucket");
  2578. connection_bucket_refill_helper(&global_relayed_read_bucket,
  2579. relayrate, relayburst,
  2580. milliseconds_elapsed,
  2581. "global_relayed_read_bucket");
  2582. connection_bucket_refill_helper(&global_relayed_write_bucket,
  2583. relayrate, relayburst,
  2584. milliseconds_elapsed,
  2585. "global_relayed_write_bucket");
  2586. /* If buckets were empty before and have now been refilled, tell any
  2587. * interested controllers. */
  2588. if (get_options()->TestingEnableTbEmptyEvent) {
  2589. uint32_t global_read_empty_time, global_write_empty_time,
  2590. relay_read_empty_time, relay_write_empty_time;
  2591. tor_gettimeofday_cached(&tvnow);
  2592. global_read_empty_time = bucket_millis_empty(prev_global_read,
  2593. global_read_emptied, global_read_bucket,
  2594. milliseconds_elapsed, &tvnow);
  2595. global_write_empty_time = bucket_millis_empty(prev_global_write,
  2596. global_write_emptied, global_write_bucket,
  2597. milliseconds_elapsed, &tvnow);
  2598. control_event_tb_empty("GLOBAL", global_read_empty_time,
  2599. global_write_empty_time, milliseconds_elapsed);
  2600. relay_read_empty_time = bucket_millis_empty(prev_relay_read,
  2601. global_relayed_read_emptied,
  2602. global_relayed_read_bucket,
  2603. milliseconds_elapsed, &tvnow);
  2604. relay_write_empty_time = bucket_millis_empty(prev_relay_write,
  2605. global_relayed_write_emptied,
  2606. global_relayed_write_bucket,
  2607. milliseconds_elapsed, &tvnow);
  2608. control_event_tb_empty("RELAY", relay_read_empty_time,
  2609. relay_write_empty_time, milliseconds_elapsed);
  2610. }
  2611. /* refill the per-connection buckets */
  2612. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  2613. if (connection_speaks_cells(conn)) {
  2614. or_connection_t *or_conn = TO_OR_CONN(conn);
  2615. int orbandwidthrate = or_conn->bandwidthrate;
  2616. int orbandwidthburst = or_conn->bandwidthburst;
  2617. int prev_conn_read = or_conn->read_bucket;
  2618. int prev_conn_write = or_conn->write_bucket;
  2619. if (connection_bucket_should_increase(or_conn->read_bucket, or_conn)) {
  2620. connection_bucket_refill_helper(&or_conn->read_bucket,
  2621. orbandwidthrate,
  2622. orbandwidthburst,
  2623. milliseconds_elapsed,
  2624. "or_conn->read_bucket");
  2625. }
  2626. if (connection_bucket_should_increase(or_conn->write_bucket, or_conn)) {
  2627. connection_bucket_refill_helper(&or_conn->write_bucket,
  2628. orbandwidthrate,
  2629. orbandwidthburst,
  2630. milliseconds_elapsed,
  2631. "or_conn->write_bucket");
  2632. }
  2633. /* If buckets were empty before and have now been refilled, tell any
  2634. * interested controllers. */
  2635. if (get_options()->TestingEnableTbEmptyEvent) {
  2636. char *bucket;
  2637. uint32_t conn_read_empty_time, conn_write_empty_time;
  2638. tor_asprintf(&bucket, "ORCONN ID="U64_FORMAT,
  2639. U64_PRINTF_ARG(or_conn->base_.global_identifier));
  2640. conn_read_empty_time = bucket_millis_empty(prev_conn_read,
  2641. or_conn->read_emptied_time,
  2642. or_conn->read_bucket,
  2643. milliseconds_elapsed, &tvnow);
  2644. conn_write_empty_time = bucket_millis_empty(prev_conn_write,
  2645. or_conn->write_emptied_time,
  2646. or_conn->write_bucket,
  2647. milliseconds_elapsed, &tvnow);
  2648. control_event_tb_empty(bucket, conn_read_empty_time,
  2649. conn_write_empty_time,
  2650. milliseconds_elapsed);
  2651. tor_free(bucket);
  2652. }
  2653. }
  2654. if (conn->read_blocked_on_bw == 1 /* marked to turn reading back on now */
  2655. && global_read_bucket > 0 /* and we're allowed to read */
  2656. && (!connection_counts_as_relayed_traffic(conn, now) ||
  2657. global_relayed_read_bucket > 0) /* even if we're relayed traffic */
  2658. && (!connection_speaks_cells(conn) ||
  2659. conn->state != OR_CONN_STATE_OPEN ||
  2660. TO_OR_CONN(conn)->read_bucket > 0)) {
  2661. /* and either a non-cell conn or a cell conn with non-empty bucket */
  2662. LOG_FN_CONN(conn, (LOG_DEBUG,LD_NET,
  2663. "waking up conn (fd %d) for read", (int)conn->s));
  2664. conn->read_blocked_on_bw = 0;
  2665. connection_start_reading(conn);
  2666. }
  2667. if (conn->write_blocked_on_bw == 1
  2668. && global_write_bucket > 0 /* and we're allowed to write */
  2669. && (!connection_counts_as_relayed_traffic(conn, now) ||
  2670. global_relayed_write_bucket > 0) /* even if it's relayed traffic */
  2671. && (!connection_speaks_cells(conn) ||
  2672. conn->state != OR_CONN_STATE_OPEN ||
  2673. TO_OR_CONN(conn)->write_bucket > 0)) {
  2674. LOG_FN_CONN(conn, (LOG_DEBUG,LD_NET,
  2675. "waking up conn (fd %d) for write", (int)conn->s));
  2676. conn->write_blocked_on_bw = 0;
  2677. connection_start_writing(conn);
  2678. }
  2679. } SMARTLIST_FOREACH_END(conn);
  2680. }
  2681. /** Is the <b>bucket</b> for connection <b>conn</b> low enough that we
  2682. * should add another pile of tokens to it?
  2683. */
  2684. static int
  2685. connection_bucket_should_increase(int bucket, or_connection_t *conn)
  2686. {
  2687. tor_assert(conn);
  2688. if (conn->base_.state != OR_CONN_STATE_OPEN)
  2689. return 0; /* only open connections play the rate limiting game */
  2690. if (bucket >= conn->bandwidthburst)
  2691. return 0;
  2692. return 1;
  2693. }
  2694. #else
  2695. static void
  2696. connection_buckets_decrement(connection_t *conn, time_t now,
  2697. size_t num_read, size_t num_written)
  2698. {
  2699. (void) conn;
  2700. (void) now;
  2701. (void) num_read;
  2702. (void) num_written;
  2703. /* Libevent does this for us. */
  2704. }
  2705. void
  2706. connection_bucket_refill(int seconds_elapsed, time_t now)
  2707. {
  2708. (void) seconds_elapsed;
  2709. (void) now;
  2710. /* Libevent does this for us. */
  2711. }
  2712. void
  2713. connection_bucket_init(void)
  2714. {
  2715. const or_options_t *options = get_options();
  2716. const struct timeval *tick = tor_libevent_get_one_tick_timeout();
  2717. struct ev_token_bucket_cfg *bucket_cfg;
  2718. uint64_t rate, burst;
  2719. if (options->RelayBandwidthRate) {
  2720. rate = options->RelayBandwidthRate;
  2721. burst = options->RelayBandwidthBurst;
  2722. } else {
  2723. rate = options->BandwidthRate;
  2724. burst = options->BandwidthBurst;
  2725. }
  2726. /* This can't overflow, since TokenBucketRefillInterval <= 1000,
  2727. * and rate started out less than INT32_MAX. */
  2728. rate = (rate * options->TokenBucketRefillInterval) / 1000;
  2729. bucket_cfg = ev_token_bucket_cfg_new((uint32_t)rate, (uint32_t)burst,
  2730. (uint32_t)rate, (uint32_t)burst,
  2731. tick);
  2732. if (!global_rate_limit) {
  2733. global_rate_limit =
  2734. bufferevent_rate_limit_group_new(tor_libevent_get_base(), bucket_cfg);
  2735. } else {
  2736. bufferevent_rate_limit_group_set_cfg(global_rate_limit, bucket_cfg);
  2737. }
  2738. ev_token_bucket_cfg_free(bucket_cfg);
  2739. }
  2740. void
  2741. connection_get_rate_limit_totals(uint64_t *read_out, uint64_t *written_out)
  2742. {
  2743. if (global_rate_limit == NULL) {
  2744. *read_out = *written_out = 0;
  2745. } else {
  2746. bufferevent_rate_limit_group_get_totals(
  2747. global_rate_limit, read_out, written_out);
  2748. }
  2749. }
  2750. /** Perform whatever operations are needed on <b>conn</b> to enable
  2751. * rate-limiting. */
  2752. void
  2753. connection_enable_rate_limiting(connection_t *conn)
  2754. {
  2755. if (conn->bufev) {
  2756. if (!global_rate_limit)
  2757. connection_bucket_init();
  2758. tor_add_bufferevent_to_rate_limit_group(conn->bufev, global_rate_limit);
  2759. }
  2760. }
  2761. static void
  2762. connection_consider_empty_write_buckets(connection_t *conn)
  2763. {
  2764. (void) conn;
  2765. }
  2766. static void
  2767. connection_consider_empty_read_buckets(connection_t *conn)
  2768. {
  2769. (void) conn;
  2770. }
  2771. #endif
  2772. /** Read bytes from conn-\>s and process them.
  2773. *
  2774. * It calls connection_read_to_buf() to bring in any new bytes,
  2775. * and then calls connection_process_inbuf() to process them.
  2776. *
  2777. * Mark the connection and return -1 if you want to close it, else
  2778. * return 0.
  2779. */
  2780. static int
  2781. connection_handle_read_impl(connection_t *conn)
  2782. {
  2783. ssize_t max_to_read=-1, try_to_read;
  2784. size_t before, n_read = 0;
  2785. int socket_error = 0;
  2786. if (conn->marked_for_close)
  2787. return 0; /* do nothing */
  2788. conn->timestamp_lastread = approx_time();
  2789. switch (conn->type) {
  2790. case CONN_TYPE_OR_LISTENER:
  2791. return connection_handle_listener_read(conn, CONN_TYPE_OR);
  2792. case CONN_TYPE_EXT_OR_LISTENER:
  2793. return connection_handle_listener_read(conn, CONN_TYPE_EXT_OR);
  2794. case CONN_TYPE_AP_LISTENER:
  2795. case CONN_TYPE_AP_TRANS_LISTENER:
  2796. case CONN_TYPE_AP_NATD_LISTENER:
  2797. return connection_handle_listener_read(conn, CONN_TYPE_AP);
  2798. case CONN_TYPE_DIR_LISTENER:
  2799. return connection_handle_listener_read(conn, CONN_TYPE_DIR);
  2800. case CONN_TYPE_CONTROL_LISTENER:
  2801. return connection_handle_listener_read(conn, CONN_TYPE_CONTROL);
  2802. case CONN_TYPE_AP_DNS_LISTENER:
  2803. /* This should never happen; eventdns.c handles the reads here. */
  2804. tor_fragile_assert();
  2805. return 0;
  2806. }
  2807. loop_again:
  2808. try_to_read = max_to_read;
  2809. tor_assert(!conn->marked_for_close);
  2810. before = buf_datalen(conn->inbuf);
  2811. if (connection_read_to_buf(conn, &max_to_read, &socket_error) < 0) {
  2812. /* There's a read error; kill the connection.*/
  2813. if (conn->type == CONN_TYPE_OR) {
  2814. connection_or_notify_error(TO_OR_CONN(conn),
  2815. socket_error != 0 ?
  2816. errno_to_orconn_end_reason(socket_error) :
  2817. END_OR_CONN_REASON_CONNRESET,
  2818. socket_error != 0 ?
  2819. tor_socket_strerror(socket_error) :
  2820. "(unknown, errno was 0)");
  2821. }
  2822. if (CONN_IS_EDGE(conn)) {
  2823. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  2824. connection_edge_end_errno(edge_conn);
  2825. if (conn->type == CONN_TYPE_AP && TO_ENTRY_CONN(conn)->socks_request) {
  2826. /* broken, don't send a socks reply back */
  2827. TO_ENTRY_CONN(conn)->socks_request->has_finished = 1;
  2828. }
  2829. }
  2830. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  2831. /*
  2832. * This can bypass normal channel checking since we did
  2833. * connection_or_notify_error() above.
  2834. */
  2835. connection_mark_for_close_internal(conn);
  2836. return -1;
  2837. }
  2838. n_read += buf_datalen(conn->inbuf) - before;
  2839. if (CONN_IS_EDGE(conn) && try_to_read != max_to_read) {
  2840. /* instruct it not to try to package partial cells. */
  2841. if (connection_process_inbuf(conn, 0) < 0) {
  2842. return -1;
  2843. }
  2844. if (!conn->marked_for_close &&
  2845. connection_is_reading(conn) &&
  2846. !conn->inbuf_reached_eof &&
  2847. max_to_read > 0)
  2848. goto loop_again; /* try reading again, in case more is here now */
  2849. }
  2850. /* one last try, packaging partial cells and all. */
  2851. if (!conn->marked_for_close &&
  2852. connection_process_inbuf(conn, 1) < 0) {
  2853. return -1;
  2854. }
  2855. if (conn->linked_conn) {
  2856. /* The other side's handle_write() will never actually get called, so
  2857. * we need to invoke the appropriate callbacks ourself. */
  2858. connection_t *linked = conn->linked_conn;
  2859. if (n_read) {
  2860. /* Probably a no-op, since linked conns typically don't count for
  2861. * bandwidth rate limiting. But do it anyway so we can keep stats
  2862. * accurately. Note that since we read the bytes from conn, and
  2863. * we're writing the bytes onto the linked connection, we count
  2864. * these as <i>written</i> bytes. */
  2865. connection_buckets_decrement(linked, approx_time(), 0, n_read);
  2866. if (connection_flushed_some(linked) < 0)
  2867. connection_mark_for_close(linked);
  2868. if (!connection_wants_to_flush(linked))
  2869. connection_finished_flushing(linked);
  2870. }
  2871. if (!buf_datalen(linked->outbuf) && conn->active_on_link)
  2872. connection_stop_reading_from_linked_conn(conn);
  2873. }
  2874. /* If we hit the EOF, call connection_reached_eof(). */
  2875. if (!conn->marked_for_close &&
  2876. conn->inbuf_reached_eof &&
  2877. connection_reached_eof(conn) < 0) {
  2878. return -1;
  2879. }
  2880. return 0;
  2881. }
  2882. /* DOCDOC connection_handle_read */
  2883. int
  2884. connection_handle_read(connection_t *conn)
  2885. {
  2886. int res;
  2887. tor_gettimeofday_cache_clear();
  2888. res = connection_handle_read_impl(conn);
  2889. return res;
  2890. }
  2891. /** Pull in new bytes from conn-\>s or conn-\>linked_conn onto conn-\>inbuf,
  2892. * either directly or via TLS. Reduce the token buckets by the number of bytes
  2893. * read.
  2894. *
  2895. * If *max_to_read is -1, then decide it ourselves, else go with the
  2896. * value passed to us. When returning, if it's changed, subtract the
  2897. * number of bytes we read from *max_to_read.
  2898. *
  2899. * Return -1 if we want to break conn, else return 0.
  2900. */
  2901. static int
  2902. connection_read_to_buf(connection_t *conn, ssize_t *max_to_read,
  2903. int *socket_error)
  2904. {
  2905. int result;
  2906. ssize_t at_most = *max_to_read;
  2907. size_t slack_in_buf, more_to_read;
  2908. size_t n_read = 0, n_written = 0;
  2909. if (at_most == -1) { /* we need to initialize it */
  2910. /* how many bytes are we allowed to read? */
  2911. at_most = connection_bucket_read_limit(conn, approx_time());
  2912. }
  2913. slack_in_buf = buf_slack(conn->inbuf);
  2914. again:
  2915. if ((size_t)at_most > slack_in_buf && slack_in_buf >= 1024) {
  2916. more_to_read = at_most - slack_in_buf;
  2917. at_most = slack_in_buf;
  2918. } else {
  2919. more_to_read = 0;
  2920. }
  2921. if (connection_speaks_cells(conn) &&
  2922. conn->state > OR_CONN_STATE_PROXY_HANDSHAKING) {
  2923. int pending;
  2924. or_connection_t *or_conn = TO_OR_CONN(conn);
  2925. size_t initial_size;
  2926. if (conn->state == OR_CONN_STATE_TLS_HANDSHAKING ||
  2927. conn->state == OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING) {
  2928. /* continue handshaking even if global token bucket is empty */
  2929. return connection_tls_continue_handshake(or_conn);
  2930. }
  2931. log_debug(LD_NET,
  2932. "%d: starting, inbuf_datalen %ld (%d pending in tls object)."
  2933. " at_most %ld.",
  2934. (int)conn->s,(long)buf_datalen(conn->inbuf),
  2935. tor_tls_get_pending_bytes(or_conn->tls), (long)at_most);
  2936. initial_size = buf_datalen(conn->inbuf);
  2937. /* else open, or closing */
  2938. result = read_to_buf_tls(or_conn->tls, at_most, conn->inbuf);
  2939. if (TOR_TLS_IS_ERROR(result) || result == TOR_TLS_CLOSE)
  2940. or_conn->tls_error = result;
  2941. else
  2942. or_conn->tls_error = 0;
  2943. switch (result) {
  2944. case TOR_TLS_CLOSE:
  2945. case TOR_TLS_ERROR_IO:
  2946. log_debug(LD_NET,"TLS connection closed %son read. Closing. "
  2947. "(Nickname %s, address %s)",
  2948. result == TOR_TLS_CLOSE ? "cleanly " : "",
  2949. or_conn->nickname ? or_conn->nickname : "not set",
  2950. conn->address);
  2951. return result;
  2952. CASE_TOR_TLS_ERROR_ANY_NONIO:
  2953. log_debug(LD_NET,"tls error [%s]. breaking (nickname %s, address %s).",
  2954. tor_tls_err_to_string(result),
  2955. or_conn->nickname ? or_conn->nickname : "not set",
  2956. conn->address);
  2957. return result;
  2958. case TOR_TLS_WANTWRITE:
  2959. connection_start_writing(conn);
  2960. return 0;
  2961. case TOR_TLS_WANTREAD:
  2962. if (conn->in_connection_handle_write) {
  2963. /* We've been invoked from connection_handle_write, because we're
  2964. * waiting for a TLS renegotiation, the renegotiation started, and
  2965. * SSL_read returned WANTWRITE. But now SSL_read is saying WANTREAD
  2966. * again. Stop waiting for write events now, or else we'll
  2967. * busy-loop until data arrives for us to read. */
  2968. connection_stop_writing(conn);
  2969. if (!connection_is_reading(conn))
  2970. connection_start_reading(conn);
  2971. }
  2972. /* we're already reading, one hopes */
  2973. result = 0;
  2974. break;
  2975. case TOR_TLS_DONE: /* no data read, so nothing to process */
  2976. result = 0;
  2977. break; /* so we call bucket_decrement below */
  2978. default:
  2979. break;
  2980. }
  2981. pending = tor_tls_get_pending_bytes(or_conn->tls);
  2982. if (pending) {
  2983. /* If we have any pending bytes, we read them now. This *can*
  2984. * take us over our read allotment, but really we shouldn't be
  2985. * believing that SSL bytes are the same as TCP bytes anyway. */
  2986. int r2 = read_to_buf_tls(or_conn->tls, pending, conn->inbuf);
  2987. if (r2<0) {
  2988. log_warn(LD_BUG, "apparently, reading pending bytes can fail.");
  2989. return -1;
  2990. }
  2991. }
  2992. result = (int)(buf_datalen(conn->inbuf)-initial_size);
  2993. tor_tls_get_n_raw_bytes(or_conn->tls, &n_read, &n_written);
  2994. log_debug(LD_GENERAL, "After TLS read of %d: %ld read, %ld written",
  2995. result, (long)n_read, (long)n_written);
  2996. } else if (conn->linked) {
  2997. if (conn->linked_conn) {
  2998. result = move_buf_to_buf(conn->inbuf, conn->linked_conn->outbuf,
  2999. &conn->linked_conn->outbuf_flushlen);
  3000. } else {
  3001. result = 0;
  3002. }
  3003. //log_notice(LD_GENERAL, "Moved %d bytes on an internal link!", result);
  3004. /* If the other side has disappeared, or if it's been marked for close and
  3005. * we flushed its outbuf, then we should set our inbuf_reached_eof. */
  3006. if (!conn->linked_conn ||
  3007. (conn->linked_conn->marked_for_close &&
  3008. buf_datalen(conn->linked_conn->outbuf) == 0))
  3009. conn->inbuf_reached_eof = 1;
  3010. n_read = (size_t) result;
  3011. } else {
  3012. /* !connection_speaks_cells, !conn->linked_conn. */
  3013. int reached_eof = 0;
  3014. CONN_LOG_PROTECT(conn,
  3015. result = read_to_buf(conn->s, at_most, conn->inbuf, &reached_eof,
  3016. socket_error));
  3017. if (reached_eof)
  3018. conn->inbuf_reached_eof = 1;
  3019. // log_fn(LOG_DEBUG,"read_to_buf returned %d.",read_result);
  3020. if (result < 0)
  3021. return -1;
  3022. n_read = (size_t) result;
  3023. }
  3024. if (n_read > 0) {
  3025. /* change *max_to_read */
  3026. *max_to_read = at_most - n_read;
  3027. /* Update edge_conn->n_read and ocirc->n_read_circ_bw */
  3028. if (conn->type == CONN_TYPE_AP) {
  3029. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  3030. circuit_t *circ = circuit_get_by_edge_conn(edge_conn);
  3031. origin_circuit_t *ocirc;
  3032. /* Check for overflow: */
  3033. if (PREDICT_LIKELY(UINT32_MAX - edge_conn->n_read > n_read))
  3034. edge_conn->n_read += (int)n_read;
  3035. else
  3036. edge_conn->n_read = UINT32_MAX;
  3037. if (circ && CIRCUIT_IS_ORIGIN(circ)) {
  3038. ocirc = TO_ORIGIN_CIRCUIT(circ);
  3039. if (PREDICT_LIKELY(UINT32_MAX - ocirc->n_read_circ_bw > n_read))
  3040. ocirc->n_read_circ_bw += (int)n_read;
  3041. else
  3042. ocirc->n_read_circ_bw = UINT32_MAX;
  3043. }
  3044. }
  3045. /* If CONN_BW events are enabled, update conn->n_read_conn_bw for
  3046. * OR/DIR/EXIT connections, checking for overflow. */
  3047. if (get_options()->TestingEnableConnBwEvent &&
  3048. (conn->type == CONN_TYPE_OR ||
  3049. conn->type == CONN_TYPE_DIR ||
  3050. conn->type == CONN_TYPE_EXIT)) {
  3051. if (PREDICT_LIKELY(UINT32_MAX - conn->n_read_conn_bw > n_read))
  3052. conn->n_read_conn_bw += (int)n_read;
  3053. else
  3054. conn->n_read_conn_bw = UINT32_MAX;
  3055. }
  3056. }
  3057. connection_buckets_decrement(conn, approx_time(), n_read, n_written);
  3058. if (more_to_read && result == at_most) {
  3059. slack_in_buf = buf_slack(conn->inbuf);
  3060. at_most = more_to_read;
  3061. goto again;
  3062. }
  3063. /* Call even if result is 0, since the global read bucket may
  3064. * have reached 0 on a different conn, and this guy needs to
  3065. * know to stop reading. */
  3066. connection_consider_empty_read_buckets(conn);
  3067. if (n_written > 0 && connection_is_writing(conn))
  3068. connection_consider_empty_write_buckets(conn);
  3069. return 0;
  3070. }
  3071. #ifdef USE_BUFFEREVENTS
  3072. /* XXXX These generic versions could be simplified by making them
  3073. type-specific */
  3074. /** Callback: Invoked whenever bytes are added to or drained from an input
  3075. * evbuffer. Used to track the number of bytes read. */
  3076. static void
  3077. evbuffer_inbuf_callback(struct evbuffer *buf,
  3078. const struct evbuffer_cb_info *info, void *arg)
  3079. {
  3080. connection_t *conn = arg;
  3081. (void) buf;
  3082. /* XXXX These need to get real counts on the non-nested TLS case. - NM */
  3083. if (info->n_added) {
  3084. time_t now = approx_time();
  3085. conn->timestamp_lastread = now;
  3086. record_num_bytes_transferred(conn, now, info->n_added, 0);
  3087. connection_consider_empty_read_buckets(conn);
  3088. if (conn->type == CONN_TYPE_AP) {
  3089. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  3090. /*XXXX024 check for overflow*/
  3091. edge_conn->n_read += (int)info->n_added;
  3092. }
  3093. }
  3094. }
  3095. /** Callback: Invoked whenever bytes are added to or drained from an output
  3096. * evbuffer. Used to track the number of bytes written. */
  3097. static void
  3098. evbuffer_outbuf_callback(struct evbuffer *buf,
  3099. const struct evbuffer_cb_info *info, void *arg)
  3100. {
  3101. connection_t *conn = arg;
  3102. (void)buf;
  3103. if (info->n_deleted) {
  3104. time_t now = approx_time();
  3105. conn->timestamp_lastwritten = now;
  3106. record_num_bytes_transferred(conn, now, 0, info->n_deleted);
  3107. connection_consider_empty_write_buckets(conn);
  3108. if (conn->type == CONN_TYPE_AP) {
  3109. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  3110. /*XXXX024 check for overflow*/
  3111. edge_conn->n_written += (int)info->n_deleted;
  3112. }
  3113. }
  3114. }
  3115. /** Callback: invoked whenever a bufferevent has read data. */
  3116. void
  3117. connection_handle_read_cb(struct bufferevent *bufev, void *arg)
  3118. {
  3119. connection_t *conn = arg;
  3120. (void) bufev;
  3121. if (!conn->marked_for_close) {
  3122. if (connection_process_inbuf(conn, 1)<0) /* XXXX Always 1? */
  3123. if (!conn->marked_for_close)
  3124. connection_mark_for_close(conn);
  3125. }
  3126. }
  3127. /** Callback: invoked whenever a bufferevent has written data. */
  3128. void
  3129. connection_handle_write_cb(struct bufferevent *bufev, void *arg)
  3130. {
  3131. connection_t *conn = arg;
  3132. struct evbuffer *output;
  3133. if (connection_flushed_some(conn)<0) {
  3134. if (!conn->marked_for_close)
  3135. connection_mark_for_close(conn);
  3136. return;
  3137. }
  3138. output = bufferevent_get_output(bufev);
  3139. if (!evbuffer_get_length(output)) {
  3140. connection_finished_flushing(conn);
  3141. if (conn->marked_for_close && conn->hold_open_until_flushed) {
  3142. conn->hold_open_until_flushed = 0;
  3143. if (conn->linked) {
  3144. /* send eof */
  3145. bufferevent_flush(conn->bufev, EV_WRITE, BEV_FINISHED);
  3146. }
  3147. }
  3148. }
  3149. }
  3150. /** Callback: invoked whenever a bufferevent has had an event (like a
  3151. * connection, or an eof, or an error) occur. */
  3152. void
  3153. connection_handle_event_cb(struct bufferevent *bufev, short event, void *arg)
  3154. {
  3155. connection_t *conn = arg;
  3156. (void) bufev;
  3157. if (conn->marked_for_close)
  3158. return;
  3159. if (event & BEV_EVENT_CONNECTED) {
  3160. tor_assert(connection_state_is_connecting(conn));
  3161. if (connection_finished_connecting(conn)<0)
  3162. return;
  3163. }
  3164. if (event & BEV_EVENT_EOF) {
  3165. if (!conn->marked_for_close) {
  3166. conn->inbuf_reached_eof = 1;
  3167. if (connection_reached_eof(conn)<0)
  3168. return;
  3169. }
  3170. }
  3171. if (event & BEV_EVENT_ERROR) {
  3172. int socket_error = evutil_socket_geterror(conn->s);
  3173. if (conn->type == CONN_TYPE_OR &&
  3174. conn->state == OR_CONN_STATE_CONNECTING) {
  3175. connection_or_connect_failed(TO_OR_CONN(conn),
  3176. errno_to_orconn_end_reason(socket_error),
  3177. tor_socket_strerror(socket_error));
  3178. } else if (CONN_IS_EDGE(conn)) {
  3179. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  3180. if (!edge_conn->edge_has_sent_end)
  3181. connection_edge_end_errno(edge_conn);
  3182. if (conn->type == CONN_TYPE_AP && TO_ENTRY_CONN(conn)->socks_request) {
  3183. /* broken, don't send a socks reply back */
  3184. TO_ENTRY_CONN(conn)->socks_request->has_finished = 1;
  3185. }
  3186. }
  3187. connection_close_immediate(conn); /* Connection is dead. */
  3188. if (!conn->marked_for_close)
  3189. connection_mark_for_close(conn);
  3190. }
  3191. }
  3192. /** Set up the generic callbacks for the bufferevent on <b>conn</b>. */
  3193. void
  3194. connection_configure_bufferevent_callbacks(connection_t *conn)
  3195. {
  3196. struct bufferevent *bufev;
  3197. struct evbuffer *input, *output;
  3198. tor_assert(conn->bufev);
  3199. bufev = conn->bufev;
  3200. bufferevent_setcb(bufev,
  3201. connection_handle_read_cb,
  3202. connection_handle_write_cb,
  3203. connection_handle_event_cb,
  3204. conn);
  3205. /* Set a fairly high write low-watermark so that we get the write callback
  3206. called whenever data is written to bring us under 128K. Leave the
  3207. high-watermark at 0.
  3208. */
  3209. bufferevent_setwatermark(bufev, EV_WRITE, 128*1024, 0);
  3210. input = bufferevent_get_input(bufev);
  3211. output = bufferevent_get_output(bufev);
  3212. evbuffer_add_cb(input, evbuffer_inbuf_callback, conn);
  3213. evbuffer_add_cb(output, evbuffer_outbuf_callback, conn);
  3214. }
  3215. #endif
  3216. /** A pass-through to fetch_from_buf. */
  3217. int
  3218. connection_fetch_from_buf(char *string, size_t len, connection_t *conn)
  3219. {
  3220. IF_HAS_BUFFEREVENT(conn, {
  3221. /* XXX overflow -seb */
  3222. return (int)bufferevent_read(conn->bufev, string, len);
  3223. }) ELSE_IF_NO_BUFFEREVENT {
  3224. return fetch_from_buf(string, len, conn->inbuf);
  3225. }
  3226. }
  3227. /** As fetch_from_buf_line(), but read from a connection's input buffer. */
  3228. int
  3229. connection_fetch_from_buf_line(connection_t *conn, char *data,
  3230. size_t *data_len)
  3231. {
  3232. IF_HAS_BUFFEREVENT(conn, {
  3233. int r;
  3234. size_t eol_len=0;
  3235. struct evbuffer *input = bufferevent_get_input(conn->bufev);
  3236. struct evbuffer_ptr ptr =
  3237. evbuffer_search_eol(input, NULL, &eol_len, EVBUFFER_EOL_LF);
  3238. if (ptr.pos == -1)
  3239. return 0; /* No EOL found. */
  3240. if ((size_t)ptr.pos+eol_len >= *data_len) {
  3241. return -1; /* Too long */
  3242. }
  3243. *data_len = ptr.pos+eol_len;
  3244. r = evbuffer_remove(input, data, ptr.pos+eol_len);
  3245. tor_assert(r >= 0);
  3246. data[ptr.pos+eol_len] = '\0';
  3247. return 1;
  3248. }) ELSE_IF_NO_BUFFEREVENT {
  3249. return fetch_from_buf_line(conn->inbuf, data, data_len);
  3250. }
  3251. }
  3252. /** As fetch_from_buf_http, but fetches from a conncetion's input buffer_t or
  3253. * its bufferevent as appropriate. */
  3254. int
  3255. connection_fetch_from_buf_http(connection_t *conn,
  3256. char **headers_out, size_t max_headerlen,
  3257. char **body_out, size_t *body_used,
  3258. size_t max_bodylen, int force_complete)
  3259. {
  3260. IF_HAS_BUFFEREVENT(conn, {
  3261. struct evbuffer *input = bufferevent_get_input(conn->bufev);
  3262. return fetch_from_evbuffer_http(input, headers_out, max_headerlen,
  3263. body_out, body_used, max_bodylen, force_complete);
  3264. }) ELSE_IF_NO_BUFFEREVENT {
  3265. return fetch_from_buf_http(conn->inbuf, headers_out, max_headerlen,
  3266. body_out, body_used, max_bodylen, force_complete);
  3267. }
  3268. }
  3269. /** Return conn-\>outbuf_flushlen: how many bytes conn wants to flush
  3270. * from its outbuf. */
  3271. int
  3272. connection_wants_to_flush(connection_t *conn)
  3273. {
  3274. return conn->outbuf_flushlen > 0;
  3275. }
  3276. /** Are there too many bytes on edge connection <b>conn</b>'s outbuf to
  3277. * send back a relay-level sendme yet? Return 1 if so, 0 if not. Used by
  3278. * connection_edge_consider_sending_sendme().
  3279. */
  3280. int
  3281. connection_outbuf_too_full(connection_t *conn)
  3282. {
  3283. return (conn->outbuf_flushlen > 10*CELL_PAYLOAD_SIZE);
  3284. }
  3285. /** Try to flush more bytes onto <b>conn</b>-\>s.
  3286. *
  3287. * This function gets called either from conn_write_callback() in main.c
  3288. * when libevent tells us that conn wants to write, or below
  3289. * from connection_write_to_buf() when an entire TLS record is ready.
  3290. *
  3291. * Update <b>conn</b>-\>timestamp_lastwritten to now, and call flush_buf
  3292. * or flush_buf_tls appropriately. If it succeeds and there are no more
  3293. * more bytes on <b>conn</b>-\>outbuf, then call connection_finished_flushing
  3294. * on it too.
  3295. *
  3296. * If <b>force</b>, then write as many bytes as possible, ignoring bandwidth
  3297. * limits. (Used for flushing messages to controller connections on fatal
  3298. * errors.)
  3299. *
  3300. * Mark the connection and return -1 if you want to close it, else
  3301. * return 0.
  3302. */
  3303. static int
  3304. connection_handle_write_impl(connection_t *conn, int force)
  3305. {
  3306. int e;
  3307. socklen_t len=(socklen_t)sizeof(e);
  3308. int result;
  3309. ssize_t max_to_write;
  3310. time_t now = approx_time();
  3311. size_t n_read = 0, n_written = 0;
  3312. int dont_stop_writing = 0;
  3313. tor_assert(!connection_is_listener(conn));
  3314. if (conn->marked_for_close || !SOCKET_OK(conn->s))
  3315. return 0; /* do nothing */
  3316. if (conn->in_flushed_some) {
  3317. log_warn(LD_BUG, "called recursively from inside conn->in_flushed_some");
  3318. return 0;
  3319. }
  3320. conn->timestamp_lastwritten = now;
  3321. /* Sometimes, "writable" means "connected". */
  3322. if (connection_state_is_connecting(conn)) {
  3323. if (getsockopt(conn->s, SOL_SOCKET, SO_ERROR, (void*)&e, &len) < 0) {
  3324. log_warn(LD_BUG, "getsockopt() syscall failed");
  3325. if (CONN_IS_EDGE(conn))
  3326. connection_edge_end_errno(TO_EDGE_CONN(conn));
  3327. connection_mark_for_close(conn);
  3328. return -1;
  3329. }
  3330. if (e) {
  3331. /* some sort of error, but maybe just inprogress still */
  3332. if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
  3333. log_info(LD_NET,"in-progress connect failed. Removing. (%s)",
  3334. tor_socket_strerror(e));
  3335. if (CONN_IS_EDGE(conn))
  3336. connection_edge_end_errno(TO_EDGE_CONN(conn));
  3337. if (conn->type == CONN_TYPE_OR)
  3338. connection_or_notify_error(TO_OR_CONN(conn),
  3339. errno_to_orconn_end_reason(e),
  3340. tor_socket_strerror(e));
  3341. connection_close_immediate(conn);
  3342. /*
  3343. * This can bypass normal channel checking since we did
  3344. * connection_or_notify_error() above.
  3345. */
  3346. connection_mark_for_close_internal(conn);
  3347. return -1;
  3348. } else {
  3349. return 0; /* no change, see if next time is better */
  3350. }
  3351. }
  3352. /* The connection is successful. */
  3353. if (connection_finished_connecting(conn)<0)
  3354. return -1;
  3355. }
  3356. max_to_write = force ? (ssize_t)conn->outbuf_flushlen
  3357. : connection_bucket_write_limit(conn, now);
  3358. if (connection_speaks_cells(conn) &&
  3359. conn->state > OR_CONN_STATE_PROXY_HANDSHAKING) {
  3360. or_connection_t *or_conn = TO_OR_CONN(conn);
  3361. size_t initial_size;
  3362. if (conn->state == OR_CONN_STATE_TLS_HANDSHAKING ||
  3363. conn->state == OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING) {
  3364. connection_stop_writing(conn);
  3365. if (connection_tls_continue_handshake(or_conn) < 0) {
  3366. /* Don't flush; connection is dead. */
  3367. connection_or_notify_error(or_conn,
  3368. END_OR_CONN_REASON_MISC,
  3369. "TLS error in connection_tls_"
  3370. "continue_handshake()");
  3371. connection_close_immediate(conn);
  3372. /*
  3373. * This can bypass normal channel checking since we did
  3374. * connection_or_notify_error() above.
  3375. */
  3376. connection_mark_for_close_internal(conn);
  3377. return -1;
  3378. }
  3379. return 0;
  3380. } else if (conn->state == OR_CONN_STATE_TLS_SERVER_RENEGOTIATING) {
  3381. return connection_handle_read(conn);
  3382. }
  3383. /* else open, or closing */
  3384. initial_size = buf_datalen(conn->outbuf);
  3385. result = flush_buf_tls(or_conn->tls, conn->outbuf,
  3386. max_to_write, &conn->outbuf_flushlen);
  3387. /* If we just flushed the last bytes, tell the channel on the
  3388. * or_conn to check if it needs to geoip_change_dirreq_state() */
  3389. /* XXXX move this to flushed_some or finished_flushing -NM */
  3390. if (buf_datalen(conn->outbuf) == 0 && or_conn->chan)
  3391. channel_notify_flushed(TLS_CHAN_TO_BASE(or_conn->chan));
  3392. switch (result) {
  3393. CASE_TOR_TLS_ERROR_ANY:
  3394. case TOR_TLS_CLOSE:
  3395. log_info(LD_NET, result != TOR_TLS_CLOSE ?
  3396. "tls error. breaking.":"TLS connection closed on flush");
  3397. /* Don't flush; connection is dead. */
  3398. connection_or_notify_error(or_conn,
  3399. END_OR_CONN_REASON_MISC,
  3400. result != TOR_TLS_CLOSE ?
  3401. "TLS error in during flush" :
  3402. "TLS closed during flush");
  3403. connection_close_immediate(conn);
  3404. /*
  3405. * This can bypass normal channel checking since we did
  3406. * connection_or_notify_error() above.
  3407. */
  3408. connection_mark_for_close_internal(conn);
  3409. return -1;
  3410. case TOR_TLS_WANTWRITE:
  3411. log_debug(LD_NET,"wanted write.");
  3412. /* we're already writing */
  3413. dont_stop_writing = 1;
  3414. break;
  3415. case TOR_TLS_WANTREAD:
  3416. /* Make sure to avoid a loop if the receive buckets are empty. */
  3417. log_debug(LD_NET,"wanted read.");
  3418. if (!connection_is_reading(conn)) {
  3419. connection_stop_writing(conn);
  3420. conn->write_blocked_on_bw = 1;
  3421. /* we'll start reading again when we get more tokens in our
  3422. * read bucket; then we'll start writing again too.
  3423. */
  3424. }
  3425. /* else no problem, we're already reading */
  3426. return 0;
  3427. /* case TOR_TLS_DONE:
  3428. * for TOR_TLS_DONE, fall through to check if the flushlen
  3429. * is empty, so we can stop writing.
  3430. */
  3431. }
  3432. tor_tls_get_n_raw_bytes(or_conn->tls, &n_read, &n_written);
  3433. log_debug(LD_GENERAL, "After TLS write of %d: %ld read, %ld written",
  3434. result, (long)n_read, (long)n_written);
  3435. /* So we notice bytes were written even on error */
  3436. /* XXXX024 This cast is safe since we can never write INT_MAX bytes in a
  3437. * single set of TLS operations. But it looks kinda ugly. If we refactor
  3438. * the *_buf_tls functions, we should make them return ssize_t or size_t
  3439. * or something. */
  3440. result = (int)(initial_size-buf_datalen(conn->outbuf));
  3441. } else {
  3442. CONN_LOG_PROTECT(conn,
  3443. result = flush_buf(conn->s, conn->outbuf,
  3444. max_to_write, &conn->outbuf_flushlen));
  3445. if (result < 0) {
  3446. if (CONN_IS_EDGE(conn))
  3447. connection_edge_end_errno(TO_EDGE_CONN(conn));
  3448. if (conn->type == CONN_TYPE_AP) {
  3449. /* writing failed; we couldn't send a SOCKS reply if we wanted to */
  3450. TO_ENTRY_CONN(conn)->socks_request->has_finished = 1;
  3451. }
  3452. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  3453. connection_mark_for_close(conn);
  3454. return -1;
  3455. }
  3456. n_written = (size_t) result;
  3457. }
  3458. if (n_written && conn->type == CONN_TYPE_AP) {
  3459. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  3460. circuit_t *circ = circuit_get_by_edge_conn(edge_conn);
  3461. origin_circuit_t *ocirc;
  3462. /* Check for overflow: */
  3463. if (PREDICT_LIKELY(UINT32_MAX - edge_conn->n_written > n_written))
  3464. edge_conn->n_written += (int)n_written;
  3465. else
  3466. edge_conn->n_written = UINT32_MAX;
  3467. if (circ && CIRCUIT_IS_ORIGIN(circ)) {
  3468. ocirc = TO_ORIGIN_CIRCUIT(circ);
  3469. if (PREDICT_LIKELY(UINT32_MAX - ocirc->n_written_circ_bw > n_written))
  3470. ocirc->n_written_circ_bw += (int)n_written;
  3471. else
  3472. ocirc->n_written_circ_bw = UINT32_MAX;
  3473. }
  3474. }
  3475. /* If CONN_BW events are enabled, update conn->n_written_conn_bw for
  3476. * OR/DIR/EXIT connections, checking for overflow. */
  3477. if (n_written && get_options()->TestingEnableConnBwEvent &&
  3478. (conn->type == CONN_TYPE_OR ||
  3479. conn->type == CONN_TYPE_DIR ||
  3480. conn->type == CONN_TYPE_EXIT)) {
  3481. if (PREDICT_LIKELY(UINT32_MAX - conn->n_written_conn_bw > n_written))
  3482. conn->n_written_conn_bw += (int)n_written;
  3483. else
  3484. conn->n_written_conn_bw = UINT32_MAX;
  3485. }
  3486. connection_buckets_decrement(conn, approx_time(), n_read, n_written);
  3487. if (result > 0) {
  3488. /* If we wrote any bytes from our buffer, then call the appropriate
  3489. * functions. */
  3490. if (connection_flushed_some(conn) < 0) {
  3491. if (connection_speaks_cells(conn)) {
  3492. connection_or_notify_error(TO_OR_CONN(conn),
  3493. END_OR_CONN_REASON_MISC,
  3494. "Got error back from "
  3495. "connection_flushed_some()");
  3496. }
  3497. /*
  3498. * This can bypass normal channel checking since we did
  3499. * connection_or_notify_error() above.
  3500. */
  3501. connection_mark_for_close_internal(conn);
  3502. }
  3503. }
  3504. if (!connection_wants_to_flush(conn) &&
  3505. !dont_stop_writing) { /* it's done flushing */
  3506. if (connection_finished_flushing(conn) < 0) {
  3507. /* already marked */
  3508. return -1;
  3509. }
  3510. return 0;
  3511. }
  3512. /* Call even if result is 0, since the global write bucket may
  3513. * have reached 0 on a different conn, and this guy needs to
  3514. * know to stop writing. */
  3515. connection_consider_empty_write_buckets(conn);
  3516. if (n_read > 0 && connection_is_reading(conn))
  3517. connection_consider_empty_read_buckets(conn);
  3518. return 0;
  3519. }
  3520. /* DOCDOC connection_handle_write */
  3521. int
  3522. connection_handle_write(connection_t *conn, int force)
  3523. {
  3524. int res;
  3525. tor_gettimeofday_cache_clear();
  3526. conn->in_connection_handle_write = 1;
  3527. res = connection_handle_write_impl(conn, force);
  3528. conn->in_connection_handle_write = 0;
  3529. return res;
  3530. }
  3531. /**
  3532. * Try to flush data that's waiting for a write on <b>conn</b>. Return
  3533. * -1 on failure, 0 on success.
  3534. *
  3535. * Don't use this function for regular writing; the buffers/bufferevents
  3536. * system should be good enough at scheduling writes there. Instead, this
  3537. * function is for cases when we're about to exit or something and we want
  3538. * to report it right away.
  3539. */
  3540. int
  3541. connection_flush(connection_t *conn)
  3542. {
  3543. IF_HAS_BUFFEREVENT(conn, {
  3544. int r = bufferevent_flush(conn->bufev, EV_WRITE, BEV_FLUSH);
  3545. return (r < 0) ? -1 : 0;
  3546. });
  3547. return connection_handle_write(conn, 1);
  3548. }
  3549. /** Append <b>len</b> bytes of <b>string</b> onto <b>conn</b>'s
  3550. * outbuf, and ask it to start writing.
  3551. *
  3552. * If <b>zlib</b> is nonzero, this is a directory connection that should get
  3553. * its contents compressed or decompressed as they're written. If zlib is
  3554. * negative, this is the last data to be compressed, and the connection's zlib
  3555. * state should be flushed.
  3556. *
  3557. * If it's a local control connection and a 64k chunk is ready, try to flush
  3558. * it all, so we don't end up with many megabytes of controller info queued at
  3559. * once.
  3560. */
  3561. MOCK_IMPL(void,
  3562. connection_write_to_buf_impl_,(const char *string, size_t len,
  3563. connection_t *conn, int zlib))
  3564. {
  3565. /* XXXX This function really needs to return -1 on failure. */
  3566. int r;
  3567. size_t old_datalen;
  3568. if (!len && !(zlib<0))
  3569. return;
  3570. /* if it's marked for close, only allow write if we mean to flush it */
  3571. if (conn->marked_for_close && !conn->hold_open_until_flushed)
  3572. return;
  3573. IF_HAS_BUFFEREVENT(conn, {
  3574. if (zlib) {
  3575. int done = zlib < 0;
  3576. r = write_to_evbuffer_zlib(bufferevent_get_output(conn->bufev),
  3577. TO_DIR_CONN(conn)->zlib_state,
  3578. string, len, done);
  3579. } else {
  3580. r = bufferevent_write(conn->bufev, string, len);
  3581. }
  3582. if (r < 0) {
  3583. /* XXXX mark for close? */
  3584. log_warn(LD_NET, "bufferevent_write failed! That shouldn't happen.");
  3585. }
  3586. return;
  3587. });
  3588. old_datalen = buf_datalen(conn->outbuf);
  3589. if (zlib) {
  3590. dir_connection_t *dir_conn = TO_DIR_CONN(conn);
  3591. int done = zlib < 0;
  3592. CONN_LOG_PROTECT(conn, r = write_to_buf_zlib(conn->outbuf,
  3593. dir_conn->zlib_state,
  3594. string, len, done));
  3595. } else {
  3596. CONN_LOG_PROTECT(conn, r = write_to_buf(string, len, conn->outbuf));
  3597. }
  3598. if (r < 0) {
  3599. if (CONN_IS_EDGE(conn)) {
  3600. /* if it failed, it means we have our package/delivery windows set
  3601. wrong compared to our max outbuf size. close the whole circuit. */
  3602. log_warn(LD_NET,
  3603. "write_to_buf failed. Closing circuit (fd %d).", (int)conn->s);
  3604. circuit_mark_for_close(circuit_get_by_edge_conn(TO_EDGE_CONN(conn)),
  3605. END_CIRC_REASON_INTERNAL);
  3606. } else {
  3607. log_warn(LD_NET,
  3608. "write_to_buf failed. Closing connection (fd %d).",
  3609. (int)conn->s);
  3610. connection_mark_for_close(conn);
  3611. }
  3612. return;
  3613. }
  3614. /* If we receive optimistic data in the EXIT_CONN_STATE_RESOLVING
  3615. * state, we don't want to try to write it right away, since
  3616. * conn->write_event won't be set yet. Otherwise, write data from
  3617. * this conn as the socket is available. */
  3618. if (conn->write_event) {
  3619. connection_start_writing(conn);
  3620. }
  3621. if (zlib) {
  3622. conn->outbuf_flushlen += buf_datalen(conn->outbuf) - old_datalen;
  3623. } else {
  3624. conn->outbuf_flushlen += len;
  3625. /* Should we try flushing the outbuf now? */
  3626. if (conn->in_flushed_some) {
  3627. /* Don't flush the outbuf when the reason we're writing more stuff is
  3628. * _because_ we flushed the outbuf. That's unfair. */
  3629. return;
  3630. }
  3631. if (conn->type == CONN_TYPE_CONTROL &&
  3632. !connection_is_rate_limited(conn) &&
  3633. conn->outbuf_flushlen-len < 1<<16 &&
  3634. conn->outbuf_flushlen >= 1<<16) {
  3635. /* just try to flush all of it */
  3636. } else
  3637. return; /* no need to try flushing */
  3638. if (connection_handle_write(conn, 0) < 0) {
  3639. if (!conn->marked_for_close) {
  3640. /* this connection is broken. remove it. */
  3641. log_warn(LD_BUG, "unhandled error on write for "
  3642. "conn (type %d, fd %d); removing",
  3643. conn->type, (int)conn->s);
  3644. tor_fragile_assert();
  3645. /* do a close-immediate here, so we don't try to flush */
  3646. connection_close_immediate(conn);
  3647. }
  3648. return;
  3649. }
  3650. }
  3651. }
  3652. /** Return a connection with given type, address, port, and purpose;
  3653. * or NULL if no such connection exists. */
  3654. connection_t *
  3655. connection_get_by_type_addr_port_purpose(int type,
  3656. const tor_addr_t *addr, uint16_t port,
  3657. int purpose)
  3658. {
  3659. smartlist_t *conns = get_connection_array();
  3660. SMARTLIST_FOREACH(conns, connection_t *, conn,
  3661. {
  3662. if (conn->type == type &&
  3663. tor_addr_eq(&conn->addr, addr) &&
  3664. conn->port == port &&
  3665. conn->purpose == purpose &&
  3666. !conn->marked_for_close)
  3667. return conn;
  3668. });
  3669. return NULL;
  3670. }
  3671. /** Return the stream with id <b>id</b> if it is not already marked for
  3672. * close.
  3673. */
  3674. connection_t *
  3675. connection_get_by_global_id(uint64_t id)
  3676. {
  3677. smartlist_t *conns = get_connection_array();
  3678. SMARTLIST_FOREACH(conns, connection_t *, conn,
  3679. {
  3680. if (conn->global_identifier == id)
  3681. return conn;
  3682. });
  3683. return NULL;
  3684. }
  3685. /** Return a connection of type <b>type</b> that is not marked for close.
  3686. */
  3687. connection_t *
  3688. connection_get_by_type(int type)
  3689. {
  3690. smartlist_t *conns = get_connection_array();
  3691. SMARTLIST_FOREACH(conns, connection_t *, conn,
  3692. {
  3693. if (conn->type == type && !conn->marked_for_close)
  3694. return conn;
  3695. });
  3696. return NULL;
  3697. }
  3698. /** Return a connection of type <b>type</b> that is in state <b>state</b>,
  3699. * and that is not marked for close.
  3700. */
  3701. connection_t *
  3702. connection_get_by_type_state(int type, int state)
  3703. {
  3704. smartlist_t *conns = get_connection_array();
  3705. SMARTLIST_FOREACH(conns, connection_t *, conn,
  3706. {
  3707. if (conn->type == type && conn->state == state && !conn->marked_for_close)
  3708. return conn;
  3709. });
  3710. return NULL;
  3711. }
  3712. /** Return a connection of type <b>type</b> that has rendquery equal
  3713. * to <b>rendquery</b>, and that is not marked for close. If state
  3714. * is non-zero, conn must be of that state too.
  3715. */
  3716. connection_t *
  3717. connection_get_by_type_state_rendquery(int type, int state,
  3718. const char *rendquery)
  3719. {
  3720. smartlist_t *conns = get_connection_array();
  3721. tor_assert(type == CONN_TYPE_DIR ||
  3722. type == CONN_TYPE_AP || type == CONN_TYPE_EXIT);
  3723. tor_assert(rendquery);
  3724. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  3725. if (conn->type == type &&
  3726. !conn->marked_for_close &&
  3727. (!state || state == conn->state)) {
  3728. if (type == CONN_TYPE_DIR &&
  3729. TO_DIR_CONN(conn)->rend_data &&
  3730. !rend_cmp_service_ids(rendquery,
  3731. TO_DIR_CONN(conn)->rend_data->onion_address))
  3732. return conn;
  3733. else if (CONN_IS_EDGE(conn) &&
  3734. TO_EDGE_CONN(conn)->rend_data &&
  3735. !rend_cmp_service_ids(rendquery,
  3736. TO_EDGE_CONN(conn)->rend_data->onion_address))
  3737. return conn;
  3738. }
  3739. } SMARTLIST_FOREACH_END(conn);
  3740. return NULL;
  3741. }
  3742. /** Return a directory connection (if any one exists) that is fetching
  3743. * the item described by <b>state</b>/<b>resource</b> */
  3744. dir_connection_t *
  3745. connection_dir_get_by_purpose_and_resource(int purpose,
  3746. const char *resource)
  3747. {
  3748. smartlist_t *conns = get_connection_array();
  3749. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  3750. dir_connection_t *dirconn;
  3751. if (conn->type != CONN_TYPE_DIR || conn->marked_for_close ||
  3752. conn->purpose != purpose)
  3753. continue;
  3754. dirconn = TO_DIR_CONN(conn);
  3755. if (dirconn->requested_resource == NULL) {
  3756. if (resource == NULL)
  3757. return dirconn;
  3758. } else if (resource) {
  3759. if (0 == strcmp(resource, dirconn->requested_resource))
  3760. return dirconn;
  3761. }
  3762. } SMARTLIST_FOREACH_END(conn);
  3763. return NULL;
  3764. }
  3765. /** Return 1 if there are any active OR connections apart from
  3766. * <b>this_conn</b>.
  3767. *
  3768. * We use this to guess if we should tell the controller that we
  3769. * didn't manage to connect to any of our bridges. */
  3770. int
  3771. any_other_active_or_conns(const or_connection_t *this_conn)
  3772. {
  3773. smartlist_t *conns = get_connection_array();
  3774. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  3775. if (conn == TO_CONN(this_conn)) { /* don't consider this conn */
  3776. continue;
  3777. }
  3778. if (conn->type == CONN_TYPE_OR &&
  3779. !conn->marked_for_close) {
  3780. log_debug(LD_DIR, "%s: Found an OR connection: %s",
  3781. __func__, conn->address);
  3782. return 1;
  3783. }
  3784. } SMARTLIST_FOREACH_END(conn);
  3785. return 0;
  3786. }
  3787. /** Return 1 if <b>conn</b> is a listener conn, else return 0. */
  3788. int
  3789. connection_is_listener(connection_t *conn)
  3790. {
  3791. if (conn->type == CONN_TYPE_OR_LISTENER ||
  3792. conn->type == CONN_TYPE_EXT_OR_LISTENER ||
  3793. conn->type == CONN_TYPE_AP_LISTENER ||
  3794. conn->type == CONN_TYPE_AP_TRANS_LISTENER ||
  3795. conn->type == CONN_TYPE_AP_DNS_LISTENER ||
  3796. conn->type == CONN_TYPE_AP_NATD_LISTENER ||
  3797. conn->type == CONN_TYPE_DIR_LISTENER ||
  3798. conn->type == CONN_TYPE_CONTROL_LISTENER)
  3799. return 1;
  3800. return 0;
  3801. }
  3802. /** Return 1 if <b>conn</b> is in state "open" and is not marked
  3803. * for close, else return 0.
  3804. */
  3805. int
  3806. connection_state_is_open(connection_t *conn)
  3807. {
  3808. tor_assert(conn);
  3809. if (conn->marked_for_close)
  3810. return 0;
  3811. if ((conn->type == CONN_TYPE_OR && conn->state == OR_CONN_STATE_OPEN) ||
  3812. (conn->type == CONN_TYPE_EXT_OR) ||
  3813. (conn->type == CONN_TYPE_AP && conn->state == AP_CONN_STATE_OPEN) ||
  3814. (conn->type == CONN_TYPE_EXIT && conn->state == EXIT_CONN_STATE_OPEN) ||
  3815. (conn->type == CONN_TYPE_CONTROL &&
  3816. conn->state == CONTROL_CONN_STATE_OPEN))
  3817. return 1;
  3818. return 0;
  3819. }
  3820. /** Return 1 if conn is in 'connecting' state, else return 0. */
  3821. int
  3822. connection_state_is_connecting(connection_t *conn)
  3823. {
  3824. tor_assert(conn);
  3825. if (conn->marked_for_close)
  3826. return 0;
  3827. switch (conn->type)
  3828. {
  3829. case CONN_TYPE_OR:
  3830. return conn->state == OR_CONN_STATE_CONNECTING;
  3831. case CONN_TYPE_EXIT:
  3832. return conn->state == EXIT_CONN_STATE_CONNECTING;
  3833. case CONN_TYPE_DIR:
  3834. return conn->state == DIR_CONN_STATE_CONNECTING;
  3835. }
  3836. return 0;
  3837. }
  3838. /** Allocates a base64'ed authenticator for use in http or https
  3839. * auth, based on the input string <b>authenticator</b>. Returns it
  3840. * if success, else returns NULL. */
  3841. char *
  3842. alloc_http_authenticator(const char *authenticator)
  3843. {
  3844. /* an authenticator in Basic authentication
  3845. * is just the string "username:password" */
  3846. const size_t authenticator_length = strlen(authenticator);
  3847. /* The base64_encode function needs a minimum buffer length
  3848. * of 66 bytes. */
  3849. const size_t base64_authenticator_length = (authenticator_length/48+1)*66;
  3850. char *base64_authenticator = tor_malloc(base64_authenticator_length);
  3851. if (base64_encode(base64_authenticator, base64_authenticator_length,
  3852. authenticator, authenticator_length) < 0) {
  3853. tor_free(base64_authenticator); /* free and set to null */
  3854. } else {
  3855. int i = 0, j = 0;
  3856. ssize_t len = strlen(base64_authenticator);
  3857. /* remove all newline occurrences within the string */
  3858. for (i=0; i < len; ++i) {
  3859. if ('\n' != base64_authenticator[i]) {
  3860. base64_authenticator[j] = base64_authenticator[i];
  3861. ++j;
  3862. }
  3863. }
  3864. base64_authenticator[j]='\0';
  3865. }
  3866. return base64_authenticator;
  3867. }
  3868. /** Given a socket handle, check whether the local address (sockname) of the
  3869. * socket is one that we've connected from before. If so, double-check
  3870. * whether our address has changed and we need to generate keys. If we do,
  3871. * call init_keys().
  3872. */
  3873. static void
  3874. client_check_address_changed(tor_socket_t sock)
  3875. {
  3876. struct sockaddr_storage out_sockaddr;
  3877. socklen_t out_addr_len = (socklen_t) sizeof(out_sockaddr);
  3878. tor_addr_t out_addr, iface_addr;
  3879. tor_addr_t **last_interface_ip_ptr;
  3880. sa_family_t family;
  3881. if (!outgoing_addrs)
  3882. outgoing_addrs = smartlist_new();
  3883. if (getsockname(sock, (struct sockaddr*)&out_sockaddr, &out_addr_len)<0) {
  3884. int e = tor_socket_errno(sock);
  3885. log_warn(LD_NET, "getsockname() to check for address change failed: %s",
  3886. tor_socket_strerror(e));
  3887. return;
  3888. }
  3889. tor_addr_from_sockaddr(&out_addr, (struct sockaddr*)&out_sockaddr, NULL);
  3890. family = tor_addr_family(&out_addr);
  3891. if (family == AF_INET)
  3892. last_interface_ip_ptr = &last_interface_ipv4;
  3893. else if (family == AF_INET6)
  3894. last_interface_ip_ptr = &last_interface_ipv6;
  3895. else
  3896. return;
  3897. if (! *last_interface_ip_ptr) {
  3898. tor_addr_t *a = tor_malloc_zero(sizeof(tor_addr_t));
  3899. if (get_interface_address6(LOG_INFO, family, a)==0) {
  3900. *last_interface_ip_ptr = a;
  3901. } else {
  3902. tor_free(a);
  3903. }
  3904. }
  3905. /* If we've used this address previously, we're okay. */
  3906. SMARTLIST_FOREACH(outgoing_addrs, const tor_addr_t *, a_ptr,
  3907. if (tor_addr_eq(a_ptr, &out_addr))
  3908. return;
  3909. );
  3910. /* Uh-oh. We haven't connected from this address before. Has the interface
  3911. * address changed? */
  3912. if (get_interface_address6(LOG_INFO, family, &iface_addr)<0)
  3913. return;
  3914. if (tor_addr_eq(&iface_addr, *last_interface_ip_ptr)) {
  3915. /* Nope, it hasn't changed. Add this address to the list. */
  3916. smartlist_add(outgoing_addrs, tor_memdup(&out_addr, sizeof(tor_addr_t)));
  3917. } else {
  3918. /* The interface changed. We're a client, so we need to regenerate our
  3919. * keys. First, reset the state. */
  3920. log_notice(LD_NET, "Our IP address has changed. Rotating keys...");
  3921. tor_addr_copy(*last_interface_ip_ptr, &iface_addr);
  3922. SMARTLIST_FOREACH(outgoing_addrs, tor_addr_t*, a_ptr, tor_free(a_ptr));
  3923. smartlist_clear(outgoing_addrs);
  3924. smartlist_add(outgoing_addrs, tor_memdup(&out_addr, sizeof(tor_addr_t)));
  3925. /* Okay, now change our keys. */
  3926. ip_address_changed(1);
  3927. }
  3928. }
  3929. /** Some systems have limited system buffers for recv and xmit on
  3930. * sockets allocated in a virtual server or similar environment. For a Tor
  3931. * server this can produce the "Error creating network socket: No buffer
  3932. * space available" error once all available TCP buffer space is consumed.
  3933. * This method will attempt to constrain the buffers allocated for the socket
  3934. * to the desired size to stay below system TCP buffer limits.
  3935. */
  3936. static void
  3937. set_constrained_socket_buffers(tor_socket_t sock, int size)
  3938. {
  3939. void *sz = (void*)&size;
  3940. socklen_t sz_sz = (socklen_t) sizeof(size);
  3941. if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, sz, sz_sz) < 0) {
  3942. int e = tor_socket_errno(sock);
  3943. log_warn(LD_NET, "setsockopt() to constrain send "
  3944. "buffer to %d bytes failed: %s", size, tor_socket_strerror(e));
  3945. }
  3946. if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, sz, sz_sz) < 0) {
  3947. int e = tor_socket_errno(sock);
  3948. log_warn(LD_NET, "setsockopt() to constrain recv "
  3949. "buffer to %d bytes failed: %s", size, tor_socket_strerror(e));
  3950. }
  3951. }
  3952. /** Process new bytes that have arrived on conn-\>inbuf.
  3953. *
  3954. * This function just passes conn to the connection-specific
  3955. * connection_*_process_inbuf() function. It also passes in
  3956. * package_partial if wanted.
  3957. */
  3958. static int
  3959. connection_process_inbuf(connection_t *conn, int package_partial)
  3960. {
  3961. tor_assert(conn);
  3962. switch (conn->type) {
  3963. case CONN_TYPE_OR:
  3964. return connection_or_process_inbuf(TO_OR_CONN(conn));
  3965. case CONN_TYPE_EXT_OR:
  3966. return connection_ext_or_process_inbuf(TO_OR_CONN(conn));
  3967. case CONN_TYPE_EXIT:
  3968. case CONN_TYPE_AP:
  3969. return connection_edge_process_inbuf(TO_EDGE_CONN(conn),
  3970. package_partial);
  3971. case CONN_TYPE_DIR:
  3972. return connection_dir_process_inbuf(TO_DIR_CONN(conn));
  3973. case CONN_TYPE_CPUWORKER:
  3974. return connection_cpu_process_inbuf(conn);
  3975. case CONN_TYPE_CONTROL:
  3976. return connection_control_process_inbuf(TO_CONTROL_CONN(conn));
  3977. default:
  3978. log_err(LD_BUG,"got unexpected conn type %d.", conn->type);
  3979. tor_fragile_assert();
  3980. return -1;
  3981. }
  3982. }
  3983. /** Called whenever we've written data on a connection. */
  3984. static int
  3985. connection_flushed_some(connection_t *conn)
  3986. {
  3987. int r = 0;
  3988. tor_assert(!conn->in_flushed_some);
  3989. conn->in_flushed_some = 1;
  3990. if (conn->type == CONN_TYPE_DIR &&
  3991. conn->state == DIR_CONN_STATE_SERVER_WRITING) {
  3992. r = connection_dirserv_flushed_some(TO_DIR_CONN(conn));
  3993. } else if (conn->type == CONN_TYPE_OR) {
  3994. r = connection_or_flushed_some(TO_OR_CONN(conn));
  3995. } else if (CONN_IS_EDGE(conn)) {
  3996. r = connection_edge_flushed_some(TO_EDGE_CONN(conn));
  3997. }
  3998. conn->in_flushed_some = 0;
  3999. return r;
  4000. }
  4001. /** We just finished flushing bytes to the appropriately low network layer,
  4002. * and there are no more bytes remaining in conn-\>outbuf, conn-\>bev, or
  4003. * conn-\>tls to be flushed.
  4004. *
  4005. * This function just passes conn to the connection-specific
  4006. * connection_*_finished_flushing() function.
  4007. */
  4008. static int
  4009. connection_finished_flushing(connection_t *conn)
  4010. {
  4011. tor_assert(conn);
  4012. /* If the connection is closed, don't try to do anything more here. */
  4013. if (CONN_IS_CLOSED(conn))
  4014. return 0;
  4015. // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
  4016. IF_HAS_NO_BUFFEREVENT(conn)
  4017. connection_stop_writing(conn);
  4018. switch (conn->type) {
  4019. case CONN_TYPE_OR:
  4020. return connection_or_finished_flushing(TO_OR_CONN(conn));
  4021. case CONN_TYPE_EXT_OR:
  4022. return connection_ext_or_finished_flushing(TO_OR_CONN(conn));
  4023. case CONN_TYPE_AP:
  4024. case CONN_TYPE_EXIT:
  4025. return connection_edge_finished_flushing(TO_EDGE_CONN(conn));
  4026. case CONN_TYPE_DIR:
  4027. return connection_dir_finished_flushing(TO_DIR_CONN(conn));
  4028. case CONN_TYPE_CPUWORKER:
  4029. return connection_cpu_finished_flushing(conn);
  4030. case CONN_TYPE_CONTROL:
  4031. return connection_control_finished_flushing(TO_CONTROL_CONN(conn));
  4032. default:
  4033. log_err(LD_BUG,"got unexpected conn type %d.", conn->type);
  4034. tor_fragile_assert();
  4035. return -1;
  4036. }
  4037. }
  4038. /** Called when our attempt to connect() to another server has just
  4039. * succeeded.
  4040. *
  4041. * This function just passes conn to the connection-specific
  4042. * connection_*_finished_connecting() function.
  4043. */
  4044. static int
  4045. connection_finished_connecting(connection_t *conn)
  4046. {
  4047. tor_assert(conn);
  4048. if (!server_mode(get_options())) {
  4049. /* See whether getsockname() says our address changed. We need to do this
  4050. * now that the connection has finished, because getsockname() on Windows
  4051. * won't work until then. */
  4052. client_check_address_changed(conn->s);
  4053. }
  4054. switch (conn->type)
  4055. {
  4056. case CONN_TYPE_OR:
  4057. return connection_or_finished_connecting(TO_OR_CONN(conn));
  4058. case CONN_TYPE_EXIT:
  4059. return connection_edge_finished_connecting(TO_EDGE_CONN(conn));
  4060. case CONN_TYPE_DIR:
  4061. return connection_dir_finished_connecting(TO_DIR_CONN(conn));
  4062. default:
  4063. log_err(LD_BUG,"got unexpected conn type %d.", conn->type);
  4064. tor_fragile_assert();
  4065. return -1;
  4066. }
  4067. }
  4068. /** Callback: invoked when a connection reaches an EOF event. */
  4069. static int
  4070. connection_reached_eof(connection_t *conn)
  4071. {
  4072. switch (conn->type) {
  4073. case CONN_TYPE_OR:
  4074. case CONN_TYPE_EXT_OR:
  4075. return connection_or_reached_eof(TO_OR_CONN(conn));
  4076. case CONN_TYPE_AP:
  4077. case CONN_TYPE_EXIT:
  4078. return connection_edge_reached_eof(TO_EDGE_CONN(conn));
  4079. case CONN_TYPE_DIR:
  4080. return connection_dir_reached_eof(TO_DIR_CONN(conn));
  4081. case CONN_TYPE_CPUWORKER:
  4082. return connection_cpu_reached_eof(conn);
  4083. case CONN_TYPE_CONTROL:
  4084. return connection_control_reached_eof(TO_CONTROL_CONN(conn));
  4085. default:
  4086. log_err(LD_BUG,"got unexpected conn type %d.", conn->type);
  4087. tor_fragile_assert();
  4088. return -1;
  4089. }
  4090. }
  4091. /** Log how many bytes are used by buffers of different kinds and sizes. */
  4092. void
  4093. connection_dump_buffer_mem_stats(int severity)
  4094. {
  4095. uint64_t used_by_type[CONN_TYPE_MAX_+1];
  4096. uint64_t alloc_by_type[CONN_TYPE_MAX_+1];
  4097. int n_conns_by_type[CONN_TYPE_MAX_+1];
  4098. uint64_t total_alloc = 0;
  4099. uint64_t total_used = 0;
  4100. int i;
  4101. smartlist_t *conns = get_connection_array();
  4102. memset(used_by_type, 0, sizeof(used_by_type));
  4103. memset(alloc_by_type, 0, sizeof(alloc_by_type));
  4104. memset(n_conns_by_type, 0, sizeof(n_conns_by_type));
  4105. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, c) {
  4106. int tp = c->type;
  4107. ++n_conns_by_type[tp];
  4108. if (c->inbuf) {
  4109. used_by_type[tp] += buf_datalen(c->inbuf);
  4110. alloc_by_type[tp] += buf_allocation(c->inbuf);
  4111. }
  4112. if (c->outbuf) {
  4113. used_by_type[tp] += buf_datalen(c->outbuf);
  4114. alloc_by_type[tp] += buf_allocation(c->outbuf);
  4115. }
  4116. } SMARTLIST_FOREACH_END(c);
  4117. for (i=0; i <= CONN_TYPE_MAX_; ++i) {
  4118. total_used += used_by_type[i];
  4119. total_alloc += alloc_by_type[i];
  4120. }
  4121. tor_log(severity, LD_GENERAL,
  4122. "In buffers for %d connections: "U64_FORMAT" used/"U64_FORMAT" allocated",
  4123. smartlist_len(conns),
  4124. U64_PRINTF_ARG(total_used), U64_PRINTF_ARG(total_alloc));
  4125. for (i=CONN_TYPE_MIN_; i <= CONN_TYPE_MAX_; ++i) {
  4126. if (!n_conns_by_type[i])
  4127. continue;
  4128. tor_log(severity, LD_GENERAL,
  4129. " For %d %s connections: "U64_FORMAT" used/"U64_FORMAT" allocated",
  4130. n_conns_by_type[i], conn_type_to_string(i),
  4131. U64_PRINTF_ARG(used_by_type[i]), U64_PRINTF_ARG(alloc_by_type[i]));
  4132. }
  4133. }
  4134. /** Verify that connection <b>conn</b> has all of its invariants
  4135. * correct. Trigger an assert if anything is invalid.
  4136. */
  4137. void
  4138. assert_connection_ok(connection_t *conn, time_t now)
  4139. {
  4140. (void) now; /* XXXX unused. */
  4141. tor_assert(conn);
  4142. tor_assert(conn->type >= CONN_TYPE_MIN_);
  4143. tor_assert(conn->type <= CONN_TYPE_MAX_);
  4144. #ifdef USE_BUFFEREVENTS
  4145. if (conn->bufev) {
  4146. tor_assert(conn->read_event == NULL);
  4147. tor_assert(conn->write_event == NULL);
  4148. tor_assert(conn->inbuf == NULL);
  4149. tor_assert(conn->outbuf == NULL);
  4150. }
  4151. #endif
  4152. switch (conn->type) {
  4153. case CONN_TYPE_OR:
  4154. case CONN_TYPE_EXT_OR:
  4155. tor_assert(conn->magic == OR_CONNECTION_MAGIC);
  4156. break;
  4157. case CONN_TYPE_AP:
  4158. tor_assert(conn->magic == ENTRY_CONNECTION_MAGIC);
  4159. break;
  4160. case CONN_TYPE_EXIT:
  4161. tor_assert(conn->magic == EDGE_CONNECTION_MAGIC);
  4162. break;
  4163. case CONN_TYPE_DIR:
  4164. tor_assert(conn->magic == DIR_CONNECTION_MAGIC);
  4165. break;
  4166. case CONN_TYPE_CONTROL:
  4167. tor_assert(conn->magic == CONTROL_CONNECTION_MAGIC);
  4168. break;
  4169. CASE_ANY_LISTENER_TYPE:
  4170. tor_assert(conn->magic == LISTENER_CONNECTION_MAGIC);
  4171. break;
  4172. default:
  4173. tor_assert(conn->magic == BASE_CONNECTION_MAGIC);
  4174. break;
  4175. }
  4176. if (conn->linked_conn) {
  4177. tor_assert(conn->linked_conn->linked_conn == conn);
  4178. tor_assert(conn->linked);
  4179. }
  4180. if (conn->linked)
  4181. tor_assert(!SOCKET_OK(conn->s));
  4182. if (conn->outbuf_flushlen > 0) {
  4183. /* With optimistic data, we may have queued data in
  4184. * EXIT_CONN_STATE_RESOLVING while the conn is not yet marked to writing.
  4185. * */
  4186. tor_assert((conn->type == CONN_TYPE_EXIT &&
  4187. conn->state == EXIT_CONN_STATE_RESOLVING) ||
  4188. connection_is_writing(conn) ||
  4189. conn->write_blocked_on_bw ||
  4190. (CONN_IS_EDGE(conn) &&
  4191. TO_EDGE_CONN(conn)->edge_blocked_on_circ));
  4192. }
  4193. if (conn->hold_open_until_flushed)
  4194. tor_assert(conn->marked_for_close);
  4195. /* XXXX check: read_blocked_on_bw, write_blocked_on_bw, s, conn_array_index,
  4196. * marked_for_close. */
  4197. /* buffers */
  4198. if (conn->inbuf)
  4199. assert_buf_ok(conn->inbuf);
  4200. if (conn->outbuf)
  4201. assert_buf_ok(conn->outbuf);
  4202. if (conn->type == CONN_TYPE_OR) {
  4203. or_connection_t *or_conn = TO_OR_CONN(conn);
  4204. if (conn->state == OR_CONN_STATE_OPEN) {
  4205. /* tor_assert(conn->bandwidth > 0); */
  4206. /* the above isn't necessarily true: if we just did a TLS
  4207. * handshake but we didn't recognize the other peer, or it
  4208. * gave a bad cert/etc, then we won't have assigned bandwidth,
  4209. * yet it will be open. -RD
  4210. */
  4211. // tor_assert(conn->read_bucket >= 0);
  4212. }
  4213. // tor_assert(conn->addr && conn->port);
  4214. tor_assert(conn->address);
  4215. if (conn->state > OR_CONN_STATE_PROXY_HANDSHAKING)
  4216. tor_assert(or_conn->tls);
  4217. }
  4218. if (CONN_IS_EDGE(conn)) {
  4219. /* XXX unchecked: package window, deliver window. */
  4220. if (conn->type == CONN_TYPE_AP) {
  4221. entry_connection_t *entry_conn = TO_ENTRY_CONN(conn);
  4222. if (entry_conn->chosen_exit_optional || entry_conn->chosen_exit_retries)
  4223. tor_assert(entry_conn->chosen_exit_name);
  4224. tor_assert(entry_conn->socks_request);
  4225. if (conn->state == AP_CONN_STATE_OPEN) {
  4226. tor_assert(entry_conn->socks_request->has_finished);
  4227. if (!conn->marked_for_close) {
  4228. tor_assert(ENTRY_TO_EDGE_CONN(entry_conn)->cpath_layer);
  4229. assert_cpath_layer_ok(ENTRY_TO_EDGE_CONN(entry_conn)->cpath_layer);
  4230. }
  4231. }
  4232. }
  4233. if (conn->type == CONN_TYPE_EXIT) {
  4234. tor_assert(conn->purpose == EXIT_PURPOSE_CONNECT ||
  4235. conn->purpose == EXIT_PURPOSE_RESOLVE);
  4236. }
  4237. } else if (conn->type == CONN_TYPE_DIR) {
  4238. } else {
  4239. /* Purpose is only used for dir and exit types currently */
  4240. tor_assert(!conn->purpose);
  4241. }
  4242. switch (conn->type)
  4243. {
  4244. CASE_ANY_LISTENER_TYPE:
  4245. tor_assert(conn->state == LISTENER_STATE_READY);
  4246. break;
  4247. case CONN_TYPE_OR:
  4248. tor_assert(conn->state >= OR_CONN_STATE_MIN_);
  4249. tor_assert(conn->state <= OR_CONN_STATE_MAX_);
  4250. break;
  4251. case CONN_TYPE_EXT_OR:
  4252. tor_assert(conn->state >= EXT_OR_CONN_STATE_MIN_);
  4253. tor_assert(conn->state <= EXT_OR_CONN_STATE_MAX_);
  4254. break;
  4255. case CONN_TYPE_EXIT:
  4256. tor_assert(conn->state >= EXIT_CONN_STATE_MIN_);
  4257. tor_assert(conn->state <= EXIT_CONN_STATE_MAX_);
  4258. tor_assert(conn->purpose >= EXIT_PURPOSE_MIN_);
  4259. tor_assert(conn->purpose <= EXIT_PURPOSE_MAX_);
  4260. break;
  4261. case CONN_TYPE_AP:
  4262. tor_assert(conn->state >= AP_CONN_STATE_MIN_);
  4263. tor_assert(conn->state <= AP_CONN_STATE_MAX_);
  4264. tor_assert(TO_ENTRY_CONN(conn)->socks_request);
  4265. break;
  4266. case CONN_TYPE_DIR:
  4267. tor_assert(conn->state >= DIR_CONN_STATE_MIN_);
  4268. tor_assert(conn->state <= DIR_CONN_STATE_MAX_);
  4269. tor_assert(conn->purpose >= DIR_PURPOSE_MIN_);
  4270. tor_assert(conn->purpose <= DIR_PURPOSE_MAX_);
  4271. break;
  4272. case CONN_TYPE_CPUWORKER:
  4273. tor_assert(conn->state >= CPUWORKER_STATE_MIN_);
  4274. tor_assert(conn->state <= CPUWORKER_STATE_MAX_);
  4275. break;
  4276. case CONN_TYPE_CONTROL:
  4277. tor_assert(conn->state >= CONTROL_CONN_STATE_MIN_);
  4278. tor_assert(conn->state <= CONTROL_CONN_STATE_MAX_);
  4279. break;
  4280. default:
  4281. tor_assert(0);
  4282. }
  4283. }
  4284. /** Fills <b>addr</b> and <b>port</b> with the details of the global
  4285. * proxy server we are using.
  4286. * <b>conn</b> contains the connection we are using the proxy for.
  4287. *
  4288. * Return 0 on success, -1 on failure.
  4289. */
  4290. int
  4291. get_proxy_addrport(tor_addr_t *addr, uint16_t *port, int *proxy_type,
  4292. const connection_t *conn)
  4293. {
  4294. const or_options_t *options = get_options();
  4295. if (options->HTTPSProxy) {
  4296. tor_addr_copy(addr, &options->HTTPSProxyAddr);
  4297. *port = options->HTTPSProxyPort;
  4298. *proxy_type = PROXY_CONNECT;
  4299. return 0;
  4300. } else if (options->Socks4Proxy) {
  4301. tor_addr_copy(addr, &options->Socks4ProxyAddr);
  4302. *port = options->Socks4ProxyPort;
  4303. *proxy_type = PROXY_SOCKS4;
  4304. return 0;
  4305. } else if (options->Socks5Proxy) {
  4306. tor_addr_copy(addr, &options->Socks5ProxyAddr);
  4307. *port = options->Socks5ProxyPort;
  4308. *proxy_type = PROXY_SOCKS5;
  4309. return 0;
  4310. } else if (options->ClientTransportPlugin ||
  4311. options->Bridges) {
  4312. const transport_t *transport = NULL;
  4313. int r;
  4314. r = get_transport_by_bridge_addrport(&conn->addr, conn->port, &transport);
  4315. if (r<0)
  4316. return -1;
  4317. if (transport) { /* transport found */
  4318. tor_addr_copy(addr, &transport->addr);
  4319. *port = transport->port;
  4320. *proxy_type = transport->socks_version;
  4321. return 0;
  4322. }
  4323. }
  4324. *proxy_type = PROXY_NONE;
  4325. return 0;
  4326. }
  4327. /** Log a failed connection to a proxy server.
  4328. * <b>conn</b> is the connection we use the proxy server for. */
  4329. void
  4330. log_failed_proxy_connection(connection_t *conn)
  4331. {
  4332. tor_addr_t proxy_addr;
  4333. uint16_t proxy_port;
  4334. int proxy_type;
  4335. if (get_proxy_addrport(&proxy_addr, &proxy_port, &proxy_type, conn) != 0)
  4336. return; /* if we have no proxy set up, leave this function. */
  4337. log_warn(LD_NET,
  4338. "The connection to the %s proxy server at %s just failed. "
  4339. "Make sure that the proxy server is up and running.",
  4340. proxy_type_to_string(get_proxy_type()),
  4341. fmt_addrport(&proxy_addr, proxy_port));
  4342. }
  4343. /** Return string representation of <b>proxy_type</b>. */
  4344. static const char *
  4345. proxy_type_to_string(int proxy_type)
  4346. {
  4347. switch (proxy_type) {
  4348. case PROXY_CONNECT: return "HTTP";
  4349. case PROXY_SOCKS4: return "SOCKS4";
  4350. case PROXY_SOCKS5: return "SOCKS5";
  4351. case PROXY_PLUGGABLE: return "pluggable transports SOCKS";
  4352. case PROXY_NONE: return "NULL";
  4353. default: tor_assert(0);
  4354. }
  4355. return NULL; /*Unreached*/
  4356. }
  4357. /** Call connection_free_() on every connection in our array, and release all
  4358. * storage held by connection.c. This is used by cpuworkers and dnsworkers
  4359. * when they fork, so they don't keep resources held open (especially
  4360. * sockets).
  4361. *
  4362. * Don't do the checks in connection_free(), because they will
  4363. * fail.
  4364. */
  4365. void
  4366. connection_free_all(void)
  4367. {
  4368. smartlist_t *conns = get_connection_array();
  4369. /* We don't want to log any messages to controllers. */
  4370. SMARTLIST_FOREACH(conns, connection_t *, conn,
  4371. if (conn->type == CONN_TYPE_CONTROL)
  4372. TO_CONTROL_CONN(conn)->event_mask = 0);
  4373. control_update_global_event_mask();
  4374. /* Unlink everything from the identity map. */
  4375. connection_or_clear_identity_map();
  4376. connection_or_clear_ext_or_id_map();
  4377. /* Clear out our list of broken connections */
  4378. clear_broken_connection_map(0);
  4379. SMARTLIST_FOREACH(conns, connection_t *, conn, connection_free_(conn));
  4380. if (outgoing_addrs) {
  4381. SMARTLIST_FOREACH(outgoing_addrs, tor_addr_t *, addr, tor_free(addr));
  4382. smartlist_free(outgoing_addrs);
  4383. outgoing_addrs = NULL;
  4384. }
  4385. tor_free(last_interface_ipv4);
  4386. tor_free(last_interface_ipv6);
  4387. #ifdef USE_BUFFEREVENTS
  4388. if (global_rate_limit)
  4389. bufferevent_rate_limit_group_free(global_rate_limit);
  4390. #endif
  4391. }