connection.c 176 KB

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