connection.c 176 KB

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