connection.c 100 KB

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