connection.c 96 KB

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