connection.c 165 KB

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