connection.c 97 KB

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