connection.c 104 KB

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