connection.c 102 KB

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