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