connection.c 174 KB

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