connection.c 135 KB

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