connection.c 95 KB

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