connection.c 153 KB

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