connection.c 167 KB

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