connection.c 121 KB

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