connection.c 104 KB

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