connection.c 137 KB

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