connection.c 144 KB

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