connection.c 183 KB

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