connection.c 175 KB

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