connection.c 148 KB

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