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 "buffers.h"
  58. /*
  59. * Define this so we get channel internal functions, since we're implementing
  60. * part of a subclass (channel_tls_t).
  61. */
  62. #define TOR_CHANNEL_INTERNAL_
  63. #define CONNECTION_PRIVATE
  64. #include "backtrace.h"
  65. #include "channel.h"
  66. #include "channeltls.h"
  67. #include "circuitbuild.h"
  68. #include "circuitlist.h"
  69. #include "circuituse.h"
  70. #include "config.h"
  71. #include "connection.h"
  72. #include "connection_edge.h"
  73. #include "connection_or.h"
  74. #include "control.h"
  75. #include "directory.h"
  76. #include "dirserv.h"
  77. #include "dns.h"
  78. #include "dnsserv.h"
  79. #include "entrynodes.h"
  80. #include "ext_orport.h"
  81. #include "geoip.h"
  82. #include "main.h"
  83. #include "nodelist.h"
  84. #include "policies.h"
  85. #include "reasons.h"
  86. #include "relay.h"
  87. #include "rendclient.h"
  88. #include "rendcommon.h"
  89. #include "rephist.h"
  90. #include "router.h"
  91. #include "routerlist.h"
  92. #include "transports.h"
  93. #include "routerparse.h"
  94. #include "sandbox.h"
  95. #include "transports.h"
  96. #ifdef HAVE_PWD_H
  97. #include <pwd.h>
  98. #endif
  99. #ifdef HAVE_SYS_UN_H
  100. #include <sys/socket.h>
  101. #include <sys/un.h>
  102. #endif
  103. static connection_t *connection_listener_new(
  104. const struct sockaddr *listensockaddr,
  105. socklen_t listensocklen, int type,
  106. const char *address,
  107. const port_cfg_t *portcfg);
  108. static void connection_init(time_t now, connection_t *conn, int type,
  109. int socket_family);
  110. static int connection_init_accepted_conn(connection_t *conn,
  111. const listener_connection_t *listener);
  112. static int connection_handle_listener_read(connection_t *conn, int new_type);
  113. static int connection_bucket_should_increase(int bucket,
  114. or_connection_t *conn);
  115. static int connection_finished_flushing(connection_t *conn);
  116. static int connection_flushed_some(connection_t *conn);
  117. static int connection_finished_connecting(connection_t *conn);
  118. static int connection_reached_eof(connection_t *conn);
  119. static int connection_read_to_buf(connection_t *conn, ssize_t *max_to_read,
  120. int *socket_error);
  121. static int connection_process_inbuf(connection_t *conn, int package_partial);
  122. static void client_check_address_changed(tor_socket_t sock);
  123. static void set_constrained_socket_buffers(tor_socket_t sock, int size);
  124. static const char *connection_proxy_state_to_string(int state);
  125. static int connection_read_https_proxy_response(connection_t *conn);
  126. static void connection_send_socks5_connect(connection_t *conn);
  127. static const char *proxy_type_to_string(int proxy_type);
  128. static int get_proxy_type(void);
  129. /** The last addresses that our network interface seemed to have been
  130. * binding to. We use this as one way to detect when our IP changes.
  131. *
  132. * XXXX+ We should really use the entire list of interfaces here.
  133. **/
  134. static tor_addr_t *last_interface_ipv4 = NULL;
  135. /* DOCDOC last_interface_ipv6 */
  136. static tor_addr_t *last_interface_ipv6 = NULL;
  137. /** A list of tor_addr_t for addresses we've used in outgoing connections.
  138. * Used to detect IP address changes. */
  139. static smartlist_t *outgoing_addrs = NULL;
  140. #define CASE_ANY_LISTENER_TYPE \
  141. case CONN_TYPE_OR_LISTENER: \
  142. case CONN_TYPE_EXT_OR_LISTENER: \
  143. case CONN_TYPE_AP_LISTENER: \
  144. case CONN_TYPE_DIR_LISTENER: \
  145. case CONN_TYPE_CONTROL_LISTENER: \
  146. case CONN_TYPE_AP_TRANS_LISTENER: \
  147. case CONN_TYPE_AP_NATD_LISTENER: \
  148. case CONN_TYPE_AP_DNS_LISTENER
  149. /**************************************************************/
  150. /**
  151. * Return the human-readable name for the connection type <b>type</b>
  152. */
  153. const char *
  154. conn_type_to_string(int type)
  155. {
  156. static char buf[64];
  157. switch (type) {
  158. case CONN_TYPE_OR_LISTENER: return "OR listener";
  159. case CONN_TYPE_OR: return "OR";
  160. case CONN_TYPE_EXIT: return "Exit";
  161. case CONN_TYPE_AP_LISTENER: return "Socks listener";
  162. case CONN_TYPE_AP_TRANS_LISTENER:
  163. return "Transparent pf/netfilter listener";
  164. case CONN_TYPE_AP_NATD_LISTENER: return "Transparent natd listener";
  165. case CONN_TYPE_AP_DNS_LISTENER: return "DNS listener";
  166. case CONN_TYPE_AP: return "Socks";
  167. case CONN_TYPE_DIR_LISTENER: return "Directory listener";
  168. case CONN_TYPE_DIR: return "Directory";
  169. case CONN_TYPE_CONTROL_LISTENER: return "Control listener";
  170. case CONN_TYPE_CONTROL: return "Control";
  171. case CONN_TYPE_EXT_OR: return "Extended OR";
  172. case CONN_TYPE_EXT_OR_LISTENER: return "Extended OR listener";
  173. default:
  174. log_warn(LD_BUG, "unknown connection type %d", type);
  175. tor_snprintf(buf, sizeof(buf), "unknown [%d]", type);
  176. return buf;
  177. }
  178. }
  179. /**
  180. * Return the human-readable name for the connection state <b>state</b>
  181. * for the connection type <b>type</b>
  182. */
  183. const char *
  184. conn_state_to_string(int type, int state)
  185. {
  186. static char buf[96];
  187. switch (type) {
  188. CASE_ANY_LISTENER_TYPE:
  189. if (state == LISTENER_STATE_READY)
  190. return "ready";
  191. break;
  192. case CONN_TYPE_OR:
  193. switch (state) {
  194. case OR_CONN_STATE_CONNECTING: return "connect()ing";
  195. case OR_CONN_STATE_PROXY_HANDSHAKING: return "handshaking (proxy)";
  196. case OR_CONN_STATE_TLS_HANDSHAKING: return "handshaking (TLS)";
  197. case OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING:
  198. return "renegotiating (TLS, v2 handshake)";
  199. case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING:
  200. return "waiting for renegotiation or V3 handshake";
  201. case OR_CONN_STATE_OR_HANDSHAKING_V2:
  202. return "handshaking (Tor, v2 handshake)";
  203. case OR_CONN_STATE_OR_HANDSHAKING_V3:
  204. return "handshaking (Tor, v3 handshake)";
  205. case OR_CONN_STATE_OPEN: return "open";
  206. }
  207. break;
  208. case CONN_TYPE_EXT_OR:
  209. switch (state) {
  210. case EXT_OR_CONN_STATE_AUTH_WAIT_AUTH_TYPE:
  211. return "waiting for authentication type";
  212. case EXT_OR_CONN_STATE_AUTH_WAIT_CLIENT_NONCE:
  213. return "waiting for client nonce";
  214. case EXT_OR_CONN_STATE_AUTH_WAIT_CLIENT_HASH:
  215. return "waiting for client hash";
  216. case EXT_OR_CONN_STATE_OPEN: return "open";
  217. case EXT_OR_CONN_STATE_FLUSHING: return "flushing final OKAY";
  218. }
  219. break;
  220. case CONN_TYPE_EXIT:
  221. switch (state) {
  222. case EXIT_CONN_STATE_RESOLVING: return "waiting for dest info";
  223. case EXIT_CONN_STATE_CONNECTING: return "connecting";
  224. case EXIT_CONN_STATE_OPEN: return "open";
  225. case EXIT_CONN_STATE_RESOLVEFAILED: return "resolve failed";
  226. }
  227. break;
  228. case CONN_TYPE_AP:
  229. switch (state) {
  230. case AP_CONN_STATE_SOCKS_WAIT: return "waiting for socks info";
  231. case AP_CONN_STATE_NATD_WAIT: return "waiting for natd dest info";
  232. case AP_CONN_STATE_RENDDESC_WAIT: return "waiting for rendezvous desc";
  233. case AP_CONN_STATE_CONTROLLER_WAIT: return "waiting for controller";
  234. case AP_CONN_STATE_CIRCUIT_WAIT: return "waiting for circuit";
  235. case AP_CONN_STATE_CONNECT_WAIT: return "waiting for connect response";
  236. case AP_CONN_STATE_RESOLVE_WAIT: return "waiting for resolve response";
  237. case AP_CONN_STATE_OPEN: return "open";
  238. }
  239. break;
  240. case CONN_TYPE_DIR:
  241. switch (state) {
  242. case DIR_CONN_STATE_CONNECTING: return "connecting";
  243. case DIR_CONN_STATE_CLIENT_SENDING: return "client sending";
  244. case DIR_CONN_STATE_CLIENT_READING: return "client reading";
  245. case DIR_CONN_STATE_CLIENT_FINISHED: return "client finished";
  246. case DIR_CONN_STATE_SERVER_COMMAND_WAIT: return "waiting for command";
  247. case DIR_CONN_STATE_SERVER_WRITING: return "writing";
  248. }
  249. break;
  250. case CONN_TYPE_CONTROL:
  251. switch (state) {
  252. case CONTROL_CONN_STATE_OPEN: return "open (protocol v1)";
  253. case CONTROL_CONN_STATE_NEEDAUTH:
  254. return "waiting for authentication (protocol v1)";
  255. }
  256. break;
  257. }
  258. log_warn(LD_BUG, "unknown connection state %d (type %d)", state, type);
  259. tor_snprintf(buf, sizeof(buf),
  260. "unknown state [%d] on unknown [%s] connection",
  261. state, conn_type_to_string(type));
  262. return buf;
  263. }
  264. /** Allocate and return a new dir_connection_t, initialized as by
  265. * connection_init(). */
  266. dir_connection_t *
  267. dir_connection_new(int socket_family)
  268. {
  269. dir_connection_t *dir_conn = tor_malloc_zero(sizeof(dir_connection_t));
  270. connection_init(time(NULL), TO_CONN(dir_conn), CONN_TYPE_DIR, socket_family);
  271. return dir_conn;
  272. }
  273. /** Allocate and return a new or_connection_t, initialized as by
  274. * connection_init().
  275. *
  276. * Initialize active_circuit_pqueue.
  277. *
  278. * Set active_circuit_pqueue_last_recalibrated to current cell_ewma tick.
  279. */
  280. or_connection_t *
  281. or_connection_new(int type, int socket_family)
  282. {
  283. or_connection_t *or_conn = tor_malloc_zero(sizeof(or_connection_t));
  284. time_t now = time(NULL);
  285. tor_assert(type == CONN_TYPE_OR || type == CONN_TYPE_EXT_OR);
  286. connection_init(now, TO_CONN(or_conn), type, socket_family);
  287. connection_or_set_canonical(or_conn, 0);
  288. if (type == CONN_TYPE_EXT_OR)
  289. connection_or_set_ext_or_identifier(or_conn);
  290. return or_conn;
  291. }
  292. /** Allocate and return a new entry_connection_t, initialized as by
  293. * connection_init().
  294. *
  295. * Allocate space to store the socks_request.
  296. */
  297. entry_connection_t *
  298. entry_connection_new(int type, int socket_family)
  299. {
  300. entry_connection_t *entry_conn = tor_malloc_zero(sizeof(entry_connection_t));
  301. tor_assert(type == CONN_TYPE_AP);
  302. connection_init(time(NULL), ENTRY_TO_CONN(entry_conn), type, socket_family);
  303. entry_conn->socks_request = socks_request_new();
  304. /* If this is coming from a listener, we'll set it up based on the listener
  305. * in a little while. Otherwise, we're doing this as a linked connection
  306. * of some kind, and we should set it up here based on the socket family */
  307. if (socket_family == AF_INET)
  308. entry_conn->entry_cfg.ipv4_traffic = 1;
  309. else if (socket_family == AF_INET6)
  310. entry_conn->entry_cfg.ipv6_traffic = 1;
  311. else if (socket_family == AF_UNIX)
  312. entry_conn->is_socks_socket = 1;
  313. return entry_conn;
  314. }
  315. /** Allocate and return a new edge_connection_t, initialized as by
  316. * connection_init(). */
  317. edge_connection_t *
  318. edge_connection_new(int type, int socket_family)
  319. {
  320. edge_connection_t *edge_conn = tor_malloc_zero(sizeof(edge_connection_t));
  321. tor_assert(type == CONN_TYPE_EXIT);
  322. connection_init(time(NULL), TO_CONN(edge_conn), type, socket_family);
  323. return edge_conn;
  324. }
  325. /** Allocate and return a new control_connection_t, initialized as by
  326. * connection_init(). */
  327. control_connection_t *
  328. control_connection_new(int socket_family)
  329. {
  330. control_connection_t *control_conn =
  331. tor_malloc_zero(sizeof(control_connection_t));
  332. connection_init(time(NULL),
  333. TO_CONN(control_conn), CONN_TYPE_CONTROL, socket_family);
  334. return control_conn;
  335. }
  336. /** Allocate and return a new listener_connection_t, initialized as by
  337. * connection_init(). */
  338. listener_connection_t *
  339. listener_connection_new(int type, int socket_family)
  340. {
  341. listener_connection_t *listener_conn =
  342. tor_malloc_zero(sizeof(listener_connection_t));
  343. connection_init(time(NULL), TO_CONN(listener_conn), type, socket_family);
  344. return listener_conn;
  345. }
  346. /** Allocate, initialize, and return a new connection_t subtype of <b>type</b>
  347. * to make or receive connections of address family <b>socket_family</b>. The
  348. * type should be one of the CONN_TYPE_* constants. */
  349. connection_t *
  350. connection_new(int type, int socket_family)
  351. {
  352. switch (type) {
  353. case CONN_TYPE_OR:
  354. case CONN_TYPE_EXT_OR:
  355. return TO_CONN(or_connection_new(type, socket_family));
  356. case CONN_TYPE_EXIT:
  357. return TO_CONN(edge_connection_new(type, socket_family));
  358. case CONN_TYPE_AP:
  359. return ENTRY_TO_CONN(entry_connection_new(type, socket_family));
  360. case CONN_TYPE_DIR:
  361. return TO_CONN(dir_connection_new(socket_family));
  362. case CONN_TYPE_CONTROL:
  363. return TO_CONN(control_connection_new(socket_family));
  364. CASE_ANY_LISTENER_TYPE:
  365. return TO_CONN(listener_connection_new(type, socket_family));
  366. default: {
  367. connection_t *conn = tor_malloc_zero(sizeof(connection_t));
  368. connection_init(time(NULL), conn, type, socket_family);
  369. return conn;
  370. }
  371. }
  372. }
  373. /** Initializes conn. (you must call connection_add() to link it into the main
  374. * array).
  375. *
  376. * Set conn-\>magic to the correct value.
  377. *
  378. * Set conn-\>type to <b>type</b>. Set conn-\>s and conn-\>conn_array_index to
  379. * -1 to signify they are not yet assigned.
  380. *
  381. * Initialize conn's timestamps to now.
  382. */
  383. static void
  384. connection_init(time_t now, connection_t *conn, int type, int socket_family)
  385. {
  386. static uint64_t n_connections_allocated = 1;
  387. switch (type) {
  388. case CONN_TYPE_OR:
  389. case CONN_TYPE_EXT_OR:
  390. conn->magic = OR_CONNECTION_MAGIC;
  391. break;
  392. case CONN_TYPE_EXIT:
  393. conn->magic = EDGE_CONNECTION_MAGIC;
  394. break;
  395. case CONN_TYPE_AP:
  396. conn->magic = ENTRY_CONNECTION_MAGIC;
  397. break;
  398. case CONN_TYPE_DIR:
  399. conn->magic = DIR_CONNECTION_MAGIC;
  400. break;
  401. case CONN_TYPE_CONTROL:
  402. conn->magic = CONTROL_CONNECTION_MAGIC;
  403. break;
  404. CASE_ANY_LISTENER_TYPE:
  405. conn->magic = LISTENER_CONNECTION_MAGIC;
  406. break;
  407. default:
  408. conn->magic = BASE_CONNECTION_MAGIC;
  409. break;
  410. }
  411. conn->s = TOR_INVALID_SOCKET; /* give it a default of 'not used' */
  412. conn->conn_array_index = -1; /* also default to 'not used' */
  413. conn->global_identifier = n_connections_allocated++;
  414. conn->type = type;
  415. conn->socket_family = socket_family;
  416. if (!connection_is_listener(conn)) {
  417. /* listeners never use their buf */
  418. conn->inbuf = buf_new();
  419. conn->outbuf = buf_new();
  420. }
  421. conn->timestamp_created = now;
  422. conn->timestamp_lastread = now;
  423. conn->timestamp_lastwritten = now;
  424. }
  425. /** Create a link between <b>conn_a</b> and <b>conn_b</b>. */
  426. void
  427. connection_link_connections(connection_t *conn_a, connection_t *conn_b)
  428. {
  429. tor_assert(! SOCKET_OK(conn_a->s));
  430. tor_assert(! SOCKET_OK(conn_b->s));
  431. conn_a->linked = 1;
  432. conn_b->linked = 1;
  433. conn_a->linked_conn = conn_b;
  434. conn_b->linked_conn = conn_a;
  435. }
  436. /** Return true iff the provided connection listener type supports AF_UNIX
  437. * sockets. */
  438. int
  439. conn_listener_type_supports_af_unix(int type)
  440. {
  441. /* For now only control ports or SOCKS ports can be Unix domain sockets
  442. * and listeners at the same time */
  443. switch (type) {
  444. case CONN_TYPE_CONTROL_LISTENER:
  445. case CONN_TYPE_AP_LISTENER:
  446. return 1;
  447. default:
  448. return 0;
  449. }
  450. }
  451. /** Deallocate memory used by <b>conn</b>. Deallocate its buffers if
  452. * necessary, close its socket if necessary, and mark the directory as dirty
  453. * if <b>conn</b> is an OR or OP connection.
  454. */
  455. STATIC void
  456. connection_free_(connection_t *conn)
  457. {
  458. void *mem;
  459. size_t memlen;
  460. if (!conn)
  461. return;
  462. switch (conn->type) {
  463. case CONN_TYPE_OR:
  464. case CONN_TYPE_EXT_OR:
  465. tor_assert(conn->magic == OR_CONNECTION_MAGIC);
  466. mem = TO_OR_CONN(conn);
  467. memlen = sizeof(or_connection_t);
  468. break;
  469. case CONN_TYPE_AP:
  470. tor_assert(conn->magic == ENTRY_CONNECTION_MAGIC);
  471. mem = TO_ENTRY_CONN(conn);
  472. memlen = sizeof(entry_connection_t);
  473. break;
  474. case CONN_TYPE_EXIT:
  475. tor_assert(conn->magic == EDGE_CONNECTION_MAGIC);
  476. mem = TO_EDGE_CONN(conn);
  477. memlen = sizeof(edge_connection_t);
  478. break;
  479. case CONN_TYPE_DIR:
  480. tor_assert(conn->magic == DIR_CONNECTION_MAGIC);
  481. mem = TO_DIR_CONN(conn);
  482. memlen = sizeof(dir_connection_t);
  483. break;
  484. case CONN_TYPE_CONTROL:
  485. tor_assert(conn->magic == CONTROL_CONNECTION_MAGIC);
  486. mem = TO_CONTROL_CONN(conn);
  487. memlen = sizeof(control_connection_t);
  488. break;
  489. CASE_ANY_LISTENER_TYPE:
  490. tor_assert(conn->magic == LISTENER_CONNECTION_MAGIC);
  491. mem = TO_LISTENER_CONN(conn);
  492. memlen = sizeof(listener_connection_t);
  493. break;
  494. default:
  495. tor_assert(conn->magic == BASE_CONNECTION_MAGIC);
  496. mem = conn;
  497. memlen = sizeof(connection_t);
  498. break;
  499. }
  500. if (conn->linked) {
  501. log_info(LD_GENERAL, "Freeing linked %s connection [%s] with %d "
  502. "bytes on inbuf, %d on outbuf.",
  503. conn_type_to_string(conn->type),
  504. conn_state_to_string(conn->type, conn->state),
  505. (int)connection_get_inbuf_len(conn),
  506. (int)connection_get_outbuf_len(conn));
  507. }
  508. if (!connection_is_listener(conn)) {
  509. buf_free(conn->inbuf);
  510. buf_free(conn->outbuf);
  511. } else {
  512. if (conn->socket_family == AF_UNIX) {
  513. /* For now only control and SOCKS ports can be Unix domain sockets
  514. * and listeners at the same time */
  515. tor_assert(conn_listener_type_supports_af_unix(conn->type));
  516. if (unlink(conn->address) < 0 && errno != ENOENT) {
  517. log_warn(LD_NET, "Could not unlink %s: %s", conn->address,
  518. strerror(errno));
  519. }
  520. }
  521. }
  522. tor_free(conn->address);
  523. if (connection_speaks_cells(conn)) {
  524. or_connection_t *or_conn = TO_OR_CONN(conn);
  525. tor_tls_free(or_conn->tls);
  526. or_conn->tls = NULL;
  527. or_handshake_state_free(or_conn->handshake_state);
  528. or_conn->handshake_state = NULL;
  529. tor_free(or_conn->nickname);
  530. if (or_conn->chan) {
  531. /* Owww, this shouldn't happen, but... */
  532. log_info(LD_CHANNEL,
  533. "Freeing orconn at %p, saw channel %p with ID "
  534. U64_FORMAT " left un-NULLed",
  535. or_conn, TLS_CHAN_TO_BASE(or_conn->chan),
  536. U64_PRINTF_ARG(
  537. TLS_CHAN_TO_BASE(or_conn->chan)->global_identifier));
  538. if (!CHANNEL_FINISHED(TLS_CHAN_TO_BASE(or_conn->chan))) {
  539. channel_close_for_error(TLS_CHAN_TO_BASE(or_conn->chan));
  540. }
  541. or_conn->chan->conn = NULL;
  542. or_conn->chan = NULL;
  543. }
  544. }
  545. if (conn->type == CONN_TYPE_AP) {
  546. entry_connection_t *entry_conn = TO_ENTRY_CONN(conn);
  547. tor_free(entry_conn->chosen_exit_name);
  548. tor_free(entry_conn->original_dest_address);
  549. if (entry_conn->socks_request)
  550. socks_request_free(entry_conn->socks_request);
  551. if (entry_conn->pending_optimistic_data) {
  552. buf_free(entry_conn->pending_optimistic_data);
  553. }
  554. if (entry_conn->sending_optimistic_data) {
  555. buf_free(entry_conn->sending_optimistic_data);
  556. }
  557. }
  558. if (CONN_IS_EDGE(conn)) {
  559. rend_data_free(TO_EDGE_CONN(conn)->rend_data);
  560. }
  561. if (conn->type == CONN_TYPE_CONTROL) {
  562. control_connection_t *control_conn = TO_CONTROL_CONN(conn);
  563. tor_free(control_conn->safecookie_client_hash);
  564. tor_free(control_conn->incoming_cmd);
  565. if (control_conn->ephemeral_onion_services) {
  566. SMARTLIST_FOREACH(control_conn->ephemeral_onion_services, char *, cp, {
  567. memwipe(cp, 0, strlen(cp));
  568. tor_free(cp);
  569. });
  570. smartlist_free(control_conn->ephemeral_onion_services);
  571. }
  572. }
  573. /* Probably already freed by connection_free. */
  574. tor_event_free(conn->read_event);
  575. tor_event_free(conn->write_event);
  576. conn->read_event = conn->write_event = NULL;
  577. if (conn->type == CONN_TYPE_DIR) {
  578. dir_connection_t *dir_conn = TO_DIR_CONN(conn);
  579. tor_free(dir_conn->requested_resource);
  580. tor_zlib_free(dir_conn->zlib_state);
  581. if (dir_conn->fingerprint_stack) {
  582. SMARTLIST_FOREACH(dir_conn->fingerprint_stack, char *, cp, tor_free(cp));
  583. smartlist_free(dir_conn->fingerprint_stack);
  584. }
  585. cached_dir_decref(dir_conn->cached_dir);
  586. rend_data_free(dir_conn->rend_data);
  587. }
  588. if (SOCKET_OK(conn->s)) {
  589. log_debug(LD_NET,"closing fd %d.",(int)conn->s);
  590. tor_close_socket(conn->s);
  591. conn->s = TOR_INVALID_SOCKET;
  592. }
  593. if (conn->type == CONN_TYPE_OR &&
  594. !tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest)) {
  595. log_warn(LD_BUG, "called on OR conn with non-zeroed identity_digest");
  596. connection_or_remove_from_identity_map(TO_OR_CONN(conn));
  597. }
  598. if (conn->type == CONN_TYPE_OR || conn->type == CONN_TYPE_EXT_OR) {
  599. connection_or_remove_from_ext_or_id_map(TO_OR_CONN(conn));
  600. tor_free(TO_OR_CONN(conn)->ext_or_conn_id);
  601. tor_free(TO_OR_CONN(conn)->ext_or_auth_correct_client_hash);
  602. tor_free(TO_OR_CONN(conn)->ext_or_transport);
  603. }
  604. memwipe(mem, 0xCC, memlen); /* poison memory */
  605. tor_free(mem);
  606. }
  607. /** Make sure <b>conn</b> isn't in any of the global conn lists; then free it.
  608. */
  609. MOCK_IMPL(void,
  610. connection_free,(connection_t *conn))
  611. {
  612. if (!conn)
  613. return;
  614. tor_assert(!connection_is_on_closeable_list(conn));
  615. tor_assert(!connection_in_array(conn));
  616. if (BUG(conn->linked_conn)) {
  617. conn->linked_conn->linked_conn = NULL;
  618. if (! conn->linked_conn->marked_for_close &&
  619. conn->linked_conn->reading_from_linked_conn)
  620. connection_start_reading(conn->linked_conn);
  621. conn->linked_conn = NULL;
  622. }
  623. if (connection_speaks_cells(conn)) {
  624. if (!tor_digest_is_zero(TO_OR_CONN(conn)->identity_digest)) {
  625. connection_or_remove_from_identity_map(TO_OR_CONN(conn));
  626. }
  627. }
  628. if (conn->type == CONN_TYPE_CONTROL) {
  629. connection_control_closed(TO_CONTROL_CONN(conn));
  630. }
  631. #if 1
  632. /* DEBUGGING */
  633. if (conn->type == CONN_TYPE_AP) {
  634. connection_ap_warn_and_unmark_if_pending_circ(TO_ENTRY_CONN(conn),
  635. "connection_free");
  636. }
  637. #endif
  638. connection_unregister_events(conn);
  639. connection_free_(conn);
  640. }
  641. /**
  642. * Called when we're about to finally unlink and free a connection:
  643. * perform necessary accounting and cleanup
  644. * - Directory conns that failed to fetch a rendezvous descriptor
  645. * need to inform pending rendezvous streams.
  646. * - OR conns need to call rep_hist_note_*() to record status.
  647. * - AP conns need to send a socks reject if necessary.
  648. * - Exit conns need to call connection_dns_remove() if necessary.
  649. * - AP and Exit conns need to send an end cell if they can.
  650. * - DNS conns need to fail any resolves that are pending on them.
  651. * - OR and edge connections need to be unlinked from circuits.
  652. */
  653. void
  654. connection_about_to_close_connection(connection_t *conn)
  655. {
  656. tor_assert(conn->marked_for_close);
  657. switch (conn->type) {
  658. case CONN_TYPE_DIR:
  659. connection_dir_about_to_close(TO_DIR_CONN(conn));
  660. break;
  661. case CONN_TYPE_OR:
  662. case CONN_TYPE_EXT_OR:
  663. connection_or_about_to_close(TO_OR_CONN(conn));
  664. break;
  665. case CONN_TYPE_AP:
  666. connection_ap_about_to_close(TO_ENTRY_CONN(conn));
  667. break;
  668. case CONN_TYPE_EXIT:
  669. connection_exit_about_to_close(TO_EDGE_CONN(conn));
  670. break;
  671. }
  672. }
  673. /** Return true iff connection_close_immediate() has been called on this
  674. * connection. */
  675. #define CONN_IS_CLOSED(c) \
  676. ((c)->linked ? ((c)->linked_conn_is_closed) : (! SOCKET_OK(c->s)))
  677. /** Close the underlying socket for <b>conn</b>, so we don't try to
  678. * flush it. Must be used in conjunction with (right before)
  679. * connection_mark_for_close().
  680. */
  681. void
  682. connection_close_immediate(connection_t *conn)
  683. {
  684. assert_connection_ok(conn,0);
  685. if (CONN_IS_CLOSED(conn)) {
  686. log_err(LD_BUG,"Attempt to close already-closed connection.");
  687. tor_fragile_assert();
  688. return;
  689. }
  690. if (conn->outbuf_flushlen) {
  691. log_info(LD_NET,"fd %d, type %s, state %s, %d bytes on outbuf.",
  692. (int)conn->s, conn_type_to_string(conn->type),
  693. conn_state_to_string(conn->type, conn->state),
  694. (int)conn->outbuf_flushlen);
  695. }
  696. connection_unregister_events(conn);
  697. if (SOCKET_OK(conn->s))
  698. tor_close_socket(conn->s);
  699. conn->s = TOR_INVALID_SOCKET;
  700. if (conn->linked)
  701. conn->linked_conn_is_closed = 1;
  702. if (conn->outbuf)
  703. buf_clear(conn->outbuf);
  704. conn->outbuf_flushlen = 0;
  705. }
  706. /** Mark <b>conn</b> to be closed next time we loop through
  707. * conn_close_if_marked() in main.c. */
  708. void
  709. connection_mark_for_close_(connection_t *conn, int line, const char *file)
  710. {
  711. assert_connection_ok(conn,0);
  712. tor_assert(line);
  713. tor_assert(line < 1<<16); /* marked_for_close can only fit a uint16_t. */
  714. tor_assert(file);
  715. if (conn->type == CONN_TYPE_OR) {
  716. /*
  717. * An or_connection should have been closed through one of the channel-
  718. * aware functions in connection_or.c. We'll assume this is an error
  719. * close and do that, and log a bug warning.
  720. */
  721. log_warn(LD_CHANNEL | LD_BUG,
  722. "Something tried to close an or_connection_t without going "
  723. "through channels at %s:%d",
  724. file, line);
  725. connection_or_close_for_error(TO_OR_CONN(conn), 0);
  726. } else {
  727. /* Pass it down to the real function */
  728. connection_mark_for_close_internal_(conn, line, file);
  729. }
  730. }
  731. /** Mark <b>conn</b> to be closed next time we loop through
  732. * conn_close_if_marked() in main.c; the _internal version bypasses the
  733. * CONN_TYPE_OR checks; this should be called when you either are sure that
  734. * if this is an or_connection_t the controlling channel has been notified
  735. * (e.g. with connection_or_notify_error()), or you actually are the
  736. * connection_or_close_for_error() or connection_or_close_normally function.
  737. * For all other cases, use connection_mark_and_flush() instead, which
  738. * checks for or_connection_t properly, instead. See below.
  739. */
  740. MOCK_IMPL(void,
  741. connection_mark_for_close_internal_, (connection_t *conn,
  742. int line, const char *file))
  743. {
  744. assert_connection_ok(conn,0);
  745. tor_assert(line);
  746. tor_assert(line < 1<<16); /* marked_for_close can only fit a uint16_t. */
  747. tor_assert(file);
  748. if (conn->marked_for_close) {
  749. log_warn(LD_BUG,"Duplicate call to connection_mark_for_close at %s:%d"
  750. " (first at %s:%d)", file, line, conn->marked_for_close_file,
  751. conn->marked_for_close);
  752. tor_fragile_assert();
  753. return;
  754. }
  755. if (conn->type == CONN_TYPE_OR) {
  756. /*
  757. * Bad news if this happens without telling the controlling channel; do
  758. * this so we can find things that call this wrongly when the asserts hit.
  759. */
  760. log_debug(LD_CHANNEL,
  761. "Calling connection_mark_for_close_internal_() on an OR conn "
  762. "at %s:%d",
  763. file, line);
  764. }
  765. conn->marked_for_close = line;
  766. conn->marked_for_close_file = file;
  767. add_connection_to_closeable_list(conn);
  768. /* in case we're going to be held-open-til-flushed, reset
  769. * the number of seconds since last successful write, so
  770. * we get our whole 15 seconds */
  771. conn->timestamp_lastwritten = time(NULL);
  772. }
  773. /** Find each connection that has hold_open_until_flushed set to
  774. * 1 but hasn't written in the past 15 seconds, and set
  775. * hold_open_until_flushed to 0. This means it will get cleaned
  776. * up in the next loop through close_if_marked() in main.c.
  777. */
  778. void
  779. connection_expire_held_open(void)
  780. {
  781. time_t now;
  782. smartlist_t *conns = get_connection_array();
  783. now = time(NULL);
  784. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  785. /* If we've been holding the connection open, but we haven't written
  786. * for 15 seconds...
  787. */
  788. if (conn->hold_open_until_flushed) {
  789. tor_assert(conn->marked_for_close);
  790. if (now - conn->timestamp_lastwritten >= 15) {
  791. int severity;
  792. if (conn->type == CONN_TYPE_EXIT ||
  793. (conn->type == CONN_TYPE_DIR &&
  794. conn->purpose == DIR_PURPOSE_SERVER))
  795. severity = LOG_INFO;
  796. else
  797. severity = LOG_NOTICE;
  798. log_fn(severity, LD_NET,
  799. "Giving up on marked_for_close conn that's been flushing "
  800. "for 15s (fd %d, type %s, state %s).",
  801. (int)conn->s, conn_type_to_string(conn->type),
  802. conn_state_to_string(conn->type, conn->state));
  803. conn->hold_open_until_flushed = 0;
  804. }
  805. }
  806. } SMARTLIST_FOREACH_END(conn);
  807. }
  808. #if defined(HAVE_SYS_UN_H) || defined(RUNNING_DOXYGEN)
  809. /** Create an AF_UNIX listenaddr struct.
  810. * <b>listenaddress</b> provides the path to the Unix socket.
  811. *
  812. * Eventually <b>listenaddress</b> will also optionally contain user, group,
  813. * and file permissions for the new socket. But not yet. XXX
  814. * Also, since we do not create the socket here the information doesn't help
  815. * here.
  816. *
  817. * If not NULL <b>readable_address</b> will contain a copy of the path part of
  818. * <b>listenaddress</b>.
  819. *
  820. * The listenaddr struct has to be freed by the caller.
  821. */
  822. static struct sockaddr_un *
  823. create_unix_sockaddr(const char *listenaddress, char **readable_address,
  824. socklen_t *len_out)
  825. {
  826. struct sockaddr_un *sockaddr = NULL;
  827. sockaddr = tor_malloc_zero(sizeof(struct sockaddr_un));
  828. sockaddr->sun_family = AF_UNIX;
  829. if (strlcpy(sockaddr->sun_path, listenaddress, sizeof(sockaddr->sun_path))
  830. >= sizeof(sockaddr->sun_path)) {
  831. log_warn(LD_CONFIG, "Unix socket path '%s' is too long to fit.",
  832. escaped(listenaddress));
  833. tor_free(sockaddr);
  834. return NULL;
  835. }
  836. if (readable_address)
  837. *readable_address = tor_strdup(listenaddress);
  838. *len_out = sizeof(struct sockaddr_un);
  839. return sockaddr;
  840. }
  841. #else
  842. static struct sockaddr *
  843. create_unix_sockaddr(const char *listenaddress, char **readable_address,
  844. socklen_t *len_out)
  845. {
  846. (void)listenaddress;
  847. (void)readable_address;
  848. log_fn(LOG_ERR, LD_BUG,
  849. "Unix domain sockets not supported, yet we tried to create one.");
  850. *len_out = 0;
  851. tor_fragile_assert();
  852. return NULL;
  853. }
  854. #endif /* HAVE_SYS_UN_H */
  855. /** Warn that an accept or a connect has failed because we're running out of
  856. * TCP sockets we can use on current system. Rate-limit these warnings so
  857. * that we don't spam the log. */
  858. static void
  859. warn_too_many_conns(void)
  860. {
  861. #define WARN_TOO_MANY_CONNS_INTERVAL (6*60*60)
  862. static ratelim_t last_warned = RATELIM_INIT(WARN_TOO_MANY_CONNS_INTERVAL);
  863. char *m;
  864. if ((m = rate_limit_log(&last_warned, approx_time()))) {
  865. int n_conns = get_n_open_sockets();
  866. log_warn(LD_NET,"Failing because we have %d connections already. Please "
  867. "read doc/TUNING for guidance.%s", n_conns, m);
  868. tor_free(m);
  869. control_event_general_status(LOG_WARN, "TOO_MANY_CONNECTIONS CURRENT=%d",
  870. n_conns);
  871. }
  872. }
  873. #ifdef HAVE_SYS_UN_H
  874. #define UNIX_SOCKET_PURPOSE_CONTROL_SOCKET 0
  875. #define UNIX_SOCKET_PURPOSE_SOCKS_SOCKET 1
  876. /** Check if the purpose isn't one of the ones we know what to do with */
  877. static int
  878. is_valid_unix_socket_purpose(int purpose)
  879. {
  880. int valid = 0;
  881. switch (purpose) {
  882. case UNIX_SOCKET_PURPOSE_CONTROL_SOCKET:
  883. case UNIX_SOCKET_PURPOSE_SOCKS_SOCKET:
  884. valid = 1;
  885. break;
  886. }
  887. return valid;
  888. }
  889. /** Return a string description of a unix socket purpose */
  890. static const char *
  891. unix_socket_purpose_to_string(int purpose)
  892. {
  893. const char *s = "unknown-purpose socket";
  894. switch (purpose) {
  895. case UNIX_SOCKET_PURPOSE_CONTROL_SOCKET:
  896. s = "control socket";
  897. break;
  898. case UNIX_SOCKET_PURPOSE_SOCKS_SOCKET:
  899. s = "SOCKS socket";
  900. break;
  901. }
  902. return s;
  903. }
  904. /** Check whether we should be willing to open an AF_UNIX socket in
  905. * <b>path</b>. Return 0 if we should go ahead and -1 if we shouldn't. */
  906. static int
  907. check_location_for_unix_socket(const or_options_t *options, const char *path,
  908. int purpose, const port_cfg_t *port)
  909. {
  910. int r = -1;
  911. char *p = NULL;
  912. tor_assert(is_valid_unix_socket_purpose(purpose));
  913. p = tor_strdup(path);
  914. cpd_check_t flags = CPD_CHECK_MODE_ONLY;
  915. if (get_parent_directory(p)<0 || p[0] != '/') {
  916. log_warn(LD_GENERAL, "Bad unix socket address '%s'. Tor does not support "
  917. "relative paths for unix sockets.", path);
  918. goto done;
  919. }
  920. if (port->is_world_writable) {
  921. /* World-writable sockets can go anywhere. */
  922. r = 0;
  923. goto done;
  924. }
  925. if (port->is_group_writable) {
  926. flags |= CPD_GROUP_OK;
  927. }
  928. if (port->relax_dirmode_check) {
  929. flags |= CPD_RELAX_DIRMODE_CHECK;
  930. }
  931. if (check_private_dir(p, flags, options->User) < 0) {
  932. char *escpath, *escdir;
  933. escpath = esc_for_log(path);
  934. escdir = esc_for_log(p);
  935. log_warn(LD_GENERAL, "Before Tor can create a %s in %s, the directory "
  936. "%s needs to exist, and to be accessible only by the user%s "
  937. "account that is running Tor. (On some Unix systems, anybody "
  938. "who can list a socket can connect to it, so Tor is being "
  939. "careful.)",
  940. unix_socket_purpose_to_string(purpose), escpath, escdir,
  941. port->is_group_writable ? " and group" : "");
  942. tor_free(escpath);
  943. tor_free(escdir);
  944. goto done;
  945. }
  946. r = 0;
  947. done:
  948. tor_free(p);
  949. return r;
  950. }
  951. #endif
  952. /** Tell the TCP stack that it shouldn't wait for a long time after
  953. * <b>sock</b> has closed before reusing its port. Return 0 on success,
  954. * -1 on failure. */
  955. static int
  956. make_socket_reuseable(tor_socket_t sock)
  957. {
  958. #ifdef _WIN32
  959. (void) sock;
  960. return 0;
  961. #else
  962. int one=1;
  963. /* REUSEADDR on normal places means you can rebind to the port
  964. * right after somebody else has let it go. But REUSEADDR on win32
  965. * means you can bind to the port _even when somebody else
  966. * already has it bound_. So, don't do that on Win32. */
  967. if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*) &one,
  968. (socklen_t)sizeof(one)) == -1) {
  969. return -1;
  970. }
  971. return 0;
  972. #endif
  973. }
  974. #ifdef _WIN32
  975. /** Tell the Windows TCP stack to prevent other applications from receiving
  976. * traffic from tor's open ports. Return 0 on success, -1 on failure. */
  977. static int
  978. make_win32_socket_exclusive(tor_socket_t sock)
  979. {
  980. #ifdef SO_EXCLUSIVEADDRUSE
  981. int one=1;
  982. /* Any socket that sets REUSEADDR on win32 can bind to a port _even when
  983. * somebody else already has it bound_, and _even if the original socket
  984. * didn't set REUSEADDR_. Use EXCLUSIVEADDRUSE to prevent this port-stealing
  985. * on win32. */
  986. if (setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (void*) &one,
  987. (socklen_t)sizeof(one))) {
  988. return -1;
  989. }
  990. return 0;
  991. #else
  992. (void) sock;
  993. return 0;
  994. #endif
  995. }
  996. #endif
  997. /** Max backlog to pass to listen. We start at */
  998. static int listen_limit = INT_MAX;
  999. /* Listen on <b>fd</b> with appropriate backlog. Return as for listen. */
  1000. static int
  1001. tor_listen(tor_socket_t fd)
  1002. {
  1003. int r;
  1004. if ((r = listen(fd, listen_limit)) < 0) {
  1005. if (listen_limit == SOMAXCONN)
  1006. return r;
  1007. if ((r = listen(fd, SOMAXCONN)) == 0) {
  1008. listen_limit = SOMAXCONN;
  1009. log_warn(LD_NET, "Setting listen backlog to INT_MAX connections "
  1010. "didn't work, but SOMAXCONN did. Lowering backlog limit.");
  1011. }
  1012. }
  1013. return r;
  1014. }
  1015. /** Bind a new non-blocking socket listening to the socket described
  1016. * by <b>listensockaddr</b>.
  1017. *
  1018. * <b>address</b> is only used for logging purposes and to add the information
  1019. * to the conn.
  1020. */
  1021. static connection_t *
  1022. connection_listener_new(const struct sockaddr *listensockaddr,
  1023. socklen_t socklen,
  1024. int type, const char *address,
  1025. const port_cfg_t *port_cfg)
  1026. {
  1027. listener_connection_t *lis_conn;
  1028. connection_t *conn = NULL;
  1029. tor_socket_t s = TOR_INVALID_SOCKET; /* the socket we're going to make */
  1030. or_options_t const *options = get_options();
  1031. (void) options; /* Windows doesn't use this. */
  1032. #if defined(HAVE_PWD_H) && defined(HAVE_SYS_UN_H)
  1033. const struct passwd *pw = NULL;
  1034. #endif
  1035. uint16_t usePort = 0, gotPort = 0;
  1036. int start_reading = 0;
  1037. static int global_next_session_group = SESSION_GROUP_FIRST_AUTO;
  1038. tor_addr_t addr;
  1039. int exhaustion = 0;
  1040. if (listensockaddr->sa_family == AF_INET ||
  1041. listensockaddr->sa_family == AF_INET6) {
  1042. int is_stream = (type != CONN_TYPE_AP_DNS_LISTENER);
  1043. if (is_stream)
  1044. start_reading = 1;
  1045. tor_addr_from_sockaddr(&addr, listensockaddr, &usePort);
  1046. log_notice(LD_NET, "Opening %s on %s",
  1047. conn_type_to_string(type), fmt_addrport(&addr, usePort));
  1048. s = tor_open_socket_nonblocking(tor_addr_family(&addr),
  1049. is_stream ? SOCK_STREAM : SOCK_DGRAM,
  1050. is_stream ? IPPROTO_TCP: IPPROTO_UDP);
  1051. if (!SOCKET_OK(s)) {
  1052. int e = tor_socket_errno(s);
  1053. if (ERRNO_IS_RESOURCE_LIMIT(e)) {
  1054. warn_too_many_conns();
  1055. /*
  1056. * We'll call the OOS handler at the error exit, so set the
  1057. * exhaustion flag for it.
  1058. */
  1059. exhaustion = 1;
  1060. } else {
  1061. log_warn(LD_NET, "Socket creation failed: %s",
  1062. tor_socket_strerror(e));
  1063. }
  1064. goto err;
  1065. }
  1066. if (make_socket_reuseable(s) < 0) {
  1067. log_warn(LD_NET, "Error setting SO_REUSEADDR flag on %s: %s",
  1068. conn_type_to_string(type),
  1069. tor_socket_strerror(errno));
  1070. }
  1071. #ifdef _WIN32
  1072. if (make_win32_socket_exclusive(s) < 0) {
  1073. log_warn(LD_NET, "Error setting SO_EXCLUSIVEADDRUSE flag on %s: %s",
  1074. conn_type_to_string(type),
  1075. tor_socket_strerror(errno));
  1076. }
  1077. #endif
  1078. #if defined(USE_TRANSPARENT) && defined(IP_TRANSPARENT)
  1079. if (options->TransProxyType_parsed == TPT_TPROXY &&
  1080. type == CONN_TYPE_AP_TRANS_LISTENER) {
  1081. int one = 1;
  1082. if (setsockopt(s, SOL_IP, IP_TRANSPARENT, (void*)&one,
  1083. (socklen_t)sizeof(one)) < 0) {
  1084. const char *extra = "";
  1085. int e = tor_socket_errno(s);
  1086. if (e == EPERM)
  1087. extra = "TransTPROXY requires root privileges or similar"
  1088. " capabilities.";
  1089. log_warn(LD_NET, "Error setting IP_TRANSPARENT flag: %s.%s",
  1090. tor_socket_strerror(e), extra);
  1091. }
  1092. }
  1093. #endif
  1094. #ifdef IPV6_V6ONLY
  1095. if (listensockaddr->sa_family == AF_INET6) {
  1096. int one = 1;
  1097. /* We need to set IPV6_V6ONLY so that this socket can't get used for
  1098. * IPv4 connections. */
  1099. if (setsockopt(s,IPPROTO_IPV6, IPV6_V6ONLY,
  1100. (void*)&one, (socklen_t)sizeof(one)) < 0) {
  1101. int e = tor_socket_errno(s);
  1102. log_warn(LD_NET, "Error setting IPV6_V6ONLY flag: %s",
  1103. tor_socket_strerror(e));
  1104. /* Keep going; probably not harmful. */
  1105. }
  1106. }
  1107. #endif
  1108. if (bind(s,listensockaddr,socklen) < 0) {
  1109. const char *helpfulhint = "";
  1110. int e = tor_socket_errno(s);
  1111. if (ERRNO_IS_EADDRINUSE(e))
  1112. helpfulhint = ". Is Tor already running?";
  1113. log_warn(LD_NET, "Could not bind to %s:%u: %s%s", address, usePort,
  1114. tor_socket_strerror(e), helpfulhint);
  1115. goto err;
  1116. }
  1117. if (is_stream) {
  1118. if (tor_listen(s) < 0) {
  1119. log_warn(LD_NET, "Could not listen on %s:%u: %s", address, usePort,
  1120. tor_socket_strerror(tor_socket_errno(s)));
  1121. goto err;
  1122. }
  1123. }
  1124. if (usePort != 0) {
  1125. gotPort = usePort;
  1126. } else {
  1127. tor_addr_t addr2;
  1128. struct sockaddr_storage ss;
  1129. socklen_t ss_len=sizeof(ss);
  1130. if (getsockname(s, (struct sockaddr*)&ss, &ss_len)<0) {
  1131. log_warn(LD_NET, "getsockname() couldn't learn address for %s: %s",
  1132. conn_type_to_string(type),
  1133. tor_socket_strerror(tor_socket_errno(s)));
  1134. gotPort = 0;
  1135. }
  1136. tor_addr_from_sockaddr(&addr2, (struct sockaddr*)&ss, &gotPort);
  1137. }
  1138. #ifdef HAVE_SYS_UN_H
  1139. /*
  1140. * AF_UNIX generic setup stuff
  1141. */
  1142. } else if (listensockaddr->sa_family == AF_UNIX) {
  1143. /* We want to start reading for both AF_UNIX cases */
  1144. start_reading = 1;
  1145. tor_assert(conn_listener_type_supports_af_unix(type));
  1146. if (check_location_for_unix_socket(options, address,
  1147. (type == CONN_TYPE_CONTROL_LISTENER) ?
  1148. UNIX_SOCKET_PURPOSE_CONTROL_SOCKET :
  1149. UNIX_SOCKET_PURPOSE_SOCKS_SOCKET, port_cfg) < 0) {
  1150. goto err;
  1151. }
  1152. log_notice(LD_NET, "Opening %s on %s",
  1153. conn_type_to_string(type), address);
  1154. tor_addr_make_unspec(&addr);
  1155. if (unlink(address) < 0 && errno != ENOENT) {
  1156. log_warn(LD_NET, "Could not unlink %s: %s", address,
  1157. strerror(errno));
  1158. goto err;
  1159. }
  1160. s = tor_open_socket_nonblocking(AF_UNIX, SOCK_STREAM, 0);
  1161. if (! SOCKET_OK(s)) {
  1162. int e = tor_socket_errno(s);
  1163. if (ERRNO_IS_RESOURCE_LIMIT(e)) {
  1164. warn_too_many_conns();
  1165. /*
  1166. * We'll call the OOS handler at the error exit, so set the
  1167. * exhaustion flag for it.
  1168. */
  1169. exhaustion = 1;
  1170. } else {
  1171. log_warn(LD_NET,"Socket creation failed: %s.", strerror(e));
  1172. }
  1173. goto err;
  1174. }
  1175. if (bind(s, listensockaddr,
  1176. (socklen_t)sizeof(struct sockaddr_un)) == -1) {
  1177. log_warn(LD_NET,"Bind to %s failed: %s.", address,
  1178. tor_socket_strerror(tor_socket_errno(s)));
  1179. goto err;
  1180. }
  1181. #ifdef HAVE_PWD_H
  1182. if (options->User) {
  1183. pw = tor_getpwnam(options->User);
  1184. struct stat st;
  1185. if (pw == NULL) {
  1186. log_warn(LD_NET,"Unable to chown() %s socket: user %s not found.",
  1187. address, options->User);
  1188. goto err;
  1189. } else if (fstat(s, &st) == 0 &&
  1190. st.st_uid == pw->pw_uid && st.st_gid == pw->pw_gid) {
  1191. /* No change needed */
  1192. } else if (chown(sandbox_intern_string(address),
  1193. pw->pw_uid, pw->pw_gid) < 0) {
  1194. log_warn(LD_NET,"Unable to chown() %s socket: %s.",
  1195. address, strerror(errno));
  1196. goto err;
  1197. }
  1198. }
  1199. #endif
  1200. {
  1201. unsigned mode;
  1202. const char *status;
  1203. struct stat st;
  1204. if (port_cfg->is_world_writable) {
  1205. mode = 0666;
  1206. status = "world-writable";
  1207. } else if (port_cfg->is_group_writable) {
  1208. mode = 0660;
  1209. status = "group-writable";
  1210. } else {
  1211. mode = 0600;
  1212. status = "private";
  1213. }
  1214. /* We need to use chmod; fchmod doesn't work on sockets on all
  1215. * platforms. */
  1216. if (fstat(s, &st) == 0 && (st.st_mode & 0777) == mode) {
  1217. /* no change needed */
  1218. } else if (chmod(sandbox_intern_string(address), mode) < 0) {
  1219. log_warn(LD_FS,"Unable to make %s %s.", address, status);
  1220. goto err;
  1221. }
  1222. }
  1223. if (listen(s, SOMAXCONN) < 0) {
  1224. log_warn(LD_NET, "Could not listen on %s: %s", address,
  1225. tor_socket_strerror(tor_socket_errno(s)));
  1226. goto err;
  1227. }
  1228. #endif /* HAVE_SYS_UN_H */
  1229. } else {
  1230. log_err(LD_BUG, "Got unexpected address family %d.",
  1231. listensockaddr->sa_family);
  1232. tor_assert(0);
  1233. }
  1234. lis_conn = listener_connection_new(type, listensockaddr->sa_family);
  1235. conn = TO_CONN(lis_conn);
  1236. conn->socket_family = listensockaddr->sa_family;
  1237. conn->s = s;
  1238. s = TOR_INVALID_SOCKET; /* Prevent double-close */
  1239. conn->address = tor_strdup(address);
  1240. conn->port = gotPort;
  1241. tor_addr_copy(&conn->addr, &addr);
  1242. memcpy(&lis_conn->entry_cfg, &port_cfg->entry_cfg, sizeof(entry_port_cfg_t));
  1243. if (port_cfg->entry_cfg.isolation_flags) {
  1244. lis_conn->entry_cfg.isolation_flags = port_cfg->entry_cfg.isolation_flags;
  1245. if (port_cfg->entry_cfg.session_group >= 0) {
  1246. lis_conn->entry_cfg.session_group = port_cfg->entry_cfg.session_group;
  1247. } else {
  1248. /* This can wrap after around INT_MAX listeners are opened. But I don't
  1249. * believe that matters, since you would need to open a ridiculous
  1250. * number of listeners while keeping the early ones open before you ever
  1251. * hit this. An OR with a dozen ports open, for example, would have to
  1252. * close and re-open its listeners every second for 4 years nonstop.
  1253. */
  1254. lis_conn->entry_cfg.session_group = global_next_session_group--;
  1255. }
  1256. }
  1257. if (type != CONN_TYPE_AP_LISTENER) {
  1258. lis_conn->entry_cfg.ipv4_traffic = 1;
  1259. lis_conn->entry_cfg.ipv6_traffic = 1;
  1260. lis_conn->entry_cfg.prefer_ipv6 = 0;
  1261. }
  1262. if (connection_add(conn) < 0) { /* no space, forget it */
  1263. log_warn(LD_NET,"connection_add for listener failed. Giving up.");
  1264. goto err;
  1265. }
  1266. log_fn(usePort==gotPort ? LOG_DEBUG : LOG_NOTICE, LD_NET,
  1267. "%s listening on port %u.",
  1268. conn_type_to_string(type), gotPort);
  1269. conn->state = LISTENER_STATE_READY;
  1270. if (start_reading) {
  1271. connection_start_reading(conn);
  1272. } else {
  1273. tor_assert(type == CONN_TYPE_AP_DNS_LISTENER);
  1274. dnsserv_configure_listener(conn);
  1275. }
  1276. /*
  1277. * Normal exit; call the OOS handler since connection count just changed;
  1278. * the exhaustion flag will always be zero here though.
  1279. */
  1280. connection_check_oos(get_n_open_sockets(), 0);
  1281. return conn;
  1282. err:
  1283. if (SOCKET_OK(s))
  1284. tor_close_socket(s);
  1285. if (conn)
  1286. connection_free(conn);
  1287. /* Call the OOS handler, indicate if we saw an exhaustion-related error */
  1288. connection_check_oos(get_n_open_sockets(), exhaustion);
  1289. return NULL;
  1290. }
  1291. /** Do basic sanity checking on a newly received socket. Return 0
  1292. * if it looks ok, else return -1.
  1293. *
  1294. * Notably, some TCP stacks can erroneously have accept() return successfully
  1295. * with socklen 0, when the client sends an RST before the accept call (as
  1296. * nmap does). We want to detect that, and not go on with the connection.
  1297. */
  1298. static int
  1299. check_sockaddr(const struct sockaddr *sa, int len, int level)
  1300. {
  1301. int ok = 1;
  1302. if (sa->sa_family == AF_INET) {
  1303. struct sockaddr_in *sin=(struct sockaddr_in*)sa;
  1304. if (len != sizeof(struct sockaddr_in)) {
  1305. log_fn(level, LD_NET, "Length of address not as expected: %d vs %d",
  1306. len,(int)sizeof(struct sockaddr_in));
  1307. ok = 0;
  1308. }
  1309. if (sin->sin_addr.s_addr == 0 || sin->sin_port == 0) {
  1310. log_fn(level, LD_NET,
  1311. "Address for new connection has address/port equal to zero.");
  1312. ok = 0;
  1313. }
  1314. } else if (sa->sa_family == AF_INET6) {
  1315. struct sockaddr_in6 *sin6=(struct sockaddr_in6*)sa;
  1316. if (len != sizeof(struct sockaddr_in6)) {
  1317. log_fn(level, LD_NET, "Length of address not as expected: %d vs %d",
  1318. len,(int)sizeof(struct sockaddr_in6));
  1319. ok = 0;
  1320. }
  1321. if (tor_mem_is_zero((void*)sin6->sin6_addr.s6_addr, 16) ||
  1322. sin6->sin6_port == 0) {
  1323. log_fn(level, LD_NET,
  1324. "Address for new connection has address/port equal to zero.");
  1325. ok = 0;
  1326. }
  1327. } else if (sa->sa_family == AF_UNIX) {
  1328. ok = 1;
  1329. } else {
  1330. ok = 0;
  1331. }
  1332. return ok ? 0 : -1;
  1333. }
  1334. /** Check whether the socket family from an accepted socket <b>got</b> is the
  1335. * same as the one that <b>listener</b> is waiting for. If it isn't, log
  1336. * a useful message and return -1. Else return 0.
  1337. *
  1338. * This is annoying, but can apparently happen on some Darwins. */
  1339. static int
  1340. check_sockaddr_family_match(sa_family_t got, connection_t *listener)
  1341. {
  1342. if (got != listener->socket_family) {
  1343. log_info(LD_BUG, "A listener connection returned a socket with a "
  1344. "mismatched family. %s for addr_family %d gave us a socket "
  1345. "with address family %d. Dropping.",
  1346. conn_type_to_string(listener->type),
  1347. (int)listener->socket_family,
  1348. (int)got);
  1349. return -1;
  1350. }
  1351. return 0;
  1352. }
  1353. /** The listener connection <b>conn</b> told poll() it wanted to read.
  1354. * Call accept() on conn-\>s, and add the new connection if necessary.
  1355. */
  1356. static int
  1357. connection_handle_listener_read(connection_t *conn, int new_type)
  1358. {
  1359. tor_socket_t news; /* the new socket */
  1360. connection_t *newconn = 0;
  1361. /* information about the remote peer when connecting to other routers */
  1362. struct sockaddr_storage addrbuf;
  1363. struct sockaddr *remote = (struct sockaddr*)&addrbuf;
  1364. /* length of the remote address. Must be whatever accept() needs. */
  1365. socklen_t remotelen = (socklen_t)sizeof(addrbuf);
  1366. const or_options_t *options = get_options();
  1367. tor_assert((size_t)remotelen >= sizeof(struct sockaddr_in));
  1368. memset(&addrbuf, 0, sizeof(addrbuf));
  1369. news = tor_accept_socket_nonblocking(conn->s,remote,&remotelen);
  1370. if (!SOCKET_OK(news)) { /* accept() error */
  1371. int e = tor_socket_errno(conn->s);
  1372. if (ERRNO_IS_ACCEPT_EAGAIN(e)) {
  1373. /*
  1374. * they hung up before we could accept(). that's fine.
  1375. *
  1376. * give the OOS handler a chance to run though
  1377. */
  1378. connection_check_oos(get_n_open_sockets(), 0);
  1379. return 0;
  1380. } else if (ERRNO_IS_RESOURCE_LIMIT(e)) {
  1381. warn_too_many_conns();
  1382. /* Exhaustion; tell the OOS handler */
  1383. connection_check_oos(get_n_open_sockets(), 1);
  1384. return 0;
  1385. }
  1386. /* else there was a real error. */
  1387. log_warn(LD_NET,"accept() failed: %s. Closing listener.",
  1388. tor_socket_strerror(e));
  1389. connection_mark_for_close(conn);
  1390. /* Tell the OOS handler about this too */
  1391. connection_check_oos(get_n_open_sockets(), 0);
  1392. return -1;
  1393. }
  1394. log_debug(LD_NET,
  1395. "Connection accepted on socket %d (child of fd %d).",
  1396. (int)news,(int)conn->s);
  1397. /* We accepted a new conn; run OOS handler */
  1398. connection_check_oos(get_n_open_sockets(), 0);
  1399. if (make_socket_reuseable(news) < 0) {
  1400. if (tor_socket_errno(news) == EINVAL) {
  1401. /* This can happen on OSX if we get a badly timed shutdown. */
  1402. log_debug(LD_NET, "make_socket_reuseable returned EINVAL");
  1403. } else {
  1404. log_warn(LD_NET, "Error setting SO_REUSEADDR flag on %s: %s",
  1405. conn_type_to_string(new_type),
  1406. tor_socket_strerror(errno));
  1407. }
  1408. tor_close_socket(news);
  1409. return 0;
  1410. }
  1411. if (options->ConstrainedSockets)
  1412. set_constrained_socket_buffers(news, (int)options->ConstrainedSockSize);
  1413. if (check_sockaddr_family_match(remote->sa_family, conn) < 0) {
  1414. tor_close_socket(news);
  1415. return 0;
  1416. }
  1417. if (conn->socket_family == AF_INET || conn->socket_family == AF_INET6 ||
  1418. (conn->socket_family == AF_UNIX && new_type == CONN_TYPE_AP)) {
  1419. tor_addr_t addr;
  1420. uint16_t port;
  1421. if (check_sockaddr(remote, remotelen, LOG_INFO)<0) {
  1422. log_info(LD_NET,
  1423. "accept() returned a strange address; closing connection.");
  1424. tor_close_socket(news);
  1425. return 0;
  1426. }
  1427. tor_addr_from_sockaddr(&addr, remote, &port);
  1428. /* process entrance policies here, before we even create the connection */
  1429. if (new_type == CONN_TYPE_AP) {
  1430. /* check sockspolicy to see if we should accept it */
  1431. if (socks_policy_permits_address(&addr) == 0) {
  1432. log_notice(LD_APP,
  1433. "Denying socks connection from untrusted address %s.",
  1434. fmt_and_decorate_addr(&addr));
  1435. tor_close_socket(news);
  1436. return 0;
  1437. }
  1438. }
  1439. if (new_type == CONN_TYPE_DIR) {
  1440. /* check dirpolicy to see if we should accept it */
  1441. if (dir_policy_permits_address(&addr) == 0) {
  1442. log_notice(LD_DIRSERV,"Denying dir connection from address %s.",
  1443. fmt_and_decorate_addr(&addr));
  1444. tor_close_socket(news);
  1445. return 0;
  1446. }
  1447. }
  1448. newconn = connection_new(new_type, conn->socket_family);
  1449. newconn->s = news;
  1450. /* remember the remote address */
  1451. tor_addr_copy(&newconn->addr, &addr);
  1452. if (new_type == CONN_TYPE_AP && conn->socket_family == AF_UNIX) {
  1453. newconn->port = 0;
  1454. newconn->address = tor_strdup(conn->address);
  1455. } else {
  1456. newconn->port = port;
  1457. newconn->address = tor_addr_to_str_dup(&addr);
  1458. }
  1459. if (new_type == CONN_TYPE_AP && conn->socket_family != AF_UNIX) {
  1460. log_info(LD_NET, "New SOCKS connection opened from %s.",
  1461. fmt_and_decorate_addr(&addr));
  1462. }
  1463. if (new_type == CONN_TYPE_AP && conn->socket_family == AF_UNIX) {
  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. TO_DIR_CONN(conn)->rend_data->onion_address))
  3716. ||
  3717. (CONN_IS_EDGE(conn) &&
  3718. TO_EDGE_CONN(conn)->rend_data &&
  3719. !rend_cmp_service_ids(rendquery,
  3720. TO_EDGE_CONN(conn)->rend_data->onion_address))
  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. }