connection.c 134 KB

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