connection.c 115 KB

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