connection.c 140 KB

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