connection.c 167 KB

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