connection.c 116 KB

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