connection.c 177 KB

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