connection.c 103 KB

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