connection.c 97 KB

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