connection.c 116 KB

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