connection.c 152 KB

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