connection.c 164 KB

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