connection.c 114 KB

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