connection.c 101 KB

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