connection.c 184 KB

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