connection.c 139 KB

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