connection.c 177 KB

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