connection.c 115 KB

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