connection.c 141 KB

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