connection.c 177 KB

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