connection.c 176 KB

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