connection.c 97 KB

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