connection.c 116 KB

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