connection.c 175 KB

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