connection.c 176 KB

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