connection.c 137 KB

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