connection.c 94 KB

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