connection.c 167 KB

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