connection.c 98 KB

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