connection.c 175 KB

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