connection.c 145 KB

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