connection.c 166 KB

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