connection.c 137 KB

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