connection.c 177 KB

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