connection.c 172 KB

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