connection.c 175 KB

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