connection.c 141 KB

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