connection.c 178 KB

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