connection.c 165 KB

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