connection.c 145 KB

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