connection.c 139 KB

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