connection.c 135 KB

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