connection.c 162 KB

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