connection.c 174 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150
  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. newconn->port = port;
  1453. newconn->address = tor_addr_to_str_dup(&addr);
  1454. if (new_type == CONN_TYPE_AP && conn->socket_family != AF_UNIX) {
  1455. log_info(LD_NET, "New SOCKS connection opened from %s.",
  1456. fmt_and_decorate_addr(&addr));
  1457. }
  1458. if (new_type == CONN_TYPE_AP && conn->socket_family == AF_UNIX) {
  1459. newconn->port = 0;
  1460. newconn->address = tor_strdup(conn->address);
  1461. log_info(LD_NET, "New SOCKS AF_UNIX connection opened");
  1462. }
  1463. if (new_type == CONN_TYPE_CONTROL) {
  1464. log_notice(LD_CONTROL, "New control connection opened from %s.",
  1465. fmt_and_decorate_addr(&addr));
  1466. }
  1467. } else if (conn->socket_family == AF_UNIX && conn->type != CONN_TYPE_AP) {
  1468. tor_assert(conn->type == CONN_TYPE_CONTROL_LISTENER);
  1469. tor_assert(new_type == CONN_TYPE_CONTROL);
  1470. log_notice(LD_CONTROL, "New control connection opened.");
  1471. newconn = connection_new(new_type, conn->socket_family);
  1472. newconn->s = news;
  1473. /* remember the remote address -- do we have anything sane to put here? */
  1474. tor_addr_make_unspec(&newconn->addr);
  1475. newconn->port = 1;
  1476. newconn->address = tor_strdup(conn->address);
  1477. } else {
  1478. tor_assert(0);
  1479. };
  1480. if (connection_add(newconn) < 0) { /* no space, forget it */
  1481. connection_free(newconn);
  1482. return 0; /* no need to tear down the parent */
  1483. }
  1484. if (connection_init_accepted_conn(newconn, TO_LISTENER_CONN(conn)) < 0) {
  1485. if (! newconn->marked_for_close)
  1486. connection_mark_for_close(newconn);
  1487. return 0;
  1488. }
  1489. return 0;
  1490. }
  1491. /** Initialize states for newly accepted connection <b>conn</b>.
  1492. * If conn is an OR, start the TLS handshake.
  1493. * If conn is a transparent AP, get its original destination
  1494. * and place it in circuit_wait.
  1495. */
  1496. static int
  1497. connection_init_accepted_conn(connection_t *conn,
  1498. const listener_connection_t *listener)
  1499. {
  1500. int rv;
  1501. connection_start_reading(conn);
  1502. switch (conn->type) {
  1503. case CONN_TYPE_EXT_OR:
  1504. /* Initiate Extended ORPort authentication. */
  1505. return connection_ext_or_start_auth(TO_OR_CONN(conn));
  1506. case CONN_TYPE_OR:
  1507. control_event_or_conn_status(TO_OR_CONN(conn), OR_CONN_EVENT_NEW, 0);
  1508. rv = connection_tls_start_handshake(TO_OR_CONN(conn), 1);
  1509. if (rv < 0) {
  1510. connection_or_close_for_error(TO_OR_CONN(conn), 0);
  1511. }
  1512. return rv;
  1513. break;
  1514. case CONN_TYPE_AP:
  1515. memcpy(&TO_ENTRY_CONN(conn)->entry_cfg, &listener->entry_cfg,
  1516. sizeof(entry_port_cfg_t));
  1517. TO_ENTRY_CONN(conn)->nym_epoch = get_signewnym_epoch();
  1518. TO_ENTRY_CONN(conn)->socks_request->listener_type = listener->base_.type;
  1519. switch (TO_CONN(listener)->type) {
  1520. case CONN_TYPE_AP_LISTENER:
  1521. conn->state = AP_CONN_STATE_SOCKS_WAIT;
  1522. TO_ENTRY_CONN(conn)->socks_request->socks_prefer_no_auth =
  1523. listener->entry_cfg.socks_prefer_no_auth;
  1524. break;
  1525. case CONN_TYPE_AP_TRANS_LISTENER:
  1526. TO_ENTRY_CONN(conn)->is_transparent_ap = 1;
  1527. /* XXXX028 -- is this correct still, with the addition of
  1528. * pending_entry_connections ? */
  1529. conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  1530. return connection_ap_process_transparent(TO_ENTRY_CONN(conn));
  1531. case CONN_TYPE_AP_NATD_LISTENER:
  1532. TO_ENTRY_CONN(conn)->is_transparent_ap = 1;
  1533. conn->state = AP_CONN_STATE_NATD_WAIT;
  1534. break;
  1535. }
  1536. break;
  1537. case CONN_TYPE_DIR:
  1538. conn->purpose = DIR_PURPOSE_SERVER;
  1539. conn->state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
  1540. break;
  1541. case CONN_TYPE_CONTROL:
  1542. conn->state = CONTROL_CONN_STATE_NEEDAUTH;
  1543. break;
  1544. }
  1545. return 0;
  1546. }
  1547. /** Take conn, make a nonblocking socket; try to connect to
  1548. * sa, binding to bindaddr if sa is not localhost. If fail, return -1 and if
  1549. * applicable put your best guess about errno into *<b>socket_error</b>.
  1550. * If connected return 1, if EAGAIN return 0.
  1551. */
  1552. MOCK_IMPL(STATIC int,
  1553. connection_connect_sockaddr,(connection_t *conn,
  1554. const struct sockaddr *sa,
  1555. socklen_t sa_len,
  1556. const struct sockaddr *bindaddr,
  1557. socklen_t bindaddr_len,
  1558. int *socket_error))
  1559. {
  1560. tor_socket_t s;
  1561. int inprogress = 0;
  1562. const or_options_t *options = get_options();
  1563. tor_assert(conn);
  1564. tor_assert(sa);
  1565. tor_assert(socket_error);
  1566. if (get_options()->DisableNetwork) {
  1567. /* We should never even try to connect anyplace if DisableNetwork is set.
  1568. * Warn if we do, and refuse to make the connection. */
  1569. static ratelim_t disablenet_violated = RATELIM_INIT(30*60);
  1570. *socket_error = SOCK_ERRNO(ENETUNREACH);
  1571. log_fn_ratelim(&disablenet_violated, LOG_WARN, LD_BUG,
  1572. "Tried to open a socket with DisableNetwork set.");
  1573. tor_fragile_assert();
  1574. return -1;
  1575. }
  1576. const int protocol_family = sa->sa_family;
  1577. const int proto = (sa->sa_family == AF_INET6 ||
  1578. sa->sa_family == AF_INET) ? IPPROTO_TCP : 0;
  1579. s = tor_open_socket_nonblocking(protocol_family, SOCK_STREAM, proto);
  1580. if (! SOCKET_OK(s)) {
  1581. /*
  1582. * Early OOS handler calls; it matters if it's an exhaustion-related
  1583. * error or not.
  1584. */
  1585. *socket_error = tor_socket_errno(s);
  1586. if (ERRNO_IS_RESOURCE_LIMIT(*socket_error)) {
  1587. warn_too_many_conns();
  1588. connection_check_oos(get_n_open_sockets(), 1);
  1589. } else {
  1590. log_warn(LD_NET,"Error creating network socket: %s",
  1591. tor_socket_strerror(*socket_error));
  1592. connection_check_oos(get_n_open_sockets(), 0);
  1593. }
  1594. return -1;
  1595. }
  1596. if (make_socket_reuseable(s) < 0) {
  1597. log_warn(LD_NET, "Error setting SO_REUSEADDR flag on new connection: %s",
  1598. tor_socket_strerror(errno));
  1599. }
  1600. /*
  1601. * We've got the socket open; give the OOS handler a chance to check
  1602. * against configuured maximum socket number, but tell it no exhaustion
  1603. * failure.
  1604. */
  1605. connection_check_oos(get_n_open_sockets(), 0);
  1606. if (bindaddr && bind(s, bindaddr, bindaddr_len) < 0) {
  1607. *socket_error = tor_socket_errno(s);
  1608. log_warn(LD_NET,"Error binding network socket: %s",
  1609. tor_socket_strerror(*socket_error));
  1610. tor_close_socket(s);
  1611. return -1;
  1612. }
  1613. tor_assert(options);
  1614. if (options->ConstrainedSockets)
  1615. set_constrained_socket_buffers(s, (int)options->ConstrainedSockSize);
  1616. if (connect(s, sa, sa_len) < 0) {
  1617. int e = tor_socket_errno(s);
  1618. if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
  1619. /* yuck. kill it. */
  1620. *socket_error = e;
  1621. log_info(LD_NET,
  1622. "connect() to socket failed: %s",
  1623. tor_socket_strerror(e));
  1624. tor_close_socket(s);
  1625. return -1;
  1626. } else {
  1627. inprogress = 1;
  1628. }
  1629. }
  1630. /* it succeeded. we're connected. */
  1631. log_fn(inprogress ? LOG_DEBUG : LOG_INFO, LD_NET,
  1632. "Connection to socket %s (sock "TOR_SOCKET_T_FORMAT").",
  1633. inprogress ? "in progress" : "established", s);
  1634. conn->s = s;
  1635. if (connection_add_connecting(conn) < 0) {
  1636. /* no space, forget it */
  1637. *socket_error = SOCK_ERRNO(ENOBUFS);
  1638. return -1;
  1639. }
  1640. return inprogress ? 0 : 1;
  1641. }
  1642. /* Log a message if connection attempt is made when IPv4 or IPv6 is disabled.
  1643. * Log a less severe message if we couldn't conform to ClientPreferIPv6ORPort
  1644. * or ClientPreferIPv6ORPort. */
  1645. static void
  1646. connection_connect_log_client_use_ip_version(const connection_t *conn)
  1647. {
  1648. const or_options_t *options = get_options();
  1649. /* Only clients care about ClientUseIPv4/6, bail out early on servers, and
  1650. * on connections we don't care about */
  1651. if (server_mode(options) || !conn || conn->type == CONN_TYPE_EXIT) {
  1652. return;
  1653. }
  1654. /* We're only prepared to log OR and DIR connections here */
  1655. if (conn->type != CONN_TYPE_OR && conn->type != CONN_TYPE_DIR) {
  1656. return;
  1657. }
  1658. const int must_ipv4 = !fascist_firewall_use_ipv6(options);
  1659. const int must_ipv6 = (options->ClientUseIPv4 == 0);
  1660. const int pref_ipv6 = (conn->type == CONN_TYPE_OR
  1661. ? fascist_firewall_prefer_ipv6_orport(options)
  1662. : fascist_firewall_prefer_ipv6_dirport(options));
  1663. tor_addr_t real_addr;
  1664. tor_addr_make_null(&real_addr, AF_UNSPEC);
  1665. /* OR conns keep the original address in real_addr, as addr gets overwritten
  1666. * with the descriptor address */
  1667. if (conn->type == CONN_TYPE_OR) {
  1668. const or_connection_t *or_conn = TO_OR_CONN((connection_t *)conn);
  1669. tor_addr_copy(&real_addr, &or_conn->real_addr);
  1670. } else if (conn->type == CONN_TYPE_DIR) {
  1671. tor_addr_copy(&real_addr, &conn->addr);
  1672. }
  1673. /* Check if we broke a mandatory address family restriction */
  1674. if ((must_ipv4 && tor_addr_family(&real_addr) == AF_INET6)
  1675. || (must_ipv6 && tor_addr_family(&real_addr) == AF_INET)) {
  1676. static int logged_backtrace = 0;
  1677. log_info(LD_BUG, "Outgoing %s connection to %s violated ClientUseIPv%s 0.",
  1678. conn->type == CONN_TYPE_OR ? "OR" : "Dir",
  1679. fmt_addr(&real_addr),
  1680. options->ClientUseIPv4 == 0 ? "4" : "6");
  1681. if (!logged_backtrace) {
  1682. log_backtrace(LOG_INFO, LD_BUG, "Address came from");
  1683. logged_backtrace = 1;
  1684. }
  1685. }
  1686. /* Bridges are allowed to break IPv4/IPv6 ORPort preferences to connect to
  1687. * the node's configured address when ClientPreferIPv6ORPort is auto */
  1688. if (options->UseBridges && conn->type == CONN_TYPE_OR
  1689. && options->ClientPreferIPv6ORPort == -1) {
  1690. return;
  1691. }
  1692. /* Check if we couldn't satisfy an address family preference */
  1693. if ((!pref_ipv6 && tor_addr_family(&real_addr) == AF_INET6)
  1694. || (pref_ipv6 && tor_addr_family(&real_addr) == AF_INET)) {
  1695. log_info(LD_NET, "Outgoing connection to %s doesn't satisfy "
  1696. "ClientPreferIPv6%sPort %d, with ClientUseIPv4 %d, and "
  1697. "fascist_firewall_use_ipv6 %d (ClientUseIPv6 %d and UseBridges "
  1698. "%d).",
  1699. fmt_addr(&real_addr),
  1700. conn->type == CONN_TYPE_OR ? "OR" : "Dir",
  1701. conn->type == CONN_TYPE_OR ? options->ClientPreferIPv6ORPort
  1702. : options->ClientPreferIPv6DirPort,
  1703. options->ClientUseIPv4, fascist_firewall_use_ipv6(options),
  1704. options->ClientUseIPv6, options->UseBridges);
  1705. }
  1706. }
  1707. /** Take conn, make a nonblocking socket; try to connect to
  1708. * addr:port (port arrives in *host order*). If fail, return -1 and if
  1709. * applicable put your best guess about errno into *<b>socket_error</b>.
  1710. * Else assign s to conn-\>s: if connected return 1, if EAGAIN return 0.
  1711. *
  1712. * addr:port can be different to conn->addr:conn->port if connecting through
  1713. * a proxy.
  1714. *
  1715. * address is used to make the logs useful.
  1716. *
  1717. * On success, add conn to the list of polled connections.
  1718. */
  1719. int
  1720. connection_connect(connection_t *conn, const char *address,
  1721. const tor_addr_t *addr, uint16_t port, int *socket_error)
  1722. {
  1723. struct sockaddr_storage addrbuf;
  1724. struct sockaddr_storage bind_addr_ss;
  1725. struct sockaddr *bind_addr = NULL;
  1726. struct sockaddr *dest_addr;
  1727. int dest_addr_len, bind_addr_len = 0;
  1728. const or_options_t *options = get_options();
  1729. int protocol_family;
  1730. /* Log if we didn't stick to ClientUseIPv4/6 or ClientPreferIPv6OR/DirPort
  1731. */
  1732. connection_connect_log_client_use_ip_version(conn);
  1733. if (tor_addr_family(addr) == AF_INET6)
  1734. protocol_family = PF_INET6;
  1735. else
  1736. protocol_family = PF_INET;
  1737. if (!tor_addr_is_loopback(addr)) {
  1738. const tor_addr_t *ext_addr = NULL;
  1739. if (protocol_family == AF_INET &&
  1740. !tor_addr_is_null(&options->OutboundBindAddressIPv4_))
  1741. ext_addr = &options->OutboundBindAddressIPv4_;
  1742. else if (protocol_family == AF_INET6 &&
  1743. !tor_addr_is_null(&options->OutboundBindAddressIPv6_))
  1744. ext_addr = &options->OutboundBindAddressIPv6_;
  1745. if (ext_addr) {
  1746. memset(&bind_addr_ss, 0, sizeof(bind_addr_ss));
  1747. bind_addr_len = tor_addr_to_sockaddr(ext_addr, 0,
  1748. (struct sockaddr *) &bind_addr_ss,
  1749. sizeof(bind_addr_ss));
  1750. if (bind_addr_len == 0) {
  1751. log_warn(LD_NET,
  1752. "Error converting OutboundBindAddress %s into sockaddr. "
  1753. "Ignoring.", fmt_and_decorate_addr(ext_addr));
  1754. } else {
  1755. bind_addr = (struct sockaddr *)&bind_addr_ss;
  1756. }
  1757. }
  1758. }
  1759. memset(&addrbuf,0,sizeof(addrbuf));
  1760. dest_addr = (struct sockaddr*) &addrbuf;
  1761. dest_addr_len = tor_addr_to_sockaddr(addr, port, dest_addr, sizeof(addrbuf));
  1762. tor_assert(dest_addr_len > 0);
  1763. log_debug(LD_NET, "Connecting to %s:%u.",
  1764. escaped_safe_str_client(address), port);
  1765. return connection_connect_sockaddr(conn, dest_addr, dest_addr_len,
  1766. bind_addr, bind_addr_len, socket_error);
  1767. }
  1768. #ifdef HAVE_SYS_UN_H
  1769. /** Take conn, make a nonblocking socket; try to connect to
  1770. * an AF_UNIX socket at socket_path. If fail, return -1 and if applicable
  1771. * put your best guess about errno into *<b>socket_error</b>. Else assign s
  1772. * to conn-\>s: if connected return 1, if EAGAIN return 0.
  1773. *
  1774. * On success, add conn to the list of polled connections.
  1775. */
  1776. int
  1777. connection_connect_unix(connection_t *conn, const char *socket_path,
  1778. int *socket_error)
  1779. {
  1780. struct sockaddr_un dest_addr;
  1781. tor_assert(socket_path);
  1782. /* Check that we'll be able to fit it into dest_addr later */
  1783. if (strlen(socket_path) + 1 > sizeof(dest_addr.sun_path)) {
  1784. log_warn(LD_NET,
  1785. "Path %s is too long for an AF_UNIX socket\n",
  1786. escaped_safe_str_client(socket_path));
  1787. *socket_error = SOCK_ERRNO(ENAMETOOLONG);
  1788. return -1;
  1789. }
  1790. memset(&dest_addr, 0, sizeof(dest_addr));
  1791. dest_addr.sun_family = AF_UNIX;
  1792. strlcpy(dest_addr.sun_path, socket_path, sizeof(dest_addr.sun_path));
  1793. log_debug(LD_NET,
  1794. "Connecting to AF_UNIX socket at %s.",
  1795. escaped_safe_str_client(socket_path));
  1796. return connection_connect_sockaddr(conn,
  1797. (struct sockaddr *)&dest_addr, sizeof(dest_addr),
  1798. NULL, 0, socket_error);
  1799. }
  1800. #endif /* defined(HAVE_SYS_UN_H) */
  1801. /** Convert state number to string representation for logging purposes.
  1802. */
  1803. static const char *
  1804. connection_proxy_state_to_string(int state)
  1805. {
  1806. static const char *unknown = "???";
  1807. static const char *states[] = {
  1808. "PROXY_NONE",
  1809. "PROXY_INFANT",
  1810. "PROXY_HTTPS_WANT_CONNECT_OK",
  1811. "PROXY_SOCKS4_WANT_CONNECT_OK",
  1812. "PROXY_SOCKS5_WANT_AUTH_METHOD_NONE",
  1813. "PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929",
  1814. "PROXY_SOCKS5_WANT_AUTH_RFC1929_OK",
  1815. "PROXY_SOCKS5_WANT_CONNECT_OK",
  1816. "PROXY_CONNECTED",
  1817. };
  1818. if (state < PROXY_NONE || state > PROXY_CONNECTED)
  1819. return unknown;
  1820. return states[state];
  1821. }
  1822. /** Returns the global proxy type used by tor. Use this function for
  1823. * logging or high-level purposes, don't use it to fill the
  1824. * <b>proxy_type</b> field of or_connection_t; use the actual proxy
  1825. * protocol instead.*/
  1826. static int
  1827. get_proxy_type(void)
  1828. {
  1829. const or_options_t *options = get_options();
  1830. if (options->ClientTransportPlugin)
  1831. return PROXY_PLUGGABLE;
  1832. else if (options->HTTPSProxy)
  1833. return PROXY_CONNECT;
  1834. else if (options->Socks4Proxy)
  1835. return PROXY_SOCKS4;
  1836. else if (options->Socks5Proxy)
  1837. return PROXY_SOCKS5;
  1838. else
  1839. return PROXY_NONE;
  1840. }
  1841. /* One byte for the version, one for the command, two for the
  1842. port, and four for the addr... and, one more for the
  1843. username NUL: */
  1844. #define SOCKS4_STANDARD_BUFFER_SIZE (1 + 1 + 2 + 4 + 1)
  1845. /** Write a proxy request of <b>type</b> (socks4, socks5, https) to conn
  1846. * for conn->addr:conn->port, authenticating with the auth details given
  1847. * in the configuration (if available). SOCKS 5 and HTTP CONNECT proxies
  1848. * support authentication.
  1849. *
  1850. * Returns -1 if conn->addr is incompatible with the proxy protocol, and
  1851. * 0 otherwise.
  1852. *
  1853. * Use connection_read_proxy_handshake() to complete the handshake.
  1854. */
  1855. int
  1856. connection_proxy_connect(connection_t *conn, int type)
  1857. {
  1858. const or_options_t *options;
  1859. tor_assert(conn);
  1860. options = get_options();
  1861. switch (type) {
  1862. case PROXY_CONNECT: {
  1863. char buf[1024];
  1864. char *base64_authenticator=NULL;
  1865. const char *authenticator = options->HTTPSProxyAuthenticator;
  1866. /* Send HTTP CONNECT and authentication (if available) in
  1867. * one request */
  1868. if (authenticator) {
  1869. base64_authenticator = alloc_http_authenticator(authenticator);
  1870. if (!base64_authenticator)
  1871. log_warn(LD_OR, "Encoding https authenticator failed");
  1872. }
  1873. if (base64_authenticator) {
  1874. const char *addrport = fmt_addrport(&conn->addr, conn->port);
  1875. tor_snprintf(buf, sizeof(buf), "CONNECT %s HTTP/1.1\r\n"
  1876. "Host: %s\r\n"
  1877. "Proxy-Authorization: Basic %s\r\n\r\n",
  1878. addrport,
  1879. addrport,
  1880. base64_authenticator);
  1881. tor_free(base64_authenticator);
  1882. } else {
  1883. tor_snprintf(buf, sizeof(buf), "CONNECT %s HTTP/1.0\r\n\r\n",
  1884. fmt_addrport(&conn->addr, conn->port));
  1885. }
  1886. connection_write_to_buf(buf, strlen(buf), conn);
  1887. conn->proxy_state = PROXY_HTTPS_WANT_CONNECT_OK;
  1888. break;
  1889. }
  1890. case PROXY_SOCKS4: {
  1891. unsigned char *buf;
  1892. uint16_t portn;
  1893. uint32_t ip4addr;
  1894. size_t buf_size = 0;
  1895. char *socks_args_string = NULL;
  1896. /* Send a SOCKS4 connect request */
  1897. if (tor_addr_family(&conn->addr) != AF_INET) {
  1898. log_warn(LD_NET, "SOCKS4 client is incompatible with IPv6");
  1899. return -1;
  1900. }
  1901. { /* If we are here because we are trying to connect to a
  1902. pluggable transport proxy, check if we have any SOCKS
  1903. arguments to transmit. If we do, compress all arguments to
  1904. a single string in 'socks_args_string': */
  1905. if (get_proxy_type() == PROXY_PLUGGABLE) {
  1906. socks_args_string =
  1907. pt_get_socks_args_for_proxy_addrport(&conn->addr, conn->port);
  1908. if (socks_args_string)
  1909. log_debug(LD_NET, "Sending out '%s' as our SOCKS argument string.",
  1910. socks_args_string);
  1911. }
  1912. }
  1913. { /* Figure out the buffer size we need for the SOCKS message: */
  1914. buf_size = SOCKS4_STANDARD_BUFFER_SIZE;
  1915. /* If we have a SOCKS argument string, consider its size when
  1916. calculating the buffer size: */
  1917. if (socks_args_string)
  1918. buf_size += strlen(socks_args_string);
  1919. }
  1920. buf = tor_malloc_zero(buf_size);
  1921. ip4addr = tor_addr_to_ipv4n(&conn->addr);
  1922. portn = htons(conn->port);
  1923. buf[0] = 4; /* version */
  1924. buf[1] = SOCKS_COMMAND_CONNECT; /* command */
  1925. memcpy(buf + 2, &portn, 2); /* port */
  1926. memcpy(buf + 4, &ip4addr, 4); /* addr */
  1927. /* Next packet field is the userid. If we have pluggable
  1928. transport SOCKS arguments, we have to embed them
  1929. there. Otherwise, we use an empty userid. */
  1930. if (socks_args_string) { /* place the SOCKS args string: */
  1931. tor_assert(strlen(socks_args_string) > 0);
  1932. tor_assert(buf_size >=
  1933. SOCKS4_STANDARD_BUFFER_SIZE + strlen(socks_args_string));
  1934. strlcpy((char *)buf + 8, socks_args_string, buf_size - 8);
  1935. tor_free(socks_args_string);
  1936. } else {
  1937. buf[8] = 0; /* no userid */
  1938. }
  1939. connection_write_to_buf((char *)buf, buf_size, conn);
  1940. tor_free(buf);
  1941. conn->proxy_state = PROXY_SOCKS4_WANT_CONNECT_OK;
  1942. break;
  1943. }
  1944. case PROXY_SOCKS5: {
  1945. unsigned char buf[4]; /* fields: vers, num methods, method list */
  1946. /* Send a SOCKS5 greeting (connect request must wait) */
  1947. buf[0] = 5; /* version */
  1948. /* We have to use SOCKS5 authentication, if we have a
  1949. Socks5ProxyUsername or if we want to pass arguments to our
  1950. pluggable transport proxy: */
  1951. if ((options->Socks5ProxyUsername) ||
  1952. (get_proxy_type() == PROXY_PLUGGABLE &&
  1953. (get_socks_args_by_bridge_addrport(&conn->addr, conn->port)))) {
  1954. /* number of auth methods */
  1955. buf[1] = 2;
  1956. buf[2] = 0x00; /* no authentication */
  1957. buf[3] = 0x02; /* rfc1929 Username/Passwd auth */
  1958. conn->proxy_state = PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929;
  1959. } else {
  1960. buf[1] = 1;
  1961. buf[2] = 0x00; /* no authentication */
  1962. conn->proxy_state = PROXY_SOCKS5_WANT_AUTH_METHOD_NONE;
  1963. }
  1964. connection_write_to_buf((char *)buf, 2 + buf[1], conn);
  1965. break;
  1966. }
  1967. default:
  1968. log_err(LD_BUG, "Invalid proxy protocol, %d", type);
  1969. tor_fragile_assert();
  1970. return -1;
  1971. }
  1972. log_debug(LD_NET, "set state %s",
  1973. connection_proxy_state_to_string(conn->proxy_state));
  1974. return 0;
  1975. }
  1976. /** Read conn's inbuf. If the http response from the proxy is all
  1977. * here, make sure it's good news, then return 1. If it's bad news,
  1978. * return -1. Else return 0 and hope for better luck next time.
  1979. */
  1980. static int
  1981. connection_read_https_proxy_response(connection_t *conn)
  1982. {
  1983. char *headers;
  1984. char *reason=NULL;
  1985. int status_code;
  1986. time_t date_header;
  1987. switch (fetch_from_buf_http(conn->inbuf,
  1988. &headers, MAX_HEADERS_SIZE,
  1989. NULL, NULL, 10000, 0)) {
  1990. case -1: /* overflow */
  1991. log_warn(LD_PROTOCOL,
  1992. "Your https proxy sent back an oversized response. Closing.");
  1993. return -1;
  1994. case 0:
  1995. log_info(LD_NET,"https proxy response not all here yet. Waiting.");
  1996. return 0;
  1997. /* case 1, fall through */
  1998. }
  1999. if (parse_http_response(headers, &status_code, &date_header,
  2000. NULL, &reason) < 0) {
  2001. log_warn(LD_NET,
  2002. "Unparseable headers from proxy (connecting to '%s'). Closing.",
  2003. conn->address);
  2004. tor_free(headers);
  2005. return -1;
  2006. }
  2007. tor_free(headers);
  2008. if (!reason) reason = tor_strdup("[no reason given]");
  2009. if (status_code == 200) {
  2010. log_info(LD_NET,
  2011. "HTTPS connect to '%s' successful! (200 %s) Starting TLS.",
  2012. conn->address, escaped(reason));
  2013. tor_free(reason);
  2014. return 1;
  2015. }
  2016. /* else, bad news on the status code */
  2017. switch (status_code) {
  2018. case 403:
  2019. log_warn(LD_NET,
  2020. "The https proxy refused to allow connection to %s "
  2021. "(status code %d, %s). Closing.",
  2022. conn->address, status_code, escaped(reason));
  2023. break;
  2024. default:
  2025. log_warn(LD_NET,
  2026. "The https proxy sent back an unexpected status code %d (%s). "
  2027. "Closing.",
  2028. status_code, escaped(reason));
  2029. break;
  2030. }
  2031. tor_free(reason);
  2032. return -1;
  2033. }
  2034. /** Send SOCKS5 CONNECT command to <b>conn</b>, copying <b>conn->addr</b>
  2035. * and <b>conn->port</b> into the request.
  2036. */
  2037. static void
  2038. connection_send_socks5_connect(connection_t *conn)
  2039. {
  2040. unsigned char buf[1024];
  2041. size_t reqsize = 6;
  2042. uint16_t port = htons(conn->port);
  2043. buf[0] = 5; /* version */
  2044. buf[1] = SOCKS_COMMAND_CONNECT; /* command */
  2045. buf[2] = 0; /* reserved */
  2046. if (tor_addr_family(&conn->addr) == AF_INET) {
  2047. uint32_t addr = tor_addr_to_ipv4n(&conn->addr);
  2048. buf[3] = 1;
  2049. reqsize += 4;
  2050. memcpy(buf + 4, &addr, 4);
  2051. memcpy(buf + 8, &port, 2);
  2052. } else { /* AF_INET6 */
  2053. buf[3] = 4;
  2054. reqsize += 16;
  2055. memcpy(buf + 4, tor_addr_to_in6_addr8(&conn->addr), 16);
  2056. memcpy(buf + 20, &port, 2);
  2057. }
  2058. connection_write_to_buf((char *)buf, reqsize, conn);
  2059. conn->proxy_state = PROXY_SOCKS5_WANT_CONNECT_OK;
  2060. }
  2061. /** Wrapper around fetch_from_buf_socks_client: see that functions
  2062. * for documentation of its behavior. */
  2063. static int
  2064. connection_fetch_from_buf_socks_client(connection_t *conn,
  2065. int state, char **reason)
  2066. {
  2067. return fetch_from_buf_socks_client(conn->inbuf, state, reason);
  2068. }
  2069. /** Call this from connection_*_process_inbuf() to advance the proxy
  2070. * handshake.
  2071. *
  2072. * No matter what proxy protocol is used, if this function returns 1, the
  2073. * handshake is complete, and the data remaining on inbuf may contain the
  2074. * start of the communication with the requested server.
  2075. *
  2076. * Returns 0 if the current buffer contains an incomplete response, and -1
  2077. * on error.
  2078. */
  2079. int
  2080. connection_read_proxy_handshake(connection_t *conn)
  2081. {
  2082. int ret = 0;
  2083. char *reason = NULL;
  2084. log_debug(LD_NET, "enter state %s",
  2085. connection_proxy_state_to_string(conn->proxy_state));
  2086. switch (conn->proxy_state) {
  2087. case PROXY_HTTPS_WANT_CONNECT_OK:
  2088. ret = connection_read_https_proxy_response(conn);
  2089. if (ret == 1)
  2090. conn->proxy_state = PROXY_CONNECTED;
  2091. break;
  2092. case PROXY_SOCKS4_WANT_CONNECT_OK:
  2093. ret = connection_fetch_from_buf_socks_client(conn,
  2094. conn->proxy_state,
  2095. &reason);
  2096. if (ret == 1)
  2097. conn->proxy_state = PROXY_CONNECTED;
  2098. break;
  2099. case PROXY_SOCKS5_WANT_AUTH_METHOD_NONE:
  2100. ret = connection_fetch_from_buf_socks_client(conn,
  2101. conn->proxy_state,
  2102. &reason);
  2103. /* no auth needed, do connect */
  2104. if (ret == 1) {
  2105. connection_send_socks5_connect(conn);
  2106. ret = 0;
  2107. }
  2108. break;
  2109. case PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929:
  2110. ret = connection_fetch_from_buf_socks_client(conn,
  2111. conn->proxy_state,
  2112. &reason);
  2113. /* send auth if needed, otherwise do connect */
  2114. if (ret == 1) {
  2115. connection_send_socks5_connect(conn);
  2116. ret = 0;
  2117. } else if (ret == 2) {
  2118. unsigned char buf[1024];
  2119. size_t reqsize, usize, psize;
  2120. const char *user, *pass;
  2121. char *socks_args_string = NULL;
  2122. if (get_proxy_type() == PROXY_PLUGGABLE) {
  2123. socks_args_string =
  2124. pt_get_socks_args_for_proxy_addrport(&conn->addr, conn->port);
  2125. if (!socks_args_string) {
  2126. log_warn(LD_NET, "Could not create SOCKS args string.");
  2127. ret = -1;
  2128. break;
  2129. }
  2130. log_debug(LD_NET, "SOCKS5 arguments: %s", socks_args_string);
  2131. tor_assert(strlen(socks_args_string) > 0);
  2132. tor_assert(strlen(socks_args_string) <= MAX_SOCKS5_AUTH_SIZE_TOTAL);
  2133. if (strlen(socks_args_string) > MAX_SOCKS5_AUTH_FIELD_SIZE) {
  2134. user = socks_args_string;
  2135. usize = MAX_SOCKS5_AUTH_FIELD_SIZE;
  2136. pass = socks_args_string + MAX_SOCKS5_AUTH_FIELD_SIZE;
  2137. psize = strlen(socks_args_string) - MAX_SOCKS5_AUTH_FIELD_SIZE;
  2138. } else {
  2139. user = socks_args_string;
  2140. usize = strlen(socks_args_string);
  2141. pass = "\0";
  2142. psize = 1;
  2143. }
  2144. } else if (get_options()->Socks5ProxyUsername) {
  2145. user = get_options()->Socks5ProxyUsername;
  2146. pass = get_options()->Socks5ProxyPassword;
  2147. tor_assert(user && pass);
  2148. usize = strlen(user);
  2149. psize = strlen(pass);
  2150. } else {
  2151. log_err(LD_BUG, "We entered %s for no reason!", __func__);
  2152. tor_fragile_assert();
  2153. ret = -1;
  2154. break;
  2155. }
  2156. /* Username and password lengths should have been checked
  2157. above and during torrc parsing. */
  2158. tor_assert(usize <= MAX_SOCKS5_AUTH_FIELD_SIZE &&
  2159. psize <= MAX_SOCKS5_AUTH_FIELD_SIZE);
  2160. reqsize = 3 + usize + psize;
  2161. buf[0] = 1; /* negotiation version */
  2162. buf[1] = usize;
  2163. memcpy(buf + 2, user, usize);
  2164. buf[2 + usize] = psize;
  2165. memcpy(buf + 3 + usize, pass, psize);
  2166. if (socks_args_string)
  2167. tor_free(socks_args_string);
  2168. connection_write_to_buf((char *)buf, reqsize, conn);
  2169. conn->proxy_state = PROXY_SOCKS5_WANT_AUTH_RFC1929_OK;
  2170. ret = 0;
  2171. }
  2172. break;
  2173. case PROXY_SOCKS5_WANT_AUTH_RFC1929_OK:
  2174. ret = connection_fetch_from_buf_socks_client(conn,
  2175. conn->proxy_state,
  2176. &reason);
  2177. /* send the connect request */
  2178. if (ret == 1) {
  2179. connection_send_socks5_connect(conn);
  2180. ret = 0;
  2181. }
  2182. break;
  2183. case PROXY_SOCKS5_WANT_CONNECT_OK:
  2184. ret = connection_fetch_from_buf_socks_client(conn,
  2185. conn->proxy_state,
  2186. &reason);
  2187. if (ret == 1)
  2188. conn->proxy_state = PROXY_CONNECTED;
  2189. break;
  2190. default:
  2191. log_err(LD_BUG, "Invalid proxy_state for reading, %d",
  2192. conn->proxy_state);
  2193. tor_fragile_assert();
  2194. ret = -1;
  2195. break;
  2196. }
  2197. log_debug(LD_NET, "leaving state %s",
  2198. connection_proxy_state_to_string(conn->proxy_state));
  2199. if (ret < 0) {
  2200. if (reason) {
  2201. log_warn(LD_NET, "Proxy Client: unable to connect to %s:%d (%s)",
  2202. conn->address, conn->port, escaped(reason));
  2203. tor_free(reason);
  2204. } else {
  2205. log_warn(LD_NET, "Proxy Client: unable to connect to %s:%d",
  2206. conn->address, conn->port);
  2207. }
  2208. } else if (ret == 1) {
  2209. log_info(LD_NET, "Proxy Client: connection to %s:%d successful",
  2210. conn->address, conn->port);
  2211. }
  2212. return ret;
  2213. }
  2214. /** Given a list of listener connections in <b>old_conns</b>, and list of
  2215. * port_cfg_t entries in <b>ports</b>, open a new listener for every port in
  2216. * <b>ports</b> that does not already have a listener in <b>old_conns</b>.
  2217. *
  2218. * Remove from <b>old_conns</b> every connection that has a corresponding
  2219. * entry in <b>ports</b>. Add to <b>new_conns</b> new every connection we
  2220. * launch.
  2221. *
  2222. * If <b>control_listeners_only</b> is true, then we only open control
  2223. * listeners, and we do not remove any noncontrol listeners from old_conns.
  2224. *
  2225. * Return 0 on success, -1 on failure.
  2226. **/
  2227. static int
  2228. retry_listener_ports(smartlist_t *old_conns,
  2229. const smartlist_t *ports,
  2230. smartlist_t *new_conns,
  2231. int control_listeners_only)
  2232. {
  2233. smartlist_t *launch = smartlist_new();
  2234. int r = 0;
  2235. if (control_listeners_only) {
  2236. SMARTLIST_FOREACH(ports, port_cfg_t *, p, {
  2237. if (p->type == CONN_TYPE_CONTROL_LISTENER)
  2238. smartlist_add(launch, p);
  2239. });
  2240. } else {
  2241. smartlist_add_all(launch, ports);
  2242. }
  2243. /* Iterate through old_conns, comparing it to launch: remove from both lists
  2244. * each pair of elements that corresponds to the same port. */
  2245. SMARTLIST_FOREACH_BEGIN(old_conns, connection_t *, conn) {
  2246. const port_cfg_t *found_port = NULL;
  2247. /* Okay, so this is a listener. Is it configured? */
  2248. SMARTLIST_FOREACH_BEGIN(launch, const port_cfg_t *, wanted) {
  2249. if (conn->type != wanted->type)
  2250. continue;
  2251. if ((conn->socket_family != AF_UNIX && wanted->is_unix_addr) ||
  2252. (conn->socket_family == AF_UNIX && ! wanted->is_unix_addr))
  2253. continue;
  2254. if (wanted->server_cfg.no_listen)
  2255. continue; /* We don't want to open a listener for this one */
  2256. if (wanted->is_unix_addr) {
  2257. if (conn->socket_family == AF_UNIX &&
  2258. !strcmp(wanted->unix_addr, conn->address)) {
  2259. found_port = wanted;
  2260. break;
  2261. }
  2262. } else {
  2263. int port_matches;
  2264. if (wanted->port == CFG_AUTO_PORT) {
  2265. port_matches = 1;
  2266. } else {
  2267. port_matches = (wanted->port == conn->port);
  2268. }
  2269. if (port_matches && tor_addr_eq(&wanted->addr, &conn->addr)) {
  2270. found_port = wanted;
  2271. break;
  2272. }
  2273. }
  2274. } SMARTLIST_FOREACH_END(wanted);
  2275. if (found_port) {
  2276. /* This listener is already running; we don't need to launch it. */
  2277. //log_debug(LD_NET, "Already have %s on %s:%d",
  2278. // conn_type_to_string(found_port->type), conn->address, conn->port);
  2279. smartlist_remove(launch, found_port);
  2280. /* And we can remove the connection from old_conns too. */
  2281. SMARTLIST_DEL_CURRENT(old_conns, conn);
  2282. }
  2283. } SMARTLIST_FOREACH_END(conn);
  2284. /* Now open all the listeners that are configured but not opened. */
  2285. SMARTLIST_FOREACH_BEGIN(launch, const port_cfg_t *, port) {
  2286. struct sockaddr *listensockaddr;
  2287. socklen_t listensocklen = 0;
  2288. char *address=NULL;
  2289. connection_t *conn;
  2290. int real_port = port->port == CFG_AUTO_PORT ? 0 : port->port;
  2291. tor_assert(real_port <= UINT16_MAX);
  2292. if (port->server_cfg.no_listen)
  2293. continue;
  2294. #ifndef _WIN32
  2295. /* We don't need to be root to create a UNIX socket, so defer until after
  2296. * setuid. */
  2297. const or_options_t *options = get_options();
  2298. if (port->is_unix_addr && !geteuid() && (options->User) &&
  2299. strcmp(options->User, "root"))
  2300. continue;
  2301. #endif
  2302. if (port->is_unix_addr) {
  2303. listensockaddr = (struct sockaddr *)
  2304. create_unix_sockaddr(port->unix_addr,
  2305. &address, &listensocklen);
  2306. } else {
  2307. listensockaddr = tor_malloc(sizeof(struct sockaddr_storage));
  2308. listensocklen = tor_addr_to_sockaddr(&port->addr,
  2309. real_port,
  2310. listensockaddr,
  2311. sizeof(struct sockaddr_storage));
  2312. address = tor_addr_to_str_dup(&port->addr);
  2313. }
  2314. if (listensockaddr) {
  2315. conn = connection_listener_new(listensockaddr, listensocklen,
  2316. port->type, address, port);
  2317. tor_free(listensockaddr);
  2318. tor_free(address);
  2319. } else {
  2320. conn = NULL;
  2321. }
  2322. if (!conn) {
  2323. r = -1;
  2324. } else {
  2325. if (new_conns)
  2326. smartlist_add(new_conns, conn);
  2327. }
  2328. } SMARTLIST_FOREACH_END(port);
  2329. smartlist_free(launch);
  2330. return r;
  2331. }
  2332. /** Launch listeners for each port you should have open. Only launch
  2333. * listeners who are not already open, and only close listeners we no longer
  2334. * want.
  2335. *
  2336. * Add all old conns that should be closed to <b>replaced_conns</b>.
  2337. * Add all new connections to <b>new_conns</b>.
  2338. *
  2339. * If <b>close_all_noncontrol</b> is true, then we only open control
  2340. * listeners, and we close all other listeners.
  2341. */
  2342. int
  2343. retry_all_listeners(smartlist_t *replaced_conns,
  2344. smartlist_t *new_conns, int close_all_noncontrol)
  2345. {
  2346. smartlist_t *listeners = smartlist_new();
  2347. const or_options_t *options = get_options();
  2348. int retval = 0;
  2349. const uint16_t old_or_port = router_get_advertised_or_port(options);
  2350. const uint16_t old_or_port_ipv6 =
  2351. router_get_advertised_or_port_by_af(options,AF_INET6);
  2352. const uint16_t old_dir_port = router_get_advertised_dir_port(options, 0);
  2353. SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t *, conn) {
  2354. if (connection_is_listener(conn) && !conn->marked_for_close)
  2355. smartlist_add(listeners, conn);
  2356. } SMARTLIST_FOREACH_END(conn);
  2357. if (retry_listener_ports(listeners,
  2358. get_configured_ports(),
  2359. new_conns,
  2360. close_all_noncontrol) < 0)
  2361. retval = -1;
  2362. /* Any members that were still in 'listeners' don't correspond to
  2363. * any configured port. Kill 'em. */
  2364. SMARTLIST_FOREACH_BEGIN(listeners, connection_t *, conn) {
  2365. log_notice(LD_NET, "Closing no-longer-configured %s on %s:%d",
  2366. conn_type_to_string(conn->type), conn->address, conn->port);
  2367. if (replaced_conns) {
  2368. smartlist_add(replaced_conns, conn);
  2369. } else {
  2370. connection_close_immediate(conn);
  2371. connection_mark_for_close(conn);
  2372. }
  2373. } SMARTLIST_FOREACH_END(conn);
  2374. smartlist_free(listeners);
  2375. if (old_or_port != router_get_advertised_or_port(options) ||
  2376. old_or_port_ipv6 != router_get_advertised_or_port_by_af(options,
  2377. AF_INET6) ||
  2378. old_dir_port != router_get_advertised_dir_port(options, 0)) {
  2379. /* Our chosen ORPort or DirPort is not what it used to be: the
  2380. * descriptor we had (if any) should be regenerated. (We won't
  2381. * automatically notice this because of changes in the option,
  2382. * since the value could be "auto".) */
  2383. mark_my_descriptor_dirty("Chosen Or/DirPort changed");
  2384. }
  2385. return retval;
  2386. }
  2387. /** Mark every listener of type other than CONTROL_LISTENER to be closed. */
  2388. void
  2389. connection_mark_all_noncontrol_listeners(void)
  2390. {
  2391. SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t *, conn) {
  2392. if (conn->marked_for_close)
  2393. continue;
  2394. if (conn->type == CONN_TYPE_CONTROL_LISTENER)
  2395. continue;
  2396. if (connection_is_listener(conn))
  2397. connection_mark_for_close(conn);
  2398. } SMARTLIST_FOREACH_END(conn);
  2399. }
  2400. /** Mark every external connection not used for controllers for close. */
  2401. void
  2402. connection_mark_all_noncontrol_connections(void)
  2403. {
  2404. SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t *, conn) {
  2405. if (conn->marked_for_close)
  2406. continue;
  2407. switch (conn->type) {
  2408. case CONN_TYPE_CONTROL_LISTENER:
  2409. case CONN_TYPE_CONTROL:
  2410. break;
  2411. case CONN_TYPE_AP:
  2412. connection_mark_unattached_ap(TO_ENTRY_CONN(conn),
  2413. END_STREAM_REASON_HIBERNATING);
  2414. break;
  2415. case CONN_TYPE_OR:
  2416. {
  2417. or_connection_t *orconn = TO_OR_CONN(conn);
  2418. if (orconn->chan) {
  2419. connection_or_close_normally(orconn, 0);
  2420. } else {
  2421. /*
  2422. * There should have been one, but mark for close and hope
  2423. * for the best..
  2424. */
  2425. connection_mark_for_close(conn);
  2426. }
  2427. }
  2428. break;
  2429. default:
  2430. connection_mark_for_close(conn);
  2431. break;
  2432. }
  2433. } SMARTLIST_FOREACH_END(conn);
  2434. }
  2435. /** Return 1 if we should apply rate limiting to <b>conn</b>, and 0
  2436. * otherwise.
  2437. * Right now this just checks if it's an internal IP address or an
  2438. * internal connection. We also should, but don't, check if the connection
  2439. * uses pluggable transports, since we should then limit it even if it
  2440. * comes from an internal IP address. */
  2441. static int
  2442. connection_is_rate_limited(connection_t *conn)
  2443. {
  2444. const or_options_t *options = get_options();
  2445. if (conn->linked)
  2446. return 0; /* Internal connection */
  2447. else if (! options->CountPrivateBandwidth &&
  2448. (tor_addr_family(&conn->addr) == AF_UNSPEC || /* no address */
  2449. tor_addr_family(&conn->addr) == AF_UNIX || /* no address */
  2450. tor_addr_is_internal(&conn->addr, 0)))
  2451. return 0; /* Internal address */
  2452. else
  2453. return 1;
  2454. }
  2455. /** Did either global write bucket run dry last second? If so,
  2456. * we are likely to run dry again this second, so be stingy with the
  2457. * tokens we just put in. */
  2458. static int write_buckets_empty_last_second = 0;
  2459. /** How many seconds of no active local circuits will make the
  2460. * connection revert to the "relayed" bandwidth class? */
  2461. #define CLIENT_IDLE_TIME_FOR_PRIORITY 30
  2462. /** Return 1 if <b>conn</b> should use tokens from the "relayed"
  2463. * bandwidth rates, else 0. Currently, only OR conns with bandwidth
  2464. * class 1, and directory conns that are serving data out, count.
  2465. */
  2466. static int
  2467. connection_counts_as_relayed_traffic(connection_t *conn, time_t now)
  2468. {
  2469. if (conn->type == CONN_TYPE_OR &&
  2470. connection_or_client_used(TO_OR_CONN(conn)) +
  2471. CLIENT_IDLE_TIME_FOR_PRIORITY < now)
  2472. return 1;
  2473. if (conn->type == CONN_TYPE_DIR && DIR_CONN_IS_SERVER(conn))
  2474. return 1;
  2475. return 0;
  2476. }
  2477. /** Helper function to decide how many bytes out of <b>global_bucket</b>
  2478. * we're willing to use for this transaction. <b>base</b> is the size
  2479. * of a cell on the network; <b>priority</b> says whether we should
  2480. * write many of them or just a few; and <b>conn_bucket</b> (if
  2481. * non-negative) provides an upper limit for our answer. */
  2482. static ssize_t
  2483. connection_bucket_round_robin(int base, int priority,
  2484. ssize_t global_bucket, ssize_t conn_bucket)
  2485. {
  2486. ssize_t at_most;
  2487. ssize_t num_bytes_high = (priority ? 32 : 16) * base;
  2488. ssize_t num_bytes_low = (priority ? 4 : 2) * base;
  2489. /* Do a rudimentary round-robin so one circuit can't hog a connection.
  2490. * Pick at most 32 cells, at least 4 cells if possible, and if we're in
  2491. * the middle pick 1/8 of the available bandwidth. */
  2492. at_most = global_bucket / 8;
  2493. at_most -= (at_most % base); /* round down */
  2494. if (at_most > num_bytes_high) /* 16 KB, or 8 KB for low-priority */
  2495. at_most = num_bytes_high;
  2496. else if (at_most < num_bytes_low) /* 2 KB, or 1 KB for low-priority */
  2497. at_most = num_bytes_low;
  2498. if (at_most > global_bucket)
  2499. at_most = global_bucket;
  2500. if (conn_bucket >= 0 && at_most > conn_bucket)
  2501. at_most = conn_bucket;
  2502. if (at_most < 0)
  2503. return 0;
  2504. return at_most;
  2505. }
  2506. /** How many bytes at most can we read onto this connection? */
  2507. static ssize_t
  2508. connection_bucket_read_limit(connection_t *conn, time_t now)
  2509. {
  2510. int base = RELAY_PAYLOAD_SIZE;
  2511. int priority = conn->type != CONN_TYPE_DIR;
  2512. int conn_bucket = -1;
  2513. int global_bucket = global_read_bucket;
  2514. if (connection_speaks_cells(conn)) {
  2515. or_connection_t *or_conn = TO_OR_CONN(conn);
  2516. if (conn->state == OR_CONN_STATE_OPEN)
  2517. conn_bucket = or_conn->read_bucket;
  2518. base = get_cell_network_size(or_conn->wide_circ_ids);
  2519. }
  2520. if (!connection_is_rate_limited(conn)) {
  2521. /* be willing to read on local conns even if our buckets are empty */
  2522. return conn_bucket>=0 ? conn_bucket : 1<<14;
  2523. }
  2524. if (connection_counts_as_relayed_traffic(conn, now) &&
  2525. global_relayed_read_bucket <= global_read_bucket)
  2526. global_bucket = global_relayed_read_bucket;
  2527. return connection_bucket_round_robin(base, priority,
  2528. global_bucket, conn_bucket);
  2529. }
  2530. /** How many bytes at most can we write onto this connection? */
  2531. ssize_t
  2532. connection_bucket_write_limit(connection_t *conn, time_t now)
  2533. {
  2534. int base = RELAY_PAYLOAD_SIZE;
  2535. int priority = conn->type != CONN_TYPE_DIR;
  2536. int conn_bucket = (int)conn->outbuf_flushlen;
  2537. int global_bucket = global_write_bucket;
  2538. if (!connection_is_rate_limited(conn)) {
  2539. /* be willing to write to local conns even if our buckets are empty */
  2540. return conn->outbuf_flushlen;
  2541. }
  2542. if (connection_speaks_cells(conn)) {
  2543. /* use the per-conn write limit if it's lower, but if it's less
  2544. * than zero just use zero */
  2545. or_connection_t *or_conn = TO_OR_CONN(conn);
  2546. if (conn->state == OR_CONN_STATE_OPEN)
  2547. if (or_conn->write_bucket < conn_bucket)
  2548. conn_bucket = or_conn->write_bucket >= 0 ?
  2549. or_conn->write_bucket : 0;
  2550. base = get_cell_network_size(or_conn->wide_circ_ids);
  2551. }
  2552. if (connection_counts_as_relayed_traffic(conn, now) &&
  2553. global_relayed_write_bucket <= global_write_bucket)
  2554. global_bucket = global_relayed_write_bucket;
  2555. return connection_bucket_round_robin(base, priority,
  2556. global_bucket, conn_bucket);
  2557. }
  2558. /** Return 1 if the global write buckets are low enough that we
  2559. * shouldn't send <b>attempt</b> bytes of low-priority directory stuff
  2560. * out to <b>conn</b>. Else return 0.
  2561. * Priority was 1 for v1 requests (directories and running-routers),
  2562. * and 2 for v2 requests and later (statuses and descriptors).
  2563. *
  2564. * There are a lot of parameters we could use here:
  2565. * - global_relayed_write_bucket. Low is bad.
  2566. * - global_write_bucket. Low is bad.
  2567. * - bandwidthrate. Low is bad.
  2568. * - bandwidthburst. Not a big factor?
  2569. * - attempt. High is bad.
  2570. * - total bytes queued on outbufs. High is bad. But I'm wary of
  2571. * using this, since a few slow-flushing queues will pump up the
  2572. * number without meaning what we meant to mean. What we really
  2573. * mean is "total directory bytes added to outbufs recently", but
  2574. * that's harder to quantify and harder to keep track of.
  2575. */
  2576. int
  2577. global_write_bucket_low(connection_t *conn, size_t attempt, int priority)
  2578. {
  2579. int smaller_bucket = global_write_bucket < global_relayed_write_bucket ?
  2580. global_write_bucket : global_relayed_write_bucket;
  2581. if (authdir_mode(get_options()) && priority>1)
  2582. return 0; /* there's always room to answer v2 if we're an auth dir */
  2583. if (!connection_is_rate_limited(conn))
  2584. return 0; /* local conns don't get limited */
  2585. if (smaller_bucket < (int)attempt)
  2586. return 1; /* not enough space no matter the priority */
  2587. if (write_buckets_empty_last_second)
  2588. return 1; /* we're already hitting our limits, no more please */
  2589. if (priority == 1) { /* old-style v1 query */
  2590. /* Could we handle *two* of these requests within the next two seconds? */
  2591. const or_options_t *options = get_options();
  2592. int64_t can_write = (int64_t)smaller_bucket
  2593. + 2*(options->RelayBandwidthRate ? options->RelayBandwidthRate :
  2594. options->BandwidthRate);
  2595. if (can_write < 2*(int64_t)attempt)
  2596. return 1;
  2597. } else { /* v2 query */
  2598. /* no further constraints yet */
  2599. }
  2600. return 0;
  2601. }
  2602. /** Helper: adjusts our bandwidth history and informs the controller as
  2603. * appropriate, given that we have just read <b>num_read</b> bytes and written
  2604. * <b>num_written</b> bytes on <b>conn</b>. */
  2605. static void
  2606. record_num_bytes_transferred_impl(connection_t *conn,
  2607. time_t now, size_t num_read, size_t num_written)
  2608. {
  2609. /* Count bytes of answering direct and tunneled directory requests */
  2610. if (conn->type == CONN_TYPE_DIR && conn->purpose == DIR_PURPOSE_SERVER) {
  2611. if (num_read > 0)
  2612. rep_hist_note_dir_bytes_read(num_read, now);
  2613. if (num_written > 0)
  2614. rep_hist_note_dir_bytes_written(num_written, now);
  2615. }
  2616. if (!connection_is_rate_limited(conn))
  2617. return; /* local IPs are free */
  2618. if (conn->type == CONN_TYPE_OR)
  2619. rep_hist_note_or_conn_bytes(conn->global_identifier, num_read,
  2620. num_written, now);
  2621. if (num_read > 0) {
  2622. rep_hist_note_bytes_read(num_read, now);
  2623. }
  2624. if (num_written > 0) {
  2625. rep_hist_note_bytes_written(num_written, now);
  2626. }
  2627. if (conn->type == CONN_TYPE_EXIT)
  2628. rep_hist_note_exit_bytes(conn->port, num_written, num_read);
  2629. }
  2630. /** Helper: convert given <b>tvnow</b> time value to milliseconds since
  2631. * midnight. */
  2632. static uint32_t
  2633. msec_since_midnight(const struct timeval *tvnow)
  2634. {
  2635. return (uint32_t)(((tvnow->tv_sec % 86400L) * 1000L) +
  2636. ((uint32_t)tvnow->tv_usec / (uint32_t)1000L));
  2637. }
  2638. /** Helper: return the time in milliseconds since <b>last_empty_time</b>
  2639. * when a bucket ran empty that previously had <b>tokens_before</b> tokens
  2640. * now has <b>tokens_after</b> tokens after refilling at timestamp
  2641. * <b>tvnow</b>, capped at <b>milliseconds_elapsed</b> milliseconds since
  2642. * last refilling that bucket. Return 0 if the bucket has not been empty
  2643. * since the last refill or has not been refilled. */
  2644. uint32_t
  2645. bucket_millis_empty(int tokens_before, uint32_t last_empty_time,
  2646. int tokens_after, int milliseconds_elapsed,
  2647. const struct timeval *tvnow)
  2648. {
  2649. uint32_t result = 0, refilled;
  2650. if (tokens_before <= 0 && tokens_after > tokens_before) {
  2651. refilled = msec_since_midnight(tvnow);
  2652. result = (uint32_t)((refilled + 86400L * 1000L - last_empty_time) %
  2653. (86400L * 1000L));
  2654. if (result > (uint32_t)milliseconds_elapsed)
  2655. result = (uint32_t)milliseconds_elapsed;
  2656. }
  2657. return result;
  2658. }
  2659. /** Check if a bucket which had <b>tokens_before</b> tokens and which got
  2660. * <b>tokens_removed</b> tokens removed at timestamp <b>tvnow</b> has run
  2661. * out of tokens, and if so, note the milliseconds since midnight in
  2662. * <b>timestamp_var</b> for the next TB_EMPTY event. */
  2663. void
  2664. connection_buckets_note_empty_ts(uint32_t *timestamp_var,
  2665. int tokens_before, size_t tokens_removed,
  2666. const struct timeval *tvnow)
  2667. {
  2668. if (tokens_before > 0 && (uint32_t)tokens_before <= tokens_removed)
  2669. *timestamp_var = msec_since_midnight(tvnow);
  2670. }
  2671. /** Last time at which the global or relay buckets were emptied in msec
  2672. * since midnight. */
  2673. static uint32_t global_relayed_read_emptied = 0,
  2674. global_relayed_write_emptied = 0,
  2675. global_read_emptied = 0,
  2676. global_write_emptied = 0;
  2677. /** We just read <b>num_read</b> and wrote <b>num_written</b> bytes
  2678. * onto <b>conn</b>. Decrement buckets appropriately. */
  2679. static void
  2680. connection_buckets_decrement(connection_t *conn, time_t now,
  2681. size_t num_read, size_t num_written)
  2682. {
  2683. if (num_written >= INT_MAX || num_read >= INT_MAX) {
  2684. log_err(LD_BUG, "Value out of range. num_read=%lu, num_written=%lu, "
  2685. "connection type=%s, state=%s",
  2686. (unsigned long)num_read, (unsigned long)num_written,
  2687. conn_type_to_string(conn->type),
  2688. conn_state_to_string(conn->type, conn->state));
  2689. if (num_written >= INT_MAX) num_written = 1;
  2690. if (num_read >= INT_MAX) num_read = 1;
  2691. tor_fragile_assert();
  2692. }
  2693. record_num_bytes_transferred_impl(conn, now, num_read, num_written);
  2694. if (!connection_is_rate_limited(conn))
  2695. return; /* local IPs are free */
  2696. /* If one or more of our token buckets ran dry just now, note the
  2697. * timestamp for TB_EMPTY events. */
  2698. if (get_options()->TestingEnableTbEmptyEvent) {
  2699. struct timeval tvnow;
  2700. tor_gettimeofday_cached(&tvnow);
  2701. if (connection_counts_as_relayed_traffic(conn, now)) {
  2702. connection_buckets_note_empty_ts(&global_relayed_read_emptied,
  2703. global_relayed_read_bucket, num_read, &tvnow);
  2704. connection_buckets_note_empty_ts(&global_relayed_write_emptied,
  2705. global_relayed_write_bucket, num_written, &tvnow);
  2706. }
  2707. connection_buckets_note_empty_ts(&global_read_emptied,
  2708. global_read_bucket, num_read, &tvnow);
  2709. connection_buckets_note_empty_ts(&global_write_emptied,
  2710. global_write_bucket, num_written, &tvnow);
  2711. if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
  2712. or_connection_t *or_conn = TO_OR_CONN(conn);
  2713. connection_buckets_note_empty_ts(&or_conn->read_emptied_time,
  2714. or_conn->read_bucket, num_read, &tvnow);
  2715. connection_buckets_note_empty_ts(&or_conn->write_emptied_time,
  2716. or_conn->write_bucket, num_written, &tvnow);
  2717. }
  2718. }
  2719. if (connection_counts_as_relayed_traffic(conn, now)) {
  2720. global_relayed_read_bucket -= (int)num_read;
  2721. global_relayed_write_bucket -= (int)num_written;
  2722. }
  2723. global_read_bucket -= (int)num_read;
  2724. global_write_bucket -= (int)num_written;
  2725. if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
  2726. TO_OR_CONN(conn)->read_bucket -= (int)num_read;
  2727. TO_OR_CONN(conn)->write_bucket -= (int)num_written;
  2728. }
  2729. }
  2730. /** If we have exhausted our global buckets, or the buckets for conn,
  2731. * stop reading. */
  2732. static void
  2733. connection_consider_empty_read_buckets(connection_t *conn)
  2734. {
  2735. const char *reason;
  2736. if (!connection_is_rate_limited(conn))
  2737. return; /* Always okay. */
  2738. if (global_read_bucket <= 0) {
  2739. reason = "global read bucket exhausted. Pausing.";
  2740. } else if (connection_counts_as_relayed_traffic(conn, approx_time()) &&
  2741. global_relayed_read_bucket <= 0) {
  2742. reason = "global relayed read bucket exhausted. Pausing.";
  2743. } else if (connection_speaks_cells(conn) &&
  2744. conn->state == OR_CONN_STATE_OPEN &&
  2745. TO_OR_CONN(conn)->read_bucket <= 0) {
  2746. reason = "connection read bucket exhausted. Pausing.";
  2747. } else
  2748. return; /* all good, no need to stop it */
  2749. LOG_FN_CONN(conn, (LOG_DEBUG, LD_NET, "%s", reason));
  2750. conn->read_blocked_on_bw = 1;
  2751. connection_stop_reading(conn);
  2752. }
  2753. /** If we have exhausted our global buckets, or the buckets for conn,
  2754. * stop writing. */
  2755. static void
  2756. connection_consider_empty_write_buckets(connection_t *conn)
  2757. {
  2758. const char *reason;
  2759. if (!connection_is_rate_limited(conn))
  2760. return; /* Always okay. */
  2761. if (global_write_bucket <= 0) {
  2762. reason = "global write bucket exhausted. Pausing.";
  2763. } else if (connection_counts_as_relayed_traffic(conn, approx_time()) &&
  2764. global_relayed_write_bucket <= 0) {
  2765. reason = "global relayed write bucket exhausted. Pausing.";
  2766. } else if (connection_speaks_cells(conn) &&
  2767. conn->state == OR_CONN_STATE_OPEN &&
  2768. TO_OR_CONN(conn)->write_bucket <= 0) {
  2769. reason = "connection write bucket exhausted. Pausing.";
  2770. } else
  2771. return; /* all good, no need to stop it */
  2772. LOG_FN_CONN(conn, (LOG_DEBUG, LD_NET, "%s", reason));
  2773. conn->write_blocked_on_bw = 1;
  2774. connection_stop_writing(conn);
  2775. }
  2776. /** Initialize the global read bucket to options-\>BandwidthBurst. */
  2777. void
  2778. connection_bucket_init(void)
  2779. {
  2780. const or_options_t *options = get_options();
  2781. /* start it at max traffic */
  2782. global_read_bucket = (int)options->BandwidthBurst;
  2783. global_write_bucket = (int)options->BandwidthBurst;
  2784. if (options->RelayBandwidthRate) {
  2785. global_relayed_read_bucket = (int)options->RelayBandwidthBurst;
  2786. global_relayed_write_bucket = (int)options->RelayBandwidthBurst;
  2787. } else {
  2788. global_relayed_read_bucket = (int)options->BandwidthBurst;
  2789. global_relayed_write_bucket = (int)options->BandwidthBurst;
  2790. }
  2791. }
  2792. /** Refill a single <b>bucket</b> called <b>name</b> with bandwidth rate per
  2793. * second <b>rate</b> and bandwidth burst <b>burst</b>, assuming that
  2794. * <b>milliseconds_elapsed</b> milliseconds have passed since the last
  2795. * call. */
  2796. static void
  2797. connection_bucket_refill_helper(int *bucket, int rate, int burst,
  2798. int milliseconds_elapsed,
  2799. const char *name)
  2800. {
  2801. int starting_bucket = *bucket;
  2802. if (starting_bucket < burst && milliseconds_elapsed > 0) {
  2803. int64_t incr = (((int64_t)rate) * milliseconds_elapsed) / 1000;
  2804. if ((burst - starting_bucket) < incr) {
  2805. *bucket = burst; /* We would overflow the bucket; just set it to
  2806. * the maximum. */
  2807. } else {
  2808. *bucket += (int)incr;
  2809. if (*bucket > burst || *bucket < starting_bucket) {
  2810. /* If we overflow the burst, or underflow our starting bucket,
  2811. * cap the bucket value to burst. */
  2812. /* XXXX this might be redundant now, but it doesn't show up
  2813. * in profiles. Remove it after analysis. */
  2814. *bucket = burst;
  2815. }
  2816. }
  2817. log_debug(LD_NET,"%s now %d.", name, *bucket);
  2818. }
  2819. }
  2820. /** Time has passed; increment buckets appropriately. */
  2821. void
  2822. connection_bucket_refill(int milliseconds_elapsed, time_t now)
  2823. {
  2824. const or_options_t *options = get_options();
  2825. smartlist_t *conns = get_connection_array();
  2826. int bandwidthrate, bandwidthburst, relayrate, relayburst;
  2827. int prev_global_read = global_read_bucket;
  2828. int prev_global_write = global_write_bucket;
  2829. int prev_relay_read = global_relayed_read_bucket;
  2830. int prev_relay_write = global_relayed_write_bucket;
  2831. struct timeval tvnow; /*< Only used if TB_EMPTY events are enabled. */
  2832. bandwidthrate = (int)options->BandwidthRate;
  2833. bandwidthburst = (int)options->BandwidthBurst;
  2834. if (options->RelayBandwidthRate) {
  2835. relayrate = (int)options->RelayBandwidthRate;
  2836. relayburst = (int)options->RelayBandwidthBurst;
  2837. } else {
  2838. relayrate = bandwidthrate;
  2839. relayburst = bandwidthburst;
  2840. }
  2841. tor_assert(milliseconds_elapsed >= 0);
  2842. write_buckets_empty_last_second =
  2843. global_relayed_write_bucket <= 0 || global_write_bucket <= 0;
  2844. /* refill the global buckets */
  2845. connection_bucket_refill_helper(&global_read_bucket,
  2846. bandwidthrate, bandwidthburst,
  2847. milliseconds_elapsed,
  2848. "global_read_bucket");
  2849. connection_bucket_refill_helper(&global_write_bucket,
  2850. bandwidthrate, bandwidthburst,
  2851. milliseconds_elapsed,
  2852. "global_write_bucket");
  2853. connection_bucket_refill_helper(&global_relayed_read_bucket,
  2854. relayrate, relayburst,
  2855. milliseconds_elapsed,
  2856. "global_relayed_read_bucket");
  2857. connection_bucket_refill_helper(&global_relayed_write_bucket,
  2858. relayrate, relayburst,
  2859. milliseconds_elapsed,
  2860. "global_relayed_write_bucket");
  2861. /* If buckets were empty before and have now been refilled, tell any
  2862. * interested controllers. */
  2863. if (get_options()->TestingEnableTbEmptyEvent) {
  2864. uint32_t global_read_empty_time, global_write_empty_time,
  2865. relay_read_empty_time, relay_write_empty_time;
  2866. tor_gettimeofday_cached(&tvnow);
  2867. global_read_empty_time = bucket_millis_empty(prev_global_read,
  2868. global_read_emptied, global_read_bucket,
  2869. milliseconds_elapsed, &tvnow);
  2870. global_write_empty_time = bucket_millis_empty(prev_global_write,
  2871. global_write_emptied, global_write_bucket,
  2872. milliseconds_elapsed, &tvnow);
  2873. control_event_tb_empty("GLOBAL", global_read_empty_time,
  2874. global_write_empty_time, milliseconds_elapsed);
  2875. relay_read_empty_time = bucket_millis_empty(prev_relay_read,
  2876. global_relayed_read_emptied,
  2877. global_relayed_read_bucket,
  2878. milliseconds_elapsed, &tvnow);
  2879. relay_write_empty_time = bucket_millis_empty(prev_relay_write,
  2880. global_relayed_write_emptied,
  2881. global_relayed_write_bucket,
  2882. milliseconds_elapsed, &tvnow);
  2883. control_event_tb_empty("RELAY", relay_read_empty_time,
  2884. relay_write_empty_time, milliseconds_elapsed);
  2885. }
  2886. /* refill the per-connection buckets */
  2887. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  2888. if (connection_speaks_cells(conn)) {
  2889. or_connection_t *or_conn = TO_OR_CONN(conn);
  2890. int orbandwidthrate = or_conn->bandwidthrate;
  2891. int orbandwidthburst = or_conn->bandwidthburst;
  2892. int prev_conn_read = or_conn->read_bucket;
  2893. int prev_conn_write = or_conn->write_bucket;
  2894. if (connection_bucket_should_increase(or_conn->read_bucket, or_conn)) {
  2895. connection_bucket_refill_helper(&or_conn->read_bucket,
  2896. orbandwidthrate,
  2897. orbandwidthburst,
  2898. milliseconds_elapsed,
  2899. "or_conn->read_bucket");
  2900. }
  2901. if (connection_bucket_should_increase(or_conn->write_bucket, or_conn)) {
  2902. connection_bucket_refill_helper(&or_conn->write_bucket,
  2903. orbandwidthrate,
  2904. orbandwidthburst,
  2905. milliseconds_elapsed,
  2906. "or_conn->write_bucket");
  2907. }
  2908. /* If buckets were empty before and have now been refilled, tell any
  2909. * interested controllers. */
  2910. if (get_options()->TestingEnableTbEmptyEvent) {
  2911. char *bucket;
  2912. uint32_t conn_read_empty_time, conn_write_empty_time;
  2913. tor_asprintf(&bucket, "ORCONN ID="U64_FORMAT,
  2914. U64_PRINTF_ARG(or_conn->base_.global_identifier));
  2915. conn_read_empty_time = bucket_millis_empty(prev_conn_read,
  2916. or_conn->read_emptied_time,
  2917. or_conn->read_bucket,
  2918. milliseconds_elapsed, &tvnow);
  2919. conn_write_empty_time = bucket_millis_empty(prev_conn_write,
  2920. or_conn->write_emptied_time,
  2921. or_conn->write_bucket,
  2922. milliseconds_elapsed, &tvnow);
  2923. control_event_tb_empty(bucket, conn_read_empty_time,
  2924. conn_write_empty_time,
  2925. milliseconds_elapsed);
  2926. tor_free(bucket);
  2927. }
  2928. }
  2929. if (conn->read_blocked_on_bw == 1 /* marked to turn reading back on now */
  2930. && global_read_bucket > 0 /* and we're allowed to read */
  2931. && (!connection_counts_as_relayed_traffic(conn, now) ||
  2932. global_relayed_read_bucket > 0) /* even if we're relayed traffic */
  2933. && (!connection_speaks_cells(conn) ||
  2934. conn->state != OR_CONN_STATE_OPEN ||
  2935. TO_OR_CONN(conn)->read_bucket > 0)) {
  2936. /* and either a non-cell conn or a cell conn with non-empty bucket */
  2937. LOG_FN_CONN(conn, (LOG_DEBUG,LD_NET,
  2938. "waking up conn (fd %d) for read", (int)conn->s));
  2939. conn->read_blocked_on_bw = 0;
  2940. connection_start_reading(conn);
  2941. }
  2942. if (conn->write_blocked_on_bw == 1
  2943. && global_write_bucket > 0 /* and we're allowed to write */
  2944. && (!connection_counts_as_relayed_traffic(conn, now) ||
  2945. global_relayed_write_bucket > 0) /* even if it's relayed traffic */
  2946. && (!connection_speaks_cells(conn) ||
  2947. conn->state != OR_CONN_STATE_OPEN ||
  2948. TO_OR_CONN(conn)->write_bucket > 0)) {
  2949. LOG_FN_CONN(conn, (LOG_DEBUG,LD_NET,
  2950. "waking up conn (fd %d) for write", (int)conn->s));
  2951. conn->write_blocked_on_bw = 0;
  2952. connection_start_writing(conn);
  2953. }
  2954. } SMARTLIST_FOREACH_END(conn);
  2955. }
  2956. /** Is the <b>bucket</b> for connection <b>conn</b> low enough that we
  2957. * should add another pile of tokens to it?
  2958. */
  2959. static int
  2960. connection_bucket_should_increase(int bucket, or_connection_t *conn)
  2961. {
  2962. tor_assert(conn);
  2963. if (conn->base_.state != OR_CONN_STATE_OPEN)
  2964. return 0; /* only open connections play the rate limiting game */
  2965. if (bucket >= conn->bandwidthburst)
  2966. return 0;
  2967. return 1;
  2968. }
  2969. /** Read bytes from conn-\>s and process them.
  2970. *
  2971. * It calls connection_read_to_buf() to bring in any new bytes,
  2972. * and then calls connection_process_inbuf() to process them.
  2973. *
  2974. * Mark the connection and return -1 if you want to close it, else
  2975. * return 0.
  2976. */
  2977. static int
  2978. connection_handle_read_impl(connection_t *conn)
  2979. {
  2980. ssize_t max_to_read=-1, try_to_read;
  2981. size_t before, n_read = 0;
  2982. int socket_error = 0;
  2983. if (conn->marked_for_close)
  2984. return 0; /* do nothing */
  2985. conn->timestamp_lastread = approx_time();
  2986. switch (conn->type) {
  2987. case CONN_TYPE_OR_LISTENER:
  2988. return connection_handle_listener_read(conn, CONN_TYPE_OR);
  2989. case CONN_TYPE_EXT_OR_LISTENER:
  2990. return connection_handle_listener_read(conn, CONN_TYPE_EXT_OR);
  2991. case CONN_TYPE_AP_LISTENER:
  2992. case CONN_TYPE_AP_TRANS_LISTENER:
  2993. case CONN_TYPE_AP_NATD_LISTENER:
  2994. return connection_handle_listener_read(conn, CONN_TYPE_AP);
  2995. case CONN_TYPE_DIR_LISTENER:
  2996. return connection_handle_listener_read(conn, CONN_TYPE_DIR);
  2997. case CONN_TYPE_CONTROL_LISTENER:
  2998. return connection_handle_listener_read(conn, CONN_TYPE_CONTROL);
  2999. case CONN_TYPE_AP_DNS_LISTENER:
  3000. /* This should never happen; eventdns.c handles the reads here. */
  3001. tor_fragile_assert();
  3002. return 0;
  3003. }
  3004. loop_again:
  3005. try_to_read = max_to_read;
  3006. tor_assert(!conn->marked_for_close);
  3007. before = buf_datalen(conn->inbuf);
  3008. if (connection_read_to_buf(conn, &max_to_read, &socket_error) < 0) {
  3009. /* There's a read error; kill the connection.*/
  3010. if (conn->type == CONN_TYPE_OR) {
  3011. connection_or_notify_error(TO_OR_CONN(conn),
  3012. socket_error != 0 ?
  3013. errno_to_orconn_end_reason(socket_error) :
  3014. END_OR_CONN_REASON_CONNRESET,
  3015. socket_error != 0 ?
  3016. tor_socket_strerror(socket_error) :
  3017. "(unknown, errno was 0)");
  3018. }
  3019. if (CONN_IS_EDGE(conn)) {
  3020. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  3021. connection_edge_end_errno(edge_conn);
  3022. if (conn->type == CONN_TYPE_AP && TO_ENTRY_CONN(conn)->socks_request) {
  3023. /* broken, don't send a socks reply back */
  3024. TO_ENTRY_CONN(conn)->socks_request->has_finished = 1;
  3025. }
  3026. }
  3027. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  3028. /*
  3029. * This can bypass normal channel checking since we did
  3030. * connection_or_notify_error() above.
  3031. */
  3032. connection_mark_for_close_internal(conn);
  3033. return -1;
  3034. }
  3035. n_read += buf_datalen(conn->inbuf) - before;
  3036. if (CONN_IS_EDGE(conn) && try_to_read != max_to_read) {
  3037. /* instruct it not to try to package partial cells. */
  3038. if (connection_process_inbuf(conn, 0) < 0) {
  3039. return -1;
  3040. }
  3041. if (!conn->marked_for_close &&
  3042. connection_is_reading(conn) &&
  3043. !conn->inbuf_reached_eof &&
  3044. max_to_read > 0)
  3045. goto loop_again; /* try reading again, in case more is here now */
  3046. }
  3047. /* one last try, packaging partial cells and all. */
  3048. if (!conn->marked_for_close &&
  3049. connection_process_inbuf(conn, 1) < 0) {
  3050. return -1;
  3051. }
  3052. if (conn->linked_conn) {
  3053. /* The other side's handle_write() will never actually get called, so
  3054. * we need to invoke the appropriate callbacks ourself. */
  3055. connection_t *linked = conn->linked_conn;
  3056. if (n_read) {
  3057. /* Probably a no-op, since linked conns typically don't count for
  3058. * bandwidth rate limiting. But do it anyway so we can keep stats
  3059. * accurately. Note that since we read the bytes from conn, and
  3060. * we're writing the bytes onto the linked connection, we count
  3061. * these as <i>written</i> bytes. */
  3062. connection_buckets_decrement(linked, approx_time(), 0, n_read);
  3063. if (connection_flushed_some(linked) < 0)
  3064. connection_mark_for_close(linked);
  3065. if (!connection_wants_to_flush(linked))
  3066. connection_finished_flushing(linked);
  3067. }
  3068. if (!buf_datalen(linked->outbuf) && conn->active_on_link)
  3069. connection_stop_reading_from_linked_conn(conn);
  3070. }
  3071. /* If we hit the EOF, call connection_reached_eof(). */
  3072. if (!conn->marked_for_close &&
  3073. conn->inbuf_reached_eof &&
  3074. connection_reached_eof(conn) < 0) {
  3075. return -1;
  3076. }
  3077. return 0;
  3078. }
  3079. /* DOCDOC connection_handle_read */
  3080. int
  3081. connection_handle_read(connection_t *conn)
  3082. {
  3083. int res;
  3084. tor_gettimeofday_cache_clear();
  3085. res = connection_handle_read_impl(conn);
  3086. return res;
  3087. }
  3088. /** Pull in new bytes from conn-\>s or conn-\>linked_conn onto conn-\>inbuf,
  3089. * either directly or via TLS. Reduce the token buckets by the number of bytes
  3090. * read.
  3091. *
  3092. * If *max_to_read is -1, then decide it ourselves, else go with the
  3093. * value passed to us. When returning, if it's changed, subtract the
  3094. * number of bytes we read from *max_to_read.
  3095. *
  3096. * Return -1 if we want to break conn, else return 0.
  3097. */
  3098. static int
  3099. connection_read_to_buf(connection_t *conn, ssize_t *max_to_read,
  3100. int *socket_error)
  3101. {
  3102. int result;
  3103. ssize_t at_most = *max_to_read;
  3104. size_t slack_in_buf, more_to_read;
  3105. size_t n_read = 0, n_written = 0;
  3106. if (at_most == -1) { /* we need to initialize it */
  3107. /* how many bytes are we allowed to read? */
  3108. at_most = connection_bucket_read_limit(conn, approx_time());
  3109. }
  3110. slack_in_buf = buf_slack(conn->inbuf);
  3111. again:
  3112. if ((size_t)at_most > slack_in_buf && slack_in_buf >= 1024) {
  3113. more_to_read = at_most - slack_in_buf;
  3114. at_most = slack_in_buf;
  3115. } else {
  3116. more_to_read = 0;
  3117. }
  3118. if (connection_speaks_cells(conn) &&
  3119. conn->state > OR_CONN_STATE_PROXY_HANDSHAKING) {
  3120. int pending;
  3121. or_connection_t *or_conn = TO_OR_CONN(conn);
  3122. size_t initial_size;
  3123. if (conn->state == OR_CONN_STATE_TLS_HANDSHAKING ||
  3124. conn->state == OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING) {
  3125. /* continue handshaking even if global token bucket is empty */
  3126. return connection_tls_continue_handshake(or_conn);
  3127. }
  3128. log_debug(LD_NET,
  3129. "%d: starting, inbuf_datalen %ld (%d pending in tls object)."
  3130. " at_most %ld.",
  3131. (int)conn->s,(long)buf_datalen(conn->inbuf),
  3132. tor_tls_get_pending_bytes(or_conn->tls), (long)at_most);
  3133. initial_size = buf_datalen(conn->inbuf);
  3134. /* else open, or closing */
  3135. result = read_to_buf_tls(or_conn->tls, at_most, conn->inbuf);
  3136. if (TOR_TLS_IS_ERROR(result) || result == TOR_TLS_CLOSE)
  3137. or_conn->tls_error = result;
  3138. else
  3139. or_conn->tls_error = 0;
  3140. switch (result) {
  3141. case TOR_TLS_CLOSE:
  3142. case TOR_TLS_ERROR_IO:
  3143. log_debug(LD_NET,"TLS connection closed %son read. Closing. "
  3144. "(Nickname %s, address %s)",
  3145. result == TOR_TLS_CLOSE ? "cleanly " : "",
  3146. or_conn->nickname ? or_conn->nickname : "not set",
  3147. conn->address);
  3148. return result;
  3149. CASE_TOR_TLS_ERROR_ANY_NONIO:
  3150. log_debug(LD_NET,"tls error [%s]. breaking (nickname %s, address %s).",
  3151. tor_tls_err_to_string(result),
  3152. or_conn->nickname ? or_conn->nickname : "not set",
  3153. conn->address);
  3154. return result;
  3155. case TOR_TLS_WANTWRITE:
  3156. connection_start_writing(conn);
  3157. return 0;
  3158. case TOR_TLS_WANTREAD:
  3159. if (conn->in_connection_handle_write) {
  3160. /* We've been invoked from connection_handle_write, because we're
  3161. * waiting for a TLS renegotiation, the renegotiation started, and
  3162. * SSL_read returned WANTWRITE. But now SSL_read is saying WANTREAD
  3163. * again. Stop waiting for write events now, or else we'll
  3164. * busy-loop until data arrives for us to read. */
  3165. connection_stop_writing(conn);
  3166. if (!connection_is_reading(conn))
  3167. connection_start_reading(conn);
  3168. }
  3169. /* we're already reading, one hopes */
  3170. result = 0;
  3171. break;
  3172. case TOR_TLS_DONE: /* no data read, so nothing to process */
  3173. result = 0;
  3174. break; /* so we call bucket_decrement below */
  3175. default:
  3176. break;
  3177. }
  3178. pending = tor_tls_get_pending_bytes(or_conn->tls);
  3179. if (pending) {
  3180. /* If we have any pending bytes, we read them now. This *can*
  3181. * take us over our read allotment, but really we shouldn't be
  3182. * believing that SSL bytes are the same as TCP bytes anyway. */
  3183. int r2 = read_to_buf_tls(or_conn->tls, pending, conn->inbuf);
  3184. if (BUG(r2<0)) {
  3185. log_warn(LD_BUG, "apparently, reading pending bytes can fail.");
  3186. return -1;
  3187. }
  3188. }
  3189. result = (int)(buf_datalen(conn->inbuf)-initial_size);
  3190. tor_tls_get_n_raw_bytes(or_conn->tls, &n_read, &n_written);
  3191. log_debug(LD_GENERAL, "After TLS read of %d: %ld read, %ld written",
  3192. result, (long)n_read, (long)n_written);
  3193. } else if (conn->linked) {
  3194. if (conn->linked_conn) {
  3195. result = move_buf_to_buf(conn->inbuf, conn->linked_conn->outbuf,
  3196. &conn->linked_conn->outbuf_flushlen);
  3197. } else {
  3198. result = 0;
  3199. }
  3200. //log_notice(LD_GENERAL, "Moved %d bytes on an internal link!", result);
  3201. /* If the other side has disappeared, or if it's been marked for close and
  3202. * we flushed its outbuf, then we should set our inbuf_reached_eof. */
  3203. if (!conn->linked_conn ||
  3204. (conn->linked_conn->marked_for_close &&
  3205. buf_datalen(conn->linked_conn->outbuf) == 0))
  3206. conn->inbuf_reached_eof = 1;
  3207. n_read = (size_t) result;
  3208. } else {
  3209. /* !connection_speaks_cells, !conn->linked_conn. */
  3210. int reached_eof = 0;
  3211. CONN_LOG_PROTECT(conn,
  3212. result = read_to_buf(conn->s, at_most, conn->inbuf, &reached_eof,
  3213. socket_error));
  3214. if (reached_eof)
  3215. conn->inbuf_reached_eof = 1;
  3216. // log_fn(LOG_DEBUG,"read_to_buf returned %d.",read_result);
  3217. if (result < 0)
  3218. return -1;
  3219. n_read = (size_t) result;
  3220. }
  3221. if (n_read > 0) {
  3222. /* change *max_to_read */
  3223. *max_to_read = at_most - n_read;
  3224. /* Update edge_conn->n_read and ocirc->n_read_circ_bw */
  3225. if (conn->type == CONN_TYPE_AP) {
  3226. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  3227. circuit_t *circ = circuit_get_by_edge_conn(edge_conn);
  3228. origin_circuit_t *ocirc;
  3229. /* Check for overflow: */
  3230. if (PREDICT_LIKELY(UINT32_MAX - edge_conn->n_read > n_read))
  3231. edge_conn->n_read += (int)n_read;
  3232. else
  3233. edge_conn->n_read = UINT32_MAX;
  3234. if (circ && CIRCUIT_IS_ORIGIN(circ)) {
  3235. ocirc = TO_ORIGIN_CIRCUIT(circ);
  3236. if (PREDICT_LIKELY(UINT32_MAX - ocirc->n_read_circ_bw > n_read))
  3237. ocirc->n_read_circ_bw += (int)n_read;
  3238. else
  3239. ocirc->n_read_circ_bw = UINT32_MAX;
  3240. }
  3241. }
  3242. /* If CONN_BW events are enabled, update conn->n_read_conn_bw for
  3243. * OR/DIR/EXIT connections, checking for overflow. */
  3244. if (get_options()->TestingEnableConnBwEvent &&
  3245. (conn->type == CONN_TYPE_OR ||
  3246. conn->type == CONN_TYPE_DIR ||
  3247. conn->type == CONN_TYPE_EXIT)) {
  3248. if (PREDICT_LIKELY(UINT32_MAX - conn->n_read_conn_bw > n_read))
  3249. conn->n_read_conn_bw += (int)n_read;
  3250. else
  3251. conn->n_read_conn_bw = UINT32_MAX;
  3252. }
  3253. }
  3254. connection_buckets_decrement(conn, approx_time(), n_read, n_written);
  3255. if (more_to_read && result == at_most) {
  3256. slack_in_buf = buf_slack(conn->inbuf);
  3257. at_most = more_to_read;
  3258. goto again;
  3259. }
  3260. /* Call even if result is 0, since the global read bucket may
  3261. * have reached 0 on a different conn, and this connection needs to
  3262. * know to stop reading. */
  3263. connection_consider_empty_read_buckets(conn);
  3264. if (n_written > 0 && connection_is_writing(conn))
  3265. connection_consider_empty_write_buckets(conn);
  3266. return 0;
  3267. }
  3268. /** A pass-through to fetch_from_buf. */
  3269. int
  3270. connection_fetch_from_buf(char *string, size_t len, connection_t *conn)
  3271. {
  3272. return fetch_from_buf(string, len, conn->inbuf);
  3273. }
  3274. /** As fetch_from_buf_line(), but read from a connection's input buffer. */
  3275. int
  3276. connection_fetch_from_buf_line(connection_t *conn, char *data,
  3277. size_t *data_len)
  3278. {
  3279. return fetch_from_buf_line(conn->inbuf, data, data_len);
  3280. }
  3281. /** As fetch_from_buf_http, but fetches from a connection's input buffer_t as
  3282. * appropriate. */
  3283. int
  3284. connection_fetch_from_buf_http(connection_t *conn,
  3285. char **headers_out, size_t max_headerlen,
  3286. char **body_out, size_t *body_used,
  3287. size_t max_bodylen, int force_complete)
  3288. {
  3289. return fetch_from_buf_http(conn->inbuf, headers_out, max_headerlen,
  3290. body_out, body_used, max_bodylen, force_complete);
  3291. }
  3292. /** Return conn-\>outbuf_flushlen: how many bytes conn wants to flush
  3293. * from its outbuf. */
  3294. int
  3295. connection_wants_to_flush(connection_t *conn)
  3296. {
  3297. return conn->outbuf_flushlen > 0;
  3298. }
  3299. /** Are there too many bytes on edge connection <b>conn</b>'s outbuf to
  3300. * send back a relay-level sendme yet? Return 1 if so, 0 if not. Used by
  3301. * connection_edge_consider_sending_sendme().
  3302. */
  3303. int
  3304. connection_outbuf_too_full(connection_t *conn)
  3305. {
  3306. return (conn->outbuf_flushlen > 10*CELL_PAYLOAD_SIZE);
  3307. }
  3308. /** Try to flush more bytes onto <b>conn</b>-\>s.
  3309. *
  3310. * This function gets called either from conn_write_callback() in main.c
  3311. * when libevent tells us that conn wants to write, or below
  3312. * from connection_write_to_buf() when an entire TLS record is ready.
  3313. *
  3314. * Update <b>conn</b>-\>timestamp_lastwritten to now, and call flush_buf
  3315. * or flush_buf_tls appropriately. If it succeeds and there are no more
  3316. * more bytes on <b>conn</b>-\>outbuf, then call connection_finished_flushing
  3317. * on it too.
  3318. *
  3319. * If <b>force</b>, then write as many bytes as possible, ignoring bandwidth
  3320. * limits. (Used for flushing messages to controller connections on fatal
  3321. * errors.)
  3322. *
  3323. * Mark the connection and return -1 if you want to close it, else
  3324. * return 0.
  3325. */
  3326. static int
  3327. connection_handle_write_impl(connection_t *conn, int force)
  3328. {
  3329. int e;
  3330. socklen_t len=(socklen_t)sizeof(e);
  3331. int result;
  3332. ssize_t max_to_write;
  3333. time_t now = approx_time();
  3334. size_t n_read = 0, n_written = 0;
  3335. int dont_stop_writing = 0;
  3336. tor_assert(!connection_is_listener(conn));
  3337. if (conn->marked_for_close || !SOCKET_OK(conn->s))
  3338. return 0; /* do nothing */
  3339. if (conn->in_flushed_some) {
  3340. log_warn(LD_BUG, "called recursively from inside conn->in_flushed_some");
  3341. return 0;
  3342. }
  3343. conn->timestamp_lastwritten = now;
  3344. /* Sometimes, "writable" means "connected". */
  3345. if (connection_state_is_connecting(conn)) {
  3346. if (getsockopt(conn->s, SOL_SOCKET, SO_ERROR, (void*)&e, &len) < 0) {
  3347. log_warn(LD_BUG, "getsockopt() syscall failed");
  3348. if (conn->type == CONN_TYPE_OR) {
  3349. or_connection_t *orconn = TO_OR_CONN(conn);
  3350. connection_or_close_for_error(orconn, 0);
  3351. } else {
  3352. if (CONN_IS_EDGE(conn)) {
  3353. connection_edge_end_errno(TO_EDGE_CONN(conn));
  3354. }
  3355. connection_mark_for_close(conn);
  3356. }
  3357. return -1;
  3358. }
  3359. if (e) {
  3360. /* some sort of error, but maybe just inprogress still */
  3361. if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
  3362. log_info(LD_NET,"in-progress connect failed. Removing. (%s)",
  3363. tor_socket_strerror(e));
  3364. if (CONN_IS_EDGE(conn))
  3365. connection_edge_end_errno(TO_EDGE_CONN(conn));
  3366. if (conn->type == CONN_TYPE_OR)
  3367. connection_or_notify_error(TO_OR_CONN(conn),
  3368. errno_to_orconn_end_reason(e),
  3369. tor_socket_strerror(e));
  3370. connection_close_immediate(conn);
  3371. /*
  3372. * This can bypass normal channel checking since we did
  3373. * connection_or_notify_error() above.
  3374. */
  3375. connection_mark_for_close_internal(conn);
  3376. return -1;
  3377. } else {
  3378. return 0; /* no change, see if next time is better */
  3379. }
  3380. }
  3381. /* The connection is successful. */
  3382. if (connection_finished_connecting(conn)<0)
  3383. return -1;
  3384. }
  3385. max_to_write = force ? (ssize_t)conn->outbuf_flushlen
  3386. : connection_bucket_write_limit(conn, now);
  3387. if (connection_speaks_cells(conn) &&
  3388. conn->state > OR_CONN_STATE_PROXY_HANDSHAKING) {
  3389. or_connection_t *or_conn = TO_OR_CONN(conn);
  3390. size_t initial_size;
  3391. if (conn->state == OR_CONN_STATE_TLS_HANDSHAKING ||
  3392. conn->state == OR_CONN_STATE_TLS_CLIENT_RENEGOTIATING) {
  3393. connection_stop_writing(conn);
  3394. if (connection_tls_continue_handshake(or_conn) < 0) {
  3395. /* Don't flush; connection is dead. */
  3396. connection_or_notify_error(or_conn,
  3397. END_OR_CONN_REASON_MISC,
  3398. "TLS error in connection_tls_"
  3399. "continue_handshake()");
  3400. connection_close_immediate(conn);
  3401. /*
  3402. * This can bypass normal channel checking since we did
  3403. * connection_or_notify_error() above.
  3404. */
  3405. connection_mark_for_close_internal(conn);
  3406. return -1;
  3407. }
  3408. return 0;
  3409. } else if (conn->state == OR_CONN_STATE_TLS_SERVER_RENEGOTIATING) {
  3410. return connection_handle_read(conn);
  3411. }
  3412. /* else open, or closing */
  3413. initial_size = buf_datalen(conn->outbuf);
  3414. result = flush_buf_tls(or_conn->tls, conn->outbuf,
  3415. max_to_write, &conn->outbuf_flushlen);
  3416. /* If we just flushed the last bytes, tell the channel on the
  3417. * or_conn to check if it needs to geoip_change_dirreq_state() */
  3418. /* XXXX move this to flushed_some or finished_flushing -NM */
  3419. if (buf_datalen(conn->outbuf) == 0 && or_conn->chan)
  3420. channel_notify_flushed(TLS_CHAN_TO_BASE(or_conn->chan));
  3421. switch (result) {
  3422. CASE_TOR_TLS_ERROR_ANY:
  3423. case TOR_TLS_CLOSE:
  3424. log_info(LD_NET, result != TOR_TLS_CLOSE ?
  3425. "tls error. breaking.":"TLS connection closed on flush");
  3426. /* Don't flush; connection is dead. */
  3427. connection_or_notify_error(or_conn,
  3428. END_OR_CONN_REASON_MISC,
  3429. result != TOR_TLS_CLOSE ?
  3430. "TLS error in during flush" :
  3431. "TLS closed during flush");
  3432. connection_close_immediate(conn);
  3433. /*
  3434. * This can bypass normal channel checking since we did
  3435. * connection_or_notify_error() above.
  3436. */
  3437. connection_mark_for_close_internal(conn);
  3438. return -1;
  3439. case TOR_TLS_WANTWRITE:
  3440. log_debug(LD_NET,"wanted write.");
  3441. /* we're already writing */
  3442. dont_stop_writing = 1;
  3443. break;
  3444. case TOR_TLS_WANTREAD:
  3445. /* Make sure to avoid a loop if the receive buckets are empty. */
  3446. log_debug(LD_NET,"wanted read.");
  3447. if (!connection_is_reading(conn)) {
  3448. connection_stop_writing(conn);
  3449. conn->write_blocked_on_bw = 1;
  3450. /* we'll start reading again when we get more tokens in our
  3451. * read bucket; then we'll start writing again too.
  3452. */
  3453. }
  3454. /* else no problem, we're already reading */
  3455. return 0;
  3456. /* case TOR_TLS_DONE:
  3457. * for TOR_TLS_DONE, fall through to check if the flushlen
  3458. * is empty, so we can stop writing.
  3459. */
  3460. }
  3461. tor_tls_get_n_raw_bytes(or_conn->tls, &n_read, &n_written);
  3462. log_debug(LD_GENERAL, "After TLS write of %d: %ld read, %ld written",
  3463. result, (long)n_read, (long)n_written);
  3464. or_conn->bytes_xmitted += result;
  3465. or_conn->bytes_xmitted_by_tls += n_written;
  3466. /* So we notice bytes were written even on error */
  3467. /* XXXX This cast is safe since we can never write INT_MAX bytes in a
  3468. * single set of TLS operations. But it looks kinda ugly. If we refactor
  3469. * the *_buf_tls functions, we should make them return ssize_t or size_t
  3470. * or something. */
  3471. result = (int)(initial_size-buf_datalen(conn->outbuf));
  3472. } else {
  3473. CONN_LOG_PROTECT(conn,
  3474. result = flush_buf(conn->s, conn->outbuf,
  3475. max_to_write, &conn->outbuf_flushlen));
  3476. if (result < 0) {
  3477. if (CONN_IS_EDGE(conn))
  3478. connection_edge_end_errno(TO_EDGE_CONN(conn));
  3479. if (conn->type == CONN_TYPE_AP) {
  3480. /* writing failed; we couldn't send a SOCKS reply if we wanted to */
  3481. TO_ENTRY_CONN(conn)->socks_request->has_finished = 1;
  3482. }
  3483. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  3484. connection_mark_for_close(conn);
  3485. return -1;
  3486. }
  3487. n_written = (size_t) result;
  3488. }
  3489. if (n_written && conn->type == CONN_TYPE_AP) {
  3490. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  3491. circuit_t *circ = circuit_get_by_edge_conn(edge_conn);
  3492. origin_circuit_t *ocirc;
  3493. /* Check for overflow: */
  3494. if (PREDICT_LIKELY(UINT32_MAX - edge_conn->n_written > n_written))
  3495. edge_conn->n_written += (int)n_written;
  3496. else
  3497. edge_conn->n_written = UINT32_MAX;
  3498. if (circ && CIRCUIT_IS_ORIGIN(circ)) {
  3499. ocirc = TO_ORIGIN_CIRCUIT(circ);
  3500. if (PREDICT_LIKELY(UINT32_MAX - ocirc->n_written_circ_bw > n_written))
  3501. ocirc->n_written_circ_bw += (int)n_written;
  3502. else
  3503. ocirc->n_written_circ_bw = UINT32_MAX;
  3504. }
  3505. }
  3506. /* If CONN_BW events are enabled, update conn->n_written_conn_bw for
  3507. * OR/DIR/EXIT connections, checking for overflow. */
  3508. if (n_written && get_options()->TestingEnableConnBwEvent &&
  3509. (conn->type == CONN_TYPE_OR ||
  3510. conn->type == CONN_TYPE_DIR ||
  3511. conn->type == CONN_TYPE_EXIT)) {
  3512. if (PREDICT_LIKELY(UINT32_MAX - conn->n_written_conn_bw > n_written))
  3513. conn->n_written_conn_bw += (int)n_written;
  3514. else
  3515. conn->n_written_conn_bw = UINT32_MAX;
  3516. }
  3517. connection_buckets_decrement(conn, approx_time(), n_read, n_written);
  3518. if (result > 0) {
  3519. /* If we wrote any bytes from our buffer, then call the appropriate
  3520. * functions. */
  3521. if (connection_flushed_some(conn) < 0) {
  3522. if (connection_speaks_cells(conn)) {
  3523. connection_or_notify_error(TO_OR_CONN(conn),
  3524. END_OR_CONN_REASON_MISC,
  3525. "Got error back from "
  3526. "connection_flushed_some()");
  3527. }
  3528. /*
  3529. * This can bypass normal channel checking since we did
  3530. * connection_or_notify_error() above.
  3531. */
  3532. connection_mark_for_close_internal(conn);
  3533. }
  3534. }
  3535. if (!connection_wants_to_flush(conn) &&
  3536. !dont_stop_writing) { /* it's done flushing */
  3537. if (connection_finished_flushing(conn) < 0) {
  3538. /* already marked */
  3539. return -1;
  3540. }
  3541. return 0;
  3542. }
  3543. /* Call even if result is 0, since the global write bucket may
  3544. * have reached 0 on a different conn, and this connection needs to
  3545. * know to stop writing. */
  3546. connection_consider_empty_write_buckets(conn);
  3547. if (n_read > 0 && connection_is_reading(conn))
  3548. connection_consider_empty_read_buckets(conn);
  3549. return 0;
  3550. }
  3551. /* DOCDOC connection_handle_write */
  3552. int
  3553. connection_handle_write(connection_t *conn, int force)
  3554. {
  3555. int res;
  3556. tor_gettimeofday_cache_clear();
  3557. conn->in_connection_handle_write = 1;
  3558. res = connection_handle_write_impl(conn, force);
  3559. conn->in_connection_handle_write = 0;
  3560. return res;
  3561. }
  3562. /**
  3563. * Try to flush data that's waiting for a write on <b>conn</b>. Return
  3564. * -1 on failure, 0 on success.
  3565. *
  3566. * Don't use this function for regular writing; the buffers
  3567. * system should be good enough at scheduling writes there. Instead, this
  3568. * function is for cases when we're about to exit or something and we want
  3569. * to report it right away.
  3570. */
  3571. int
  3572. connection_flush(connection_t *conn)
  3573. {
  3574. return connection_handle_write(conn, 1);
  3575. }
  3576. /** Append <b>len</b> bytes of <b>string</b> onto <b>conn</b>'s
  3577. * outbuf, and ask it to start writing.
  3578. *
  3579. * If <b>zlib</b> is nonzero, this is a directory connection that should get
  3580. * its contents compressed or decompressed as they're written. If zlib is
  3581. * negative, this is the last data to be compressed, and the connection's zlib
  3582. * state should be flushed.
  3583. *
  3584. * If it's a local control connection and a 64k chunk is ready, try to flush
  3585. * it all, so we don't end up with many megabytes of controller info queued at
  3586. * once.
  3587. */
  3588. MOCK_IMPL(void,
  3589. connection_write_to_buf_impl_,(const char *string, size_t len,
  3590. connection_t *conn, int zlib))
  3591. {
  3592. /* XXXX This function really needs to return -1 on failure. */
  3593. int r;
  3594. size_t old_datalen;
  3595. if (!len && !(zlib<0))
  3596. return;
  3597. /* if it's marked for close, only allow write if we mean to flush it */
  3598. if (conn->marked_for_close && !conn->hold_open_until_flushed)
  3599. return;
  3600. old_datalen = buf_datalen(conn->outbuf);
  3601. if (zlib) {
  3602. dir_connection_t *dir_conn = TO_DIR_CONN(conn);
  3603. int done = zlib < 0;
  3604. CONN_LOG_PROTECT(conn, r = write_to_buf_zlib(conn->outbuf,
  3605. dir_conn->zlib_state,
  3606. string, len, done));
  3607. } else {
  3608. CONN_LOG_PROTECT(conn, r = write_to_buf(string, len, conn->outbuf));
  3609. }
  3610. if (r < 0) {
  3611. if (CONN_IS_EDGE(conn)) {
  3612. /* if it failed, it means we have our package/delivery windows set
  3613. wrong compared to our max outbuf size. close the whole circuit. */
  3614. log_warn(LD_NET,
  3615. "write_to_buf failed. Closing circuit (fd %d).", (int)conn->s);
  3616. circuit_mark_for_close(circuit_get_by_edge_conn(TO_EDGE_CONN(conn)),
  3617. END_CIRC_REASON_INTERNAL);
  3618. } else if (conn->type == CONN_TYPE_OR) {
  3619. or_connection_t *orconn = TO_OR_CONN(conn);
  3620. log_warn(LD_NET,
  3621. "write_to_buf failed on an orconn; notifying of error "
  3622. "(fd %d)", (int)(conn->s));
  3623. connection_or_close_for_error(orconn, 0);
  3624. } else {
  3625. log_warn(LD_NET,
  3626. "write_to_buf failed. Closing connection (fd %d).",
  3627. (int)conn->s);
  3628. connection_mark_for_close(conn);
  3629. }
  3630. return;
  3631. }
  3632. /* If we receive optimistic data in the EXIT_CONN_STATE_RESOLVING
  3633. * state, we don't want to try to write it right away, since
  3634. * conn->write_event won't be set yet. Otherwise, write data from
  3635. * this conn as the socket is available. */
  3636. if (conn->write_event) {
  3637. connection_start_writing(conn);
  3638. }
  3639. if (zlib) {
  3640. conn->outbuf_flushlen += buf_datalen(conn->outbuf) - old_datalen;
  3641. } else {
  3642. conn->outbuf_flushlen += len;
  3643. }
  3644. }
  3645. /** Return a connection_t * from get_connection_array() that satisfies test on
  3646. * var, and that is not marked for close. */
  3647. #define CONN_GET_TEMPLATE(var, test) \
  3648. STMT_BEGIN \
  3649. smartlist_t *conns = get_connection_array(); \
  3650. SMARTLIST_FOREACH(conns, connection_t *, var, \
  3651. { \
  3652. if (var && (test) && !var->marked_for_close) \
  3653. return var; \
  3654. }); \
  3655. return NULL; \
  3656. STMT_END
  3657. /** Return a connection with given type, address, port, and purpose;
  3658. * or NULL if no such connection exists (or if all such connections are marked
  3659. * for close). */
  3660. MOCK_IMPL(connection_t *,
  3661. connection_get_by_type_addr_port_purpose,(int type,
  3662. const tor_addr_t *addr, uint16_t port,
  3663. int purpose))
  3664. {
  3665. CONN_GET_TEMPLATE(conn,
  3666. (conn->type == type &&
  3667. tor_addr_eq(&conn->addr, addr) &&
  3668. conn->port == port &&
  3669. conn->purpose == purpose));
  3670. }
  3671. /** Return the stream with id <b>id</b> if it is not already marked for
  3672. * close.
  3673. */
  3674. connection_t *
  3675. connection_get_by_global_id(uint64_t id)
  3676. {
  3677. CONN_GET_TEMPLATE(conn, conn->global_identifier == id);
  3678. }
  3679. /** Return a connection of type <b>type</b> that is not marked for close.
  3680. */
  3681. connection_t *
  3682. connection_get_by_type(int type)
  3683. {
  3684. CONN_GET_TEMPLATE(conn, conn->type == type);
  3685. }
  3686. /** Return a connection of type <b>type</b> that is in state <b>state</b>,
  3687. * and that is not marked for close.
  3688. */
  3689. connection_t *
  3690. connection_get_by_type_state(int type, int state)
  3691. {
  3692. CONN_GET_TEMPLATE(conn, conn->type == type && conn->state == state);
  3693. }
  3694. /** Return a connection of type <b>type</b> that has rendquery equal
  3695. * to <b>rendquery</b>, and that is not marked for close. If state
  3696. * is non-zero, conn must be of that state too.
  3697. */
  3698. connection_t *
  3699. connection_get_by_type_state_rendquery(int type, int state,
  3700. const char *rendquery)
  3701. {
  3702. tor_assert(type == CONN_TYPE_DIR ||
  3703. type == CONN_TYPE_AP || type == CONN_TYPE_EXIT);
  3704. tor_assert(rendquery);
  3705. CONN_GET_TEMPLATE(conn,
  3706. (conn->type == type &&
  3707. (!state || state == conn->state)) &&
  3708. (
  3709. (type == CONN_TYPE_DIR &&
  3710. TO_DIR_CONN(conn)->rend_data &&
  3711. !rend_cmp_service_ids(rendquery,
  3712. TO_DIR_CONN(conn)->rend_data->onion_address))
  3713. ||
  3714. (CONN_IS_EDGE(conn) &&
  3715. TO_EDGE_CONN(conn)->rend_data &&
  3716. !rend_cmp_service_ids(rendquery,
  3717. TO_EDGE_CONN(conn)->rend_data->onion_address))
  3718. ));
  3719. }
  3720. /** Return a new smartlist of dir_connection_t * from get_connection_array()
  3721. * that satisfy conn_test on connection_t *conn_var, and dirconn_test on
  3722. * dir_connection_t *dirconn_var. conn_var must be of CONN_TYPE_DIR and not
  3723. * marked for close to be included in the list. */
  3724. #define DIR_CONN_LIST_TEMPLATE(conn_var, conn_test, \
  3725. dirconn_var, dirconn_test) \
  3726. STMT_BEGIN \
  3727. smartlist_t *conns = get_connection_array(); \
  3728. smartlist_t *dir_conns = smartlist_new(); \
  3729. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn_var) { \
  3730. if (conn_var && (conn_test) \
  3731. && conn_var->type == CONN_TYPE_DIR \
  3732. && !conn_var->marked_for_close) { \
  3733. dir_connection_t *dirconn_var = TO_DIR_CONN(conn_var); \
  3734. if (dirconn_var && (dirconn_test)) { \
  3735. smartlist_add(dir_conns, dirconn_var); \
  3736. } \
  3737. } \
  3738. } SMARTLIST_FOREACH_END(conn_var); \
  3739. return dir_conns; \
  3740. STMT_END
  3741. /** Return a list of directory connections that are fetching the item
  3742. * described by <b>purpose</b>/<b>resource</b>. If there are none,
  3743. * return an empty list. This list must be freed using smartlist_free,
  3744. * but the pointers in it must not be freed.
  3745. * Note that this list should not be cached, as the pointers in it can be
  3746. * freed if their connections close. */
  3747. smartlist_t *
  3748. connection_dir_list_by_purpose_and_resource(
  3749. int purpose,
  3750. const char *resource)
  3751. {
  3752. DIR_CONN_LIST_TEMPLATE(conn,
  3753. conn->purpose == purpose,
  3754. dirconn,
  3755. 0 == strcmp_opt(resource,
  3756. dirconn->requested_resource));
  3757. }
  3758. /** Return a list of directory connections that are fetching the item
  3759. * described by <b>purpose</b>/<b>resource</b>/<b>state</b>. If there are
  3760. * none, return an empty list. This list must be freed using smartlist_free,
  3761. * but the pointers in it must not be freed.
  3762. * Note that this list should not be cached, as the pointers in it can be
  3763. * freed if their connections close. */
  3764. smartlist_t *
  3765. connection_dir_list_by_purpose_resource_and_state(
  3766. int purpose,
  3767. const char *resource,
  3768. int state)
  3769. {
  3770. DIR_CONN_LIST_TEMPLATE(conn,
  3771. conn->purpose == purpose && conn->state == state,
  3772. dirconn,
  3773. 0 == strcmp_opt(resource,
  3774. dirconn->requested_resource));
  3775. }
  3776. #undef DIR_CONN_LIST_TEMPLATE
  3777. /** Return an arbitrary active OR connection that isn't <b>this_conn</b>.
  3778. *
  3779. * We use this to guess if we should tell the controller that we
  3780. * didn't manage to connect to any of our bridges. */
  3781. static connection_t *
  3782. connection_get_another_active_or_conn(const or_connection_t *this_conn)
  3783. {
  3784. CONN_GET_TEMPLATE(conn,
  3785. conn != TO_CONN(this_conn) && conn->type == CONN_TYPE_OR);
  3786. }
  3787. /** Return 1 if there are any active OR connections apart from
  3788. * <b>this_conn</b>.
  3789. *
  3790. * We use this to guess if we should tell the controller that we
  3791. * didn't manage to connect to any of our bridges. */
  3792. int
  3793. any_other_active_or_conns(const or_connection_t *this_conn)
  3794. {
  3795. connection_t *conn = connection_get_another_active_or_conn(this_conn);
  3796. if (conn != NULL) {
  3797. log_debug(LD_DIR, "%s: Found an OR connection: %s",
  3798. __func__, conn->address);
  3799. return 1;
  3800. }
  3801. return 0;
  3802. }
  3803. #undef CONN_GET_TEMPLATE
  3804. /** Return 1 if <b>conn</b> is a listener conn, else return 0. */
  3805. int
  3806. connection_is_listener(connection_t *conn)
  3807. {
  3808. if (conn->type == CONN_TYPE_OR_LISTENER ||
  3809. conn->type == CONN_TYPE_EXT_OR_LISTENER ||
  3810. conn->type == CONN_TYPE_AP_LISTENER ||
  3811. conn->type == CONN_TYPE_AP_TRANS_LISTENER ||
  3812. conn->type == CONN_TYPE_AP_DNS_LISTENER ||
  3813. conn->type == CONN_TYPE_AP_NATD_LISTENER ||
  3814. conn->type == CONN_TYPE_DIR_LISTENER ||
  3815. conn->type == CONN_TYPE_CONTROL_LISTENER)
  3816. return 1;
  3817. return 0;
  3818. }
  3819. /** Return 1 if <b>conn</b> is in state "open" and is not marked
  3820. * for close, else return 0.
  3821. */
  3822. int
  3823. connection_state_is_open(connection_t *conn)
  3824. {
  3825. tor_assert(conn);
  3826. if (conn->marked_for_close)
  3827. return 0;
  3828. if ((conn->type == CONN_TYPE_OR && conn->state == OR_CONN_STATE_OPEN) ||
  3829. (conn->type == CONN_TYPE_EXT_OR) ||
  3830. (conn->type == CONN_TYPE_AP && conn->state == AP_CONN_STATE_OPEN) ||
  3831. (conn->type == CONN_TYPE_EXIT && conn->state == EXIT_CONN_STATE_OPEN) ||
  3832. (conn->type == CONN_TYPE_CONTROL &&
  3833. conn->state == CONTROL_CONN_STATE_OPEN))
  3834. return 1;
  3835. return 0;
  3836. }
  3837. /** Return 1 if conn is in 'connecting' state, else return 0. */
  3838. int
  3839. connection_state_is_connecting(connection_t *conn)
  3840. {
  3841. tor_assert(conn);
  3842. if (conn->marked_for_close)
  3843. return 0;
  3844. switch (conn->type)
  3845. {
  3846. case CONN_TYPE_OR:
  3847. return conn->state == OR_CONN_STATE_CONNECTING;
  3848. case CONN_TYPE_EXIT:
  3849. return conn->state == EXIT_CONN_STATE_CONNECTING;
  3850. case CONN_TYPE_DIR:
  3851. return conn->state == DIR_CONN_STATE_CONNECTING;
  3852. }
  3853. return 0;
  3854. }
  3855. /** Allocates a base64'ed authenticator for use in http or https
  3856. * auth, based on the input string <b>authenticator</b>. Returns it
  3857. * if success, else returns NULL. */
  3858. char *
  3859. alloc_http_authenticator(const char *authenticator)
  3860. {
  3861. /* an authenticator in Basic authentication
  3862. * is just the string "username:password" */
  3863. const size_t authenticator_length = strlen(authenticator);
  3864. const size_t base64_authenticator_length =
  3865. base64_encode_size(authenticator_length, 0) + 1;
  3866. char *base64_authenticator = tor_malloc(base64_authenticator_length);
  3867. if (base64_encode(base64_authenticator, base64_authenticator_length,
  3868. authenticator, authenticator_length, 0) < 0) {
  3869. tor_free(base64_authenticator); /* free and set to null */
  3870. }
  3871. return base64_authenticator;
  3872. }
  3873. /** Given a socket handle, check whether the local address (sockname) of the
  3874. * socket is one that we've connected from before. If so, double-check
  3875. * whether our address has changed and we need to generate keys. If we do,
  3876. * call init_keys().
  3877. */
  3878. static void
  3879. client_check_address_changed(tor_socket_t sock)
  3880. {
  3881. struct sockaddr_storage out_sockaddr;
  3882. socklen_t out_addr_len = (socklen_t) sizeof(out_sockaddr);
  3883. tor_addr_t out_addr, iface_addr;
  3884. tor_addr_t **last_interface_ip_ptr;
  3885. sa_family_t family;
  3886. if (!outgoing_addrs)
  3887. outgoing_addrs = smartlist_new();
  3888. if (getsockname(sock, (struct sockaddr*)&out_sockaddr, &out_addr_len)<0) {
  3889. int e = tor_socket_errno(sock);
  3890. log_warn(LD_NET, "getsockname() to check for address change failed: %s",
  3891. tor_socket_strerror(e));
  3892. return;
  3893. }
  3894. tor_addr_from_sockaddr(&out_addr, (struct sockaddr*)&out_sockaddr, NULL);
  3895. family = tor_addr_family(&out_addr);
  3896. if (family == AF_INET)
  3897. last_interface_ip_ptr = &last_interface_ipv4;
  3898. else if (family == AF_INET6)
  3899. last_interface_ip_ptr = &last_interface_ipv6;
  3900. else
  3901. return;
  3902. if (! *last_interface_ip_ptr) {
  3903. tor_addr_t *a = tor_malloc_zero(sizeof(tor_addr_t));
  3904. if (get_interface_address6(LOG_INFO, family, a)==0) {
  3905. *last_interface_ip_ptr = a;
  3906. } else {
  3907. tor_free(a);
  3908. }
  3909. }
  3910. /* If we've used this address previously, we're okay. */
  3911. SMARTLIST_FOREACH(outgoing_addrs, const tor_addr_t *, a_ptr,
  3912. if (tor_addr_eq(a_ptr, &out_addr))
  3913. return;
  3914. );
  3915. /* Uh-oh. We haven't connected from this address before. Has the interface
  3916. * address changed? */
  3917. if (get_interface_address6(LOG_INFO, family, &iface_addr)<0)
  3918. return;
  3919. if (tor_addr_eq(&iface_addr, *last_interface_ip_ptr)) {
  3920. /* Nope, it hasn't changed. Add this address to the list. */
  3921. smartlist_add(outgoing_addrs, tor_memdup(&out_addr, sizeof(tor_addr_t)));
  3922. } else {
  3923. /* The interface changed. We're a client, so we need to regenerate our
  3924. * keys. First, reset the state. */
  3925. log_notice(LD_NET, "Our IP address has changed. Rotating keys...");
  3926. tor_addr_copy(*last_interface_ip_ptr, &iface_addr);
  3927. SMARTLIST_FOREACH(outgoing_addrs, tor_addr_t*, a_ptr, tor_free(a_ptr));
  3928. smartlist_clear(outgoing_addrs);
  3929. smartlist_add(outgoing_addrs, tor_memdup(&out_addr, sizeof(tor_addr_t)));
  3930. /* We'll need to resolve ourselves again. */
  3931. reset_last_resolved_addr();
  3932. /* Okay, now change our keys. */
  3933. ip_address_changed(1);
  3934. }
  3935. }
  3936. /** Some systems have limited system buffers for recv and xmit on
  3937. * sockets allocated in a virtual server or similar environment. For a Tor
  3938. * server this can produce the "Error creating network socket: No buffer
  3939. * space available" error once all available TCP buffer space is consumed.
  3940. * This method will attempt to constrain the buffers allocated for the socket
  3941. * to the desired size to stay below system TCP buffer limits.
  3942. */
  3943. static void
  3944. set_constrained_socket_buffers(tor_socket_t sock, int size)
  3945. {
  3946. void *sz = (void*)&size;
  3947. socklen_t sz_sz = (socklen_t) sizeof(size);
  3948. if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, sz, sz_sz) < 0) {
  3949. int e = tor_socket_errno(sock);
  3950. log_warn(LD_NET, "setsockopt() to constrain send "
  3951. "buffer to %d bytes failed: %s", size, tor_socket_strerror(e));
  3952. }
  3953. if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, sz, sz_sz) < 0) {
  3954. int e = tor_socket_errno(sock);
  3955. log_warn(LD_NET, "setsockopt() to constrain recv "
  3956. "buffer to %d bytes failed: %s", size, tor_socket_strerror(e));
  3957. }
  3958. }
  3959. /** Process new bytes that have arrived on conn-\>inbuf.
  3960. *
  3961. * This function just passes conn to the connection-specific
  3962. * connection_*_process_inbuf() function. It also passes in
  3963. * package_partial if wanted.
  3964. */
  3965. static int
  3966. connection_process_inbuf(connection_t *conn, int package_partial)
  3967. {
  3968. tor_assert(conn);
  3969. switch (conn->type) {
  3970. case CONN_TYPE_OR:
  3971. return connection_or_process_inbuf(TO_OR_CONN(conn));
  3972. case CONN_TYPE_EXT_OR:
  3973. return connection_ext_or_process_inbuf(TO_OR_CONN(conn));
  3974. case CONN_TYPE_EXIT:
  3975. case CONN_TYPE_AP:
  3976. return connection_edge_process_inbuf(TO_EDGE_CONN(conn),
  3977. package_partial);
  3978. case CONN_TYPE_DIR:
  3979. return connection_dir_process_inbuf(TO_DIR_CONN(conn));
  3980. case CONN_TYPE_CONTROL:
  3981. return connection_control_process_inbuf(TO_CONTROL_CONN(conn));
  3982. default:
  3983. log_err(LD_BUG,"got unexpected conn type %d.", conn->type);
  3984. tor_fragile_assert();
  3985. return -1;
  3986. }
  3987. }
  3988. /** Called whenever we've written data on a connection. */
  3989. static int
  3990. connection_flushed_some(connection_t *conn)
  3991. {
  3992. int r = 0;
  3993. tor_assert(!conn->in_flushed_some);
  3994. conn->in_flushed_some = 1;
  3995. if (conn->type == CONN_TYPE_DIR &&
  3996. conn->state == DIR_CONN_STATE_SERVER_WRITING) {
  3997. r = connection_dirserv_flushed_some(TO_DIR_CONN(conn));
  3998. } else if (conn->type == CONN_TYPE_OR) {
  3999. r = connection_or_flushed_some(TO_OR_CONN(conn));
  4000. } else if (CONN_IS_EDGE(conn)) {
  4001. r = connection_edge_flushed_some(TO_EDGE_CONN(conn));
  4002. }
  4003. conn->in_flushed_some = 0;
  4004. return r;
  4005. }
  4006. /** We just finished flushing bytes to the appropriately low network layer,
  4007. * and there are no more bytes remaining in conn-\>outbuf or
  4008. * conn-\>tls to be flushed.
  4009. *
  4010. * This function just passes conn to the connection-specific
  4011. * connection_*_finished_flushing() function.
  4012. */
  4013. static int
  4014. connection_finished_flushing(connection_t *conn)
  4015. {
  4016. tor_assert(conn);
  4017. /* If the connection is closed, don't try to do anything more here. */
  4018. if (CONN_IS_CLOSED(conn))
  4019. return 0;
  4020. // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
  4021. connection_stop_writing(conn);
  4022. switch (conn->type) {
  4023. case CONN_TYPE_OR:
  4024. return connection_or_finished_flushing(TO_OR_CONN(conn));
  4025. case CONN_TYPE_EXT_OR:
  4026. return connection_ext_or_finished_flushing(TO_OR_CONN(conn));
  4027. case CONN_TYPE_AP:
  4028. case CONN_TYPE_EXIT:
  4029. return connection_edge_finished_flushing(TO_EDGE_CONN(conn));
  4030. case CONN_TYPE_DIR:
  4031. return connection_dir_finished_flushing(TO_DIR_CONN(conn));
  4032. case CONN_TYPE_CONTROL:
  4033. return connection_control_finished_flushing(TO_CONTROL_CONN(conn));
  4034. default:
  4035. log_err(LD_BUG,"got unexpected conn type %d.", conn->type);
  4036. tor_fragile_assert();
  4037. return -1;
  4038. }
  4039. }
  4040. /** Called when our attempt to connect() to another server has just
  4041. * succeeded.
  4042. *
  4043. * This function just passes conn to the connection-specific
  4044. * connection_*_finished_connecting() function.
  4045. */
  4046. static int
  4047. connection_finished_connecting(connection_t *conn)
  4048. {
  4049. tor_assert(conn);
  4050. if (!server_mode(get_options())) {
  4051. /* See whether getsockname() says our address changed. We need to do this
  4052. * now that the connection has finished, because getsockname() on Windows
  4053. * won't work until then. */
  4054. client_check_address_changed(conn->s);
  4055. }
  4056. switch (conn->type)
  4057. {
  4058. case CONN_TYPE_OR:
  4059. return connection_or_finished_connecting(TO_OR_CONN(conn));
  4060. case CONN_TYPE_EXIT:
  4061. return connection_edge_finished_connecting(TO_EDGE_CONN(conn));
  4062. case CONN_TYPE_DIR:
  4063. return connection_dir_finished_connecting(TO_DIR_CONN(conn));
  4064. default:
  4065. log_err(LD_BUG,"got unexpected conn type %d.", conn->type);
  4066. tor_fragile_assert();
  4067. return -1;
  4068. }
  4069. }
  4070. /** Callback: invoked when a connection reaches an EOF event. */
  4071. static int
  4072. connection_reached_eof(connection_t *conn)
  4073. {
  4074. switch (conn->type) {
  4075. case CONN_TYPE_OR:
  4076. case CONN_TYPE_EXT_OR:
  4077. return connection_or_reached_eof(TO_OR_CONN(conn));
  4078. case CONN_TYPE_AP:
  4079. case CONN_TYPE_EXIT:
  4080. return connection_edge_reached_eof(TO_EDGE_CONN(conn));
  4081. case CONN_TYPE_DIR:
  4082. return connection_dir_reached_eof(TO_DIR_CONN(conn));
  4083. case CONN_TYPE_CONTROL:
  4084. return connection_control_reached_eof(TO_CONTROL_CONN(conn));
  4085. default:
  4086. log_err(LD_BUG,"got unexpected conn type %d.", conn->type);
  4087. tor_fragile_assert();
  4088. return -1;
  4089. }
  4090. }
  4091. /** Comparator for the two-orconn case in OOS victim sort */
  4092. static int
  4093. oos_victim_comparator_for_orconns(or_connection_t *a, or_connection_t *b)
  4094. {
  4095. int a_circs, b_circs;
  4096. /* Fewer circuits == higher priority for OOS kill, sort earlier */
  4097. a_circs = connection_or_get_num_circuits(a);
  4098. b_circs = connection_or_get_num_circuits(b);
  4099. if (a_circs < b_circs) return 1;
  4100. else if (a_circs > b_circs) return -1;
  4101. else return 0;
  4102. }
  4103. /** Sort comparator for OOS victims; better targets sort before worse
  4104. * ones. */
  4105. static int
  4106. oos_victim_comparator(const void **a_v, const void **b_v)
  4107. {
  4108. connection_t *a = NULL, *b = NULL;
  4109. /* Get connection pointers out */
  4110. a = (connection_t *)(*a_v);
  4111. b = (connection_t *)(*b_v);
  4112. tor_assert(a != NULL);
  4113. tor_assert(b != NULL);
  4114. /*
  4115. * We always prefer orconns as victims currently; we won't even see
  4116. * these non-orconn cases, but if we do, sort them after orconns.
  4117. */
  4118. if (a->type == CONN_TYPE_OR && b->type == CONN_TYPE_OR) {
  4119. return oos_victim_comparator_for_orconns(TO_OR_CONN(a), TO_OR_CONN(b));
  4120. } else {
  4121. /*
  4122. * One isn't an orconn; if one is, it goes first. We currently have no
  4123. * opinions about cases where neither is an orconn.
  4124. */
  4125. if (a->type == CONN_TYPE_OR) return -1;
  4126. else if (b->type == CONN_TYPE_OR) return 1;
  4127. else return 0;
  4128. }
  4129. }
  4130. /** Pick n victim connections for the OOS handler and return them in a
  4131. * smartlist.
  4132. */
  4133. MOCK_IMPL(STATIC smartlist_t *,
  4134. pick_oos_victims, (int n))
  4135. {
  4136. smartlist_t *eligible = NULL, *victims = NULL;
  4137. smartlist_t *conns;
  4138. int conn_counts_by_type[CONN_TYPE_MAX_ + 1], i;
  4139. /*
  4140. * Big damn assumption (someone improve this someday!):
  4141. *
  4142. * Socket exhaustion normally happens on high-volume relays, and so
  4143. * most of the connections involved are orconns. We should pick victims
  4144. * by assembling a list of all orconns, and sorting them in order of
  4145. * how much 'damage' by some metric we'd be doing by dropping them.
  4146. *
  4147. * If we move on from orconns, we should probably think about incoming
  4148. * directory connections next, or exit connections. Things we should
  4149. * probably never kill are controller connections and listeners.
  4150. *
  4151. * This function will count how many connections of different types
  4152. * exist and log it for purposes of gathering data on typical OOS
  4153. * situations to guide future improvements.
  4154. */
  4155. /* First, get the connection array */
  4156. conns = get_connection_array();
  4157. /*
  4158. * Iterate it and pick out eligible connection types, and log some stats
  4159. * along the way.
  4160. */
  4161. eligible = smartlist_new();
  4162. memset(conn_counts_by_type, 0, sizeof(conn_counts_by_type));
  4163. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, c) {
  4164. /* Bump the counter */
  4165. tor_assert(c->type <= CONN_TYPE_MAX_);
  4166. ++(conn_counts_by_type[c->type]);
  4167. /* Skip anything without a socket we can free */
  4168. if (!(SOCKET_OK(c->s))) {
  4169. continue;
  4170. }
  4171. /* Skip anything we would count as moribund */
  4172. if (connection_is_moribund(c)) {
  4173. continue;
  4174. }
  4175. switch (c->type) {
  4176. case CONN_TYPE_OR:
  4177. /* We've got an orconn, it's eligible to be OOSed */
  4178. smartlist_add(eligible, c);
  4179. break;
  4180. default:
  4181. /* We don't know what to do with it, ignore it */
  4182. break;
  4183. }
  4184. } SMARTLIST_FOREACH_END(c);
  4185. /* Log some stats */
  4186. if (smartlist_len(conns) > 0) {
  4187. /* At least one counter must be non-zero */
  4188. log_info(LD_NET, "Some stats on conn types seen during OOS follow");
  4189. for (i = CONN_TYPE_MIN_; i <= CONN_TYPE_MAX_; ++i) {
  4190. /* Did we see any? */
  4191. if (conn_counts_by_type[i] > 0) {
  4192. log_info(LD_NET, "%s: %d conns",
  4193. conn_type_to_string(i),
  4194. conn_counts_by_type[i]);
  4195. }
  4196. }
  4197. log_info(LD_NET, "Done with OOS conn type stats");
  4198. }
  4199. /* Did we find more eligible targets than we want to kill? */
  4200. if (smartlist_len(eligible) > n) {
  4201. /* Sort the list in order of target preference */
  4202. smartlist_sort(eligible, oos_victim_comparator);
  4203. /* Pick first n as victims */
  4204. victims = smartlist_new();
  4205. for (i = 0; i < n; ++i) {
  4206. smartlist_add(victims, smartlist_get(eligible, i));
  4207. }
  4208. /* Free the original list */
  4209. smartlist_free(eligible);
  4210. } else {
  4211. /* No, we can just call them all victims */
  4212. victims = eligible;
  4213. }
  4214. return victims;
  4215. }
  4216. /** Kill a list of connections for the OOS handler. */
  4217. MOCK_IMPL(STATIC void,
  4218. kill_conn_list_for_oos, (smartlist_t *conns))
  4219. {
  4220. if (!conns) return;
  4221. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, c) {
  4222. /* Make sure the channel layer gets told about orconns */
  4223. if (c->type == CONN_TYPE_OR) {
  4224. connection_or_close_for_error(TO_OR_CONN(c), 1);
  4225. } else {
  4226. connection_mark_for_close(c);
  4227. }
  4228. } SMARTLIST_FOREACH_END(c);
  4229. log_notice(LD_NET,
  4230. "OOS handler marked %d connections",
  4231. smartlist_len(conns));
  4232. }
  4233. /** Out-of-Sockets handler; n_socks is the current number of open
  4234. * sockets, and failed is non-zero if a socket exhaustion related
  4235. * error immediately preceded this call. This is where to do
  4236. * circuit-killing heuristics as needed.
  4237. */
  4238. void
  4239. connection_check_oos(int n_socks, int failed)
  4240. {
  4241. int target_n_socks = 0, moribund_socks, socks_to_kill;
  4242. smartlist_t *conns;
  4243. /* Early exit: is OOS checking disabled? */
  4244. if (get_options()->DisableOOSCheck) {
  4245. return;
  4246. }
  4247. /* Sanity-check args */
  4248. tor_assert(n_socks >= 0);
  4249. /*
  4250. * Make some log noise; keep it at debug level since this gets a chance
  4251. * to run on every connection attempt.
  4252. */
  4253. log_debug(LD_NET,
  4254. "Running the OOS handler (%d open sockets, %s)",
  4255. n_socks, (failed != 0) ? "exhaustion seen" : "no exhaustion");
  4256. /*
  4257. * Check if we're really handling an OOS condition, and if so decide how
  4258. * many sockets we want to get down to. Be sure we check if the threshold
  4259. * is distinct from zero first; it's possible for this to be called a few
  4260. * times before we've finished reading the config.
  4261. */
  4262. if (n_socks >= get_options()->ConnLimit_high_thresh &&
  4263. get_options()->ConnLimit_high_thresh != 0 &&
  4264. get_options()->ConnLimit_ != 0) {
  4265. /* Try to get down to the low threshold */
  4266. target_n_socks = get_options()->ConnLimit_low_thresh;
  4267. log_notice(LD_NET,
  4268. "Current number of sockets %d is greater than configured "
  4269. "limit %d; OOS handler trying to get down to %d",
  4270. n_socks, get_options()->ConnLimit_high_thresh,
  4271. target_n_socks);
  4272. } else if (failed) {
  4273. /*
  4274. * If we're not at the limit but we hit a socket exhaustion error, try to
  4275. * drop some (but not as aggressively as ConnLimit_low_threshold, which is
  4276. * 3/4 of ConnLimit_)
  4277. */
  4278. target_n_socks = (n_socks * 9) / 10;
  4279. log_notice(LD_NET,
  4280. "We saw socket exhaustion at %d open sockets; OOS handler "
  4281. "trying to get down to %d",
  4282. n_socks, target_n_socks);
  4283. }
  4284. if (target_n_socks > 0) {
  4285. /*
  4286. * It's an OOS!
  4287. *
  4288. * Count moribund sockets; it's be important that anything we decide
  4289. * to get rid of here but don't immediately close get counted as moribund
  4290. * on subsequent invocations so we don't try to kill too many things if
  4291. * connection_check_oos() gets called multiple times.
  4292. */
  4293. moribund_socks = connection_count_moribund();
  4294. if (moribund_socks < n_socks - target_n_socks) {
  4295. socks_to_kill = n_socks - target_n_socks - moribund_socks;
  4296. conns = pick_oos_victims(socks_to_kill);
  4297. if (conns) {
  4298. kill_conn_list_for_oos(conns);
  4299. log_notice(LD_NET,
  4300. "OOS handler killed %d conns", smartlist_len(conns));
  4301. smartlist_free(conns);
  4302. } else {
  4303. log_notice(LD_NET, "OOS handler failed to pick any victim conns");
  4304. }
  4305. } else {
  4306. log_notice(LD_NET,
  4307. "Not killing any sockets for OOS because there are %d "
  4308. "already moribund, and we only want to eliminate %d",
  4309. moribund_socks, n_socks - target_n_socks);
  4310. }
  4311. }
  4312. }
  4313. /** Log how many bytes are used by buffers of different kinds and sizes. */
  4314. void
  4315. connection_dump_buffer_mem_stats(int severity)
  4316. {
  4317. uint64_t used_by_type[CONN_TYPE_MAX_+1];
  4318. uint64_t alloc_by_type[CONN_TYPE_MAX_+1];
  4319. int n_conns_by_type[CONN_TYPE_MAX_+1];
  4320. uint64_t total_alloc = 0;
  4321. uint64_t total_used = 0;
  4322. int i;
  4323. smartlist_t *conns = get_connection_array();
  4324. memset(used_by_type, 0, sizeof(used_by_type));
  4325. memset(alloc_by_type, 0, sizeof(alloc_by_type));
  4326. memset(n_conns_by_type, 0, sizeof(n_conns_by_type));
  4327. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, c) {
  4328. int tp = c->type;
  4329. ++n_conns_by_type[tp];
  4330. if (c->inbuf) {
  4331. used_by_type[tp] += buf_datalen(c->inbuf);
  4332. alloc_by_type[tp] += buf_allocation(c->inbuf);
  4333. }
  4334. if (c->outbuf) {
  4335. used_by_type[tp] += buf_datalen(c->outbuf);
  4336. alloc_by_type[tp] += buf_allocation(c->outbuf);
  4337. }
  4338. } SMARTLIST_FOREACH_END(c);
  4339. for (i=0; i <= CONN_TYPE_MAX_; ++i) {
  4340. total_used += used_by_type[i];
  4341. total_alloc += alloc_by_type[i];
  4342. }
  4343. tor_log(severity, LD_GENERAL,
  4344. "In buffers for %d connections: "U64_FORMAT" used/"U64_FORMAT" allocated",
  4345. smartlist_len(conns),
  4346. U64_PRINTF_ARG(total_used), U64_PRINTF_ARG(total_alloc));
  4347. for (i=CONN_TYPE_MIN_; i <= CONN_TYPE_MAX_; ++i) {
  4348. if (!n_conns_by_type[i])
  4349. continue;
  4350. tor_log(severity, LD_GENERAL,
  4351. " For %d %s connections: "U64_FORMAT" used/"U64_FORMAT" allocated",
  4352. n_conns_by_type[i], conn_type_to_string(i),
  4353. U64_PRINTF_ARG(used_by_type[i]), U64_PRINTF_ARG(alloc_by_type[i]));
  4354. }
  4355. }
  4356. /** Verify that connection <b>conn</b> has all of its invariants
  4357. * correct. Trigger an assert if anything is invalid.
  4358. */
  4359. void
  4360. assert_connection_ok(connection_t *conn, time_t now)
  4361. {
  4362. (void) now; /* XXXX unused. */
  4363. tor_assert(conn);
  4364. tor_assert(conn->type >= CONN_TYPE_MIN_);
  4365. tor_assert(conn->type <= CONN_TYPE_MAX_);
  4366. switch (conn->type) {
  4367. case CONN_TYPE_OR:
  4368. case CONN_TYPE_EXT_OR:
  4369. tor_assert(conn->magic == OR_CONNECTION_MAGIC);
  4370. break;
  4371. case CONN_TYPE_AP:
  4372. tor_assert(conn->magic == ENTRY_CONNECTION_MAGIC);
  4373. break;
  4374. case CONN_TYPE_EXIT:
  4375. tor_assert(conn->magic == EDGE_CONNECTION_MAGIC);
  4376. break;
  4377. case CONN_TYPE_DIR:
  4378. tor_assert(conn->magic == DIR_CONNECTION_MAGIC);
  4379. break;
  4380. case CONN_TYPE_CONTROL:
  4381. tor_assert(conn->magic == CONTROL_CONNECTION_MAGIC);
  4382. break;
  4383. CASE_ANY_LISTENER_TYPE:
  4384. tor_assert(conn->magic == LISTENER_CONNECTION_MAGIC);
  4385. break;
  4386. default:
  4387. tor_assert(conn->magic == BASE_CONNECTION_MAGIC);
  4388. break;
  4389. }
  4390. if (conn->linked_conn) {
  4391. tor_assert(conn->linked_conn->linked_conn == conn);
  4392. tor_assert(conn->linked);
  4393. }
  4394. if (conn->linked)
  4395. tor_assert(!SOCKET_OK(conn->s));
  4396. if (conn->outbuf_flushlen > 0) {
  4397. /* With optimistic data, we may have queued data in
  4398. * EXIT_CONN_STATE_RESOLVING while the conn is not yet marked to writing.
  4399. * */
  4400. tor_assert((conn->type == CONN_TYPE_EXIT &&
  4401. conn->state == EXIT_CONN_STATE_RESOLVING) ||
  4402. connection_is_writing(conn) ||
  4403. conn->write_blocked_on_bw ||
  4404. (CONN_IS_EDGE(conn) &&
  4405. TO_EDGE_CONN(conn)->edge_blocked_on_circ));
  4406. }
  4407. if (conn->hold_open_until_flushed)
  4408. tor_assert(conn->marked_for_close);
  4409. /* XXXX check: read_blocked_on_bw, write_blocked_on_bw, s, conn_array_index,
  4410. * marked_for_close. */
  4411. /* buffers */
  4412. if (conn->inbuf)
  4413. assert_buf_ok(conn->inbuf);
  4414. if (conn->outbuf)
  4415. assert_buf_ok(conn->outbuf);
  4416. if (conn->type == CONN_TYPE_OR) {
  4417. or_connection_t *or_conn = TO_OR_CONN(conn);
  4418. if (conn->state == OR_CONN_STATE_OPEN) {
  4419. /* tor_assert(conn->bandwidth > 0); */
  4420. /* the above isn't necessarily true: if we just did a TLS
  4421. * handshake but we didn't recognize the other peer, or it
  4422. * gave a bad cert/etc, then we won't have assigned bandwidth,
  4423. * yet it will be open. -RD
  4424. */
  4425. // tor_assert(conn->read_bucket >= 0);
  4426. }
  4427. // tor_assert(conn->addr && conn->port);
  4428. tor_assert(conn->address);
  4429. if (conn->state > OR_CONN_STATE_PROXY_HANDSHAKING)
  4430. tor_assert(or_conn->tls);
  4431. }
  4432. if (CONN_IS_EDGE(conn)) {
  4433. /* XXX unchecked: package window, deliver window. */
  4434. if (conn->type == CONN_TYPE_AP) {
  4435. entry_connection_t *entry_conn = TO_ENTRY_CONN(conn);
  4436. if (entry_conn->chosen_exit_optional || entry_conn->chosen_exit_retries)
  4437. tor_assert(entry_conn->chosen_exit_name);
  4438. tor_assert(entry_conn->socks_request);
  4439. if (conn->state == AP_CONN_STATE_OPEN) {
  4440. tor_assert(entry_conn->socks_request->has_finished);
  4441. if (!conn->marked_for_close) {
  4442. tor_assert(ENTRY_TO_EDGE_CONN(entry_conn)->cpath_layer);
  4443. assert_cpath_layer_ok(ENTRY_TO_EDGE_CONN(entry_conn)->cpath_layer);
  4444. }
  4445. }
  4446. }
  4447. if (conn->type == CONN_TYPE_EXIT) {
  4448. tor_assert(conn->purpose == EXIT_PURPOSE_CONNECT ||
  4449. conn->purpose == EXIT_PURPOSE_RESOLVE);
  4450. }
  4451. } else if (conn->type == CONN_TYPE_DIR) {
  4452. } else {
  4453. /* Purpose is only used for dir and exit types currently */
  4454. tor_assert(!conn->purpose);
  4455. }
  4456. switch (conn->type)
  4457. {
  4458. CASE_ANY_LISTENER_TYPE:
  4459. tor_assert(conn->state == LISTENER_STATE_READY);
  4460. break;
  4461. case CONN_TYPE_OR:
  4462. tor_assert(conn->state >= OR_CONN_STATE_MIN_);
  4463. tor_assert(conn->state <= OR_CONN_STATE_MAX_);
  4464. break;
  4465. case CONN_TYPE_EXT_OR:
  4466. tor_assert(conn->state >= EXT_OR_CONN_STATE_MIN_);
  4467. tor_assert(conn->state <= EXT_OR_CONN_STATE_MAX_);
  4468. break;
  4469. case CONN_TYPE_EXIT:
  4470. tor_assert(conn->state >= EXIT_CONN_STATE_MIN_);
  4471. tor_assert(conn->state <= EXIT_CONN_STATE_MAX_);
  4472. tor_assert(conn->purpose >= EXIT_PURPOSE_MIN_);
  4473. tor_assert(conn->purpose <= EXIT_PURPOSE_MAX_);
  4474. break;
  4475. case CONN_TYPE_AP:
  4476. tor_assert(conn->state >= AP_CONN_STATE_MIN_);
  4477. tor_assert(conn->state <= AP_CONN_STATE_MAX_);
  4478. tor_assert(TO_ENTRY_CONN(conn)->socks_request);
  4479. break;
  4480. case CONN_TYPE_DIR:
  4481. tor_assert(conn->state >= DIR_CONN_STATE_MIN_);
  4482. tor_assert(conn->state <= DIR_CONN_STATE_MAX_);
  4483. tor_assert(conn->purpose >= DIR_PURPOSE_MIN_);
  4484. tor_assert(conn->purpose <= DIR_PURPOSE_MAX_);
  4485. break;
  4486. case CONN_TYPE_CONTROL:
  4487. tor_assert(conn->state >= CONTROL_CONN_STATE_MIN_);
  4488. tor_assert(conn->state <= CONTROL_CONN_STATE_MAX_);
  4489. break;
  4490. default:
  4491. tor_assert(0);
  4492. }
  4493. }
  4494. /** Fills <b>addr</b> and <b>port</b> with the details of the global
  4495. * proxy server we are using.
  4496. * <b>conn</b> contains the connection we are using the proxy for.
  4497. *
  4498. * Return 0 on success, -1 on failure.
  4499. */
  4500. int
  4501. get_proxy_addrport(tor_addr_t *addr, uint16_t *port, int *proxy_type,
  4502. const connection_t *conn)
  4503. {
  4504. const or_options_t *options = get_options();
  4505. /* Client Transport Plugins can use another proxy, but that should be hidden
  4506. * from the rest of tor (as the plugin is responsible for dealing with the
  4507. * proxy), check it first, then check the rest of the proxy types to allow
  4508. * the config to have unused ClientTransportPlugin entries.
  4509. */
  4510. if (options->ClientTransportPlugin) {
  4511. const transport_t *transport = NULL;
  4512. int r;
  4513. r = get_transport_by_bridge_addrport(&conn->addr, conn->port, &transport);
  4514. if (r<0)
  4515. return -1;
  4516. if (transport) { /* transport found */
  4517. tor_addr_copy(addr, &transport->addr);
  4518. *port = transport->port;
  4519. *proxy_type = transport->socks_version;
  4520. return 0;
  4521. }
  4522. /* Unused ClientTransportPlugin. */
  4523. }
  4524. if (options->HTTPSProxy) {
  4525. tor_addr_copy(addr, &options->HTTPSProxyAddr);
  4526. *port = options->HTTPSProxyPort;
  4527. *proxy_type = PROXY_CONNECT;
  4528. return 0;
  4529. } else if (options->Socks4Proxy) {
  4530. tor_addr_copy(addr, &options->Socks4ProxyAddr);
  4531. *port = options->Socks4ProxyPort;
  4532. *proxy_type = PROXY_SOCKS4;
  4533. return 0;
  4534. } else if (options->Socks5Proxy) {
  4535. tor_addr_copy(addr, &options->Socks5ProxyAddr);
  4536. *port = options->Socks5ProxyPort;
  4537. *proxy_type = PROXY_SOCKS5;
  4538. return 0;
  4539. }
  4540. tor_addr_make_unspec(addr);
  4541. *port = 0;
  4542. *proxy_type = PROXY_NONE;
  4543. return 0;
  4544. }
  4545. /** Log a failed connection to a proxy server.
  4546. * <b>conn</b> is the connection we use the proxy server for. */
  4547. void
  4548. log_failed_proxy_connection(connection_t *conn)
  4549. {
  4550. tor_addr_t proxy_addr;
  4551. uint16_t proxy_port;
  4552. int proxy_type;
  4553. if (get_proxy_addrport(&proxy_addr, &proxy_port, &proxy_type, conn) != 0)
  4554. return; /* if we have no proxy set up, leave this function. */
  4555. log_warn(LD_NET,
  4556. "The connection to the %s proxy server at %s just failed. "
  4557. "Make sure that the proxy server is up and running.",
  4558. proxy_type_to_string(proxy_type),
  4559. fmt_addrport(&proxy_addr, proxy_port));
  4560. }
  4561. /** Return string representation of <b>proxy_type</b>. */
  4562. static const char *
  4563. proxy_type_to_string(int proxy_type)
  4564. {
  4565. switch (proxy_type) {
  4566. case PROXY_CONNECT: return "HTTP";
  4567. case PROXY_SOCKS4: return "SOCKS4";
  4568. case PROXY_SOCKS5: return "SOCKS5";
  4569. case PROXY_PLUGGABLE: return "pluggable transports SOCKS";
  4570. case PROXY_NONE: return "NULL";
  4571. default: tor_assert(0);
  4572. }
  4573. return NULL; /*Unreached*/
  4574. }
  4575. /** Call connection_free_() on every connection in our array, and release all
  4576. * storage held by connection.c.
  4577. *
  4578. * Don't do the checks in connection_free(), because they will
  4579. * fail.
  4580. */
  4581. void
  4582. connection_free_all(void)
  4583. {
  4584. smartlist_t *conns = get_connection_array();
  4585. /* We don't want to log any messages to controllers. */
  4586. SMARTLIST_FOREACH(conns, connection_t *, conn,
  4587. if (conn->type == CONN_TYPE_CONTROL)
  4588. TO_CONTROL_CONN(conn)->event_mask = 0);
  4589. control_update_global_event_mask();
  4590. /* Unlink everything from the identity map. */
  4591. connection_or_clear_identity_map();
  4592. connection_or_clear_ext_or_id_map();
  4593. /* Clear out our list of broken connections */
  4594. clear_broken_connection_map(0);
  4595. SMARTLIST_FOREACH(conns, connection_t *, conn, connection_free_(conn));
  4596. if (outgoing_addrs) {
  4597. SMARTLIST_FOREACH(outgoing_addrs, tor_addr_t *, addr, tor_free(addr));
  4598. smartlist_free(outgoing_addrs);
  4599. outgoing_addrs = NULL;
  4600. }
  4601. tor_free(last_interface_ipv4);
  4602. tor_free(last_interface_ipv6);
  4603. }
  4604. /** Log a warning, and possibly emit a control event, that <b>received</b> came
  4605. * at a skewed time. <b>trusted</b> indicates that the <b>source</b> was one
  4606. * that we had more faith in and therefore the warning level should have higher
  4607. * severity.
  4608. */
  4609. void
  4610. clock_skew_warning(const connection_t *conn, long apparent_skew, int trusted,
  4611. log_domain_mask_t domain, const char *received,
  4612. const char *source)
  4613. {
  4614. char dbuf[64];
  4615. char *ext_source = NULL;
  4616. format_time_interval(dbuf, sizeof(dbuf), apparent_skew);
  4617. if (conn)
  4618. tor_asprintf(&ext_source, "%s:%s:%d", source, conn->address, conn->port);
  4619. else
  4620. ext_source = tor_strdup(source);
  4621. log_fn(trusted ? LOG_WARN : LOG_INFO, domain,
  4622. "Received %s with skewed time (%s): "
  4623. "It seems that our clock is %s by %s, or that theirs is %s%s. "
  4624. "Tor requires an accurate clock to work: please check your time, "
  4625. "timezone, and date settings.", received, ext_source,
  4626. apparent_skew > 0 ? "ahead" : "behind", dbuf,
  4627. apparent_skew > 0 ? "behind" : "ahead",
  4628. (!conn || trusted) ? "" : ", or they are sending us the wrong time");
  4629. if (trusted)
  4630. control_event_general_status(LOG_WARN, "CLOCK_SKEW SKEW=%ld SOURCE=%s",
  4631. apparent_skew, ext_source);
  4632. tor_free(ext_source);
  4633. }