connection.c 98 KB

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