connection.c 186 KB

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