connection.c 152 KB

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