connection.c 102 KB

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