connection.c 182 KB

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