connection.c 116 KB

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