connection.c 134 KB

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