connection.c 130 KB

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