connection.c 140 KB

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