connection.c 137 KB

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