connection.c 137 KB

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