connection.c 176 KB

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