connection.c 172 KB

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