connection.c 97 KB

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