connection.c 100 KB

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