connection.c 143 KB

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