connection.c 141 KB

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