connection.c 176 KB

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