connection.c 116 KB

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