connection.c 133 KB

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