connection.c 103 KB

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