connection.c 158 KB

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