connection.c 134 KB

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