connection.c 177 KB

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