connection.c 115 KB

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