connection.c 104 KB

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