connection.c 102 KB

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