connection.c 166 KB

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