connection.c 172 KB

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