connection.c 103 KB

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