connection.c 175 KB

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