connection.c 103 KB

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