connection.c 178 KB

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