connection.c 180 KB

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