connection.c 162 KB

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