connection.c 175 KB

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