connection.c 163 KB

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