connection.c 135 KB

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