connection.c 177 KB

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