connection.c 165 KB

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