connection.c 172 KB

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