connection.c 172 KB

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