connection.c 115 KB

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