connection.c 186 KB

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