connection.c 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, 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(const char *listenaddress,
  15. uint16_t listenport, int type);
  16. static int connection_init_accepted_conn(connection_t *conn);
  17. static int connection_handle_listener_read(connection_t *conn, int new_type);
  18. static int connection_receiver_bucket_should_increase(connection_t *conn);
  19. static int connection_finished_flushing(connection_t *conn);
  20. static int connection_finished_connecting(connection_t *conn);
  21. static int connection_reached_eof(connection_t *conn);
  22. static int connection_read_to_buf(connection_t *conn, int *max_to_read);
  23. static int connection_process_inbuf(connection_t *conn, int package_partial);
  24. static void client_check_address_changed(int sock);
  25. static uint32_t last_interface_ip = 0;
  26. static smartlist_t *outgoing_addrs = NULL;
  27. /**************************************************************/
  28. /**
  29. * Return the human-readable name for the connection type <b>type</b>
  30. */
  31. const char *
  32. conn_type_to_string(int type)
  33. {
  34. static char buf[64];
  35. switch (type) {
  36. case CONN_TYPE_OR_LISTENER: return "OR listener";
  37. case CONN_TYPE_OR: return "OR";
  38. case CONN_TYPE_EXIT: return "Exit";
  39. case CONN_TYPE_AP_LISTENER: return "Socks listener";
  40. case CONN_TYPE_AP: return "Socks";
  41. case CONN_TYPE_DIR_LISTENER: return "Directory listener";
  42. case CONN_TYPE_DIR: return "Directory";
  43. case CONN_TYPE_DNSWORKER: return "DNS worker";
  44. case CONN_TYPE_CPUWORKER: return "CPU worker";
  45. case CONN_TYPE_CONTROL_LISTENER: return "Control listener";
  46. case CONN_TYPE_CONTROL: return "Control";
  47. default:
  48. log_warn(LD_BUG, "Bug: unknown connection type %d", type);
  49. tor_snprintf(buf, sizeof(buf), "unknown [%d]", type);
  50. return buf;
  51. }
  52. }
  53. /**
  54. * Return the human-readable name for the connection state <b>state</b>
  55. * for the connection type <b>type</b>
  56. */
  57. const char *
  58. conn_state_to_string(int type, int state)
  59. {
  60. static char buf[96];
  61. switch (type) {
  62. case CONN_TYPE_OR_LISTENER:
  63. case CONN_TYPE_AP_LISTENER:
  64. case CONN_TYPE_DIR_LISTENER:
  65. case CONN_TYPE_CONTROL_LISTENER:
  66. if (state == LISTENER_STATE_READY)
  67. return "ready";
  68. break;
  69. case CONN_TYPE_OR:
  70. switch (state) {
  71. case OR_CONN_STATE_CONNECTING: return "connect()ing";
  72. case OR_CONN_STATE_PROXY_FLUSHING: return "proxy flushing";
  73. case OR_CONN_STATE_PROXY_READING: return "proxy reading";
  74. case OR_CONN_STATE_HANDSHAKING: return "handshaking";
  75. case OR_CONN_STATE_OPEN: return "open";
  76. }
  77. break;
  78. case CONN_TYPE_EXIT:
  79. switch (state) {
  80. case EXIT_CONN_STATE_RESOLVING: return "waiting for dest info";
  81. case EXIT_CONN_STATE_CONNECTING: return "connecting";
  82. case EXIT_CONN_STATE_OPEN: return "open";
  83. case EXIT_CONN_STATE_RESOLVEFAILED: return "resolve failed";
  84. }
  85. break;
  86. case CONN_TYPE_AP:
  87. switch (state) {
  88. case AP_CONN_STATE_SOCKS_WAIT: return "waiting for dest info";
  89. case AP_CONN_STATE_RENDDESC_WAIT: return "waiting for rendezvous desc";
  90. case AP_CONN_STATE_CONTROLLER_WAIT: return "waiting for controller";
  91. case AP_CONN_STATE_CIRCUIT_WAIT: return "waiting for safe circuit";
  92. case AP_CONN_STATE_CONNECT_WAIT: return "waiting for connect";
  93. case AP_CONN_STATE_RESOLVE_WAIT: return "waiting for resolve";
  94. case AP_CONN_STATE_OPEN: return "open";
  95. }
  96. break;
  97. case CONN_TYPE_DIR:
  98. switch (state) {
  99. case DIR_CONN_STATE_CONNECTING: return "connecting";
  100. case DIR_CONN_STATE_CLIENT_SENDING: return "client sending";
  101. case DIR_CONN_STATE_CLIENT_READING: return "client reading";
  102. case DIR_CONN_STATE_SERVER_COMMAND_WAIT: return "waiting for command";
  103. case DIR_CONN_STATE_SERVER_WRITING: return "writing";
  104. }
  105. break;
  106. case CONN_TYPE_DNSWORKER:
  107. switch (state) {
  108. case DNSWORKER_STATE_IDLE: return "idle";
  109. case DNSWORKER_STATE_BUSY: return "busy";
  110. }
  111. break;
  112. case CONN_TYPE_CPUWORKER:
  113. switch (state) {
  114. case CPUWORKER_STATE_IDLE: return "idle";
  115. case CPUWORKER_STATE_BUSY_ONION: return "busy with onion";
  116. }
  117. break;
  118. case CONN_TYPE_CONTROL:
  119. switch (state) {
  120. case CONTROL_CONN_STATE_OPEN_V0: return "open (protocol v0)";
  121. case CONTROL_CONN_STATE_OPEN_V1: return "open (protocol v1)";
  122. case CONTROL_CONN_STATE_NEEDAUTH_V0:
  123. return "waiting for authentication (protocol unknown)";
  124. case CONTROL_CONN_STATE_NEEDAUTH_V1:
  125. return "waiting for authentication (protocol v1)";
  126. }
  127. break;
  128. }
  129. log_warn(LD_BUG, "Bug: unknown connection state %d (type %d)", state, type);
  130. tor_snprintf(buf, sizeof(buf),
  131. "unknown state [%d] on unknown [%s] connection",
  132. state, conn_type_to_string(type));
  133. return buf;
  134. }
  135. /** Allocate space for a new connection_t. This function just initializes
  136. * conn; you must call connection_add() to link it into the main array.
  137. *
  138. * Set conn-\>type to <b>type</b>. Set conn-\>s and conn-\>poll_index to
  139. * -1 to signify they are not yet assigned.
  140. *
  141. * If conn is not a listener type, allocate buffers for it. If it's
  142. * an AP type, allocate space to store the socks_request.
  143. *
  144. * Assign a pseudorandom next_circ_id between 0 and 2**15.
  145. *
  146. * Initialize conn's timestamps to now.
  147. */
  148. connection_t *
  149. connection_new(int type)
  150. {
  151. static uint32_t n_connections_allocated = 0;
  152. connection_t *conn;
  153. time_t now = time(NULL);
  154. conn = tor_malloc_zero(sizeof(connection_t));
  155. conn->magic = CONNECTION_MAGIC;
  156. conn->s = -1; /* give it a default of 'not used' */
  157. conn->poll_index = -1; /* also default to 'not used' */
  158. conn->global_identifier = n_connections_allocated++;
  159. conn->type = type;
  160. if (!connection_is_listener(conn)) { /* listeners never use their buf */
  161. conn->inbuf = buf_new();
  162. conn->outbuf = buf_new();
  163. }
  164. if (type == CONN_TYPE_AP) {
  165. conn->socks_request = tor_malloc_zero(sizeof(socks_request_t));
  166. }
  167. conn->next_circ_id = crypto_rand_int(1<<15);
  168. conn->timestamp_created = now;
  169. conn->timestamp_lastread = now;
  170. conn->timestamp_lastwritten = now;
  171. return conn;
  172. }
  173. /** Tell libevent that we don't care about <b>conn</b> any more. */
  174. void
  175. connection_unregister(connection_t *conn)
  176. {
  177. if (conn->read_event) {
  178. if (event_del(conn->read_event))
  179. log_warn(LD_BUG, "Error removing read event for %d", conn->s);
  180. tor_free(conn->read_event);
  181. }
  182. if (conn->write_event) {
  183. if (event_del(conn->write_event))
  184. log_warn(LD_BUG, "Error removing write event for %d", conn->s);
  185. tor_free(conn->write_event);
  186. }
  187. }
  188. /** Deallocate memory used by <b>conn</b>. Deallocate its buffers if
  189. * necessary, close its socket if necessary, and mark the directory as dirty
  190. * if <b>conn</b> is an OR or OP connection.
  191. */
  192. static void
  193. _connection_free(connection_t *conn)
  194. {
  195. tor_assert(conn->magic == CONNECTION_MAGIC);
  196. if (!connection_is_listener(conn)) {
  197. buf_free(conn->inbuf);
  198. buf_free(conn->outbuf);
  199. }
  200. tor_free(conn->address);
  201. tor_free(conn->chosen_exit_name);
  202. if (connection_speaks_cells(conn)) {
  203. if (conn->tls) {
  204. tor_tls_free(conn->tls);
  205. conn->tls = NULL;
  206. }
  207. }
  208. if (conn->identity_pkey)
  209. crypto_free_pk_env(conn->identity_pkey);
  210. tor_free(conn->nickname);
  211. tor_free(conn->socks_request);
  212. tor_free(conn->incoming_cmd);
  213. tor_free(conn->read_event); /* Probably already freed by connection_free. */
  214. tor_free(conn->write_event); /* Probably already freed by connection_free. */
  215. tor_free(conn->requested_resource);
  216. if (conn->s >= 0) {
  217. log_debug(LD_NET,"closing fd %d.",conn->s);
  218. tor_close_socket(conn->s);
  219. }
  220. if (conn->type == CONN_TYPE_OR &&
  221. !tor_digest_is_zero(conn->identity_digest)) {
  222. log_warn(LD_BUG, "called on OR conn with non-zeroed identity_digest");
  223. connection_or_remove_from_identity_map(conn);
  224. }
  225. memset(conn, 0xAA, sizeof(connection_t)); /* poison memory */
  226. tor_free(conn);
  227. }
  228. /** Make sure <b>conn</b> isn't in any of the global conn lists; then free it.
  229. */
  230. void
  231. connection_free(connection_t *conn)
  232. {
  233. tor_assert(conn);
  234. tor_assert(!connection_is_on_closeable_list(conn));
  235. tor_assert(!connection_in_array(conn));
  236. if (connection_speaks_cells(conn)) {
  237. if (conn->state == OR_CONN_STATE_OPEN)
  238. directory_set_dirty();
  239. if (!tor_digest_is_zero(conn->identity_digest)) {
  240. connection_or_remove_from_identity_map(conn);
  241. }
  242. }
  243. if (conn->type == CONN_TYPE_CONTROL) {
  244. conn->event_mask = 0;
  245. control_update_global_event_mask();
  246. }
  247. connection_unregister(conn);
  248. _connection_free(conn);
  249. }
  250. /** Call _connection_free() on every connection in our array, and release all
  251. * storage helpd by connection.c. This is used by cpuworkers and dnsworkers
  252. * when they fork, so they don't keep resources held open (especially
  253. * sockets).
  254. *
  255. * Don't do the checks in connection_free(), because they will
  256. * fail.
  257. */
  258. void
  259. connection_free_all(void)
  260. {
  261. int i, n;
  262. connection_t **carray;
  263. get_connection_array(&carray,&n);
  264. /* We don't want to log any messages to controllers. */
  265. for (i=0;i<n;i++)
  266. if (carray[i]->type == CONN_TYPE_CONTROL)
  267. carray[i]->event_mask = 0;
  268. control_update_global_event_mask();
  269. /* Unlink everything from the identity map. */
  270. connection_or_clear_identity_map();
  271. for (i=0;i<n;i++)
  272. _connection_free(carray[i]);
  273. if (outgoing_addrs) {
  274. SMARTLIST_FOREACH(outgoing_addrs, void*, addr, tor_free(addr));
  275. smartlist_free(outgoing_addrs);
  276. outgoing_addrs = NULL;
  277. }
  278. }
  279. /** Do any cleanup needed:
  280. * - Directory conns that failed to fetch a rendezvous descriptor
  281. * need to inform pending rendezvous streams.
  282. * - OR conns need to call rep_hist_note_*() to record status.
  283. * - AP conns need to send a socks reject if necessary.
  284. * - Exit conns need to call connection_dns_remove() if necessary.
  285. * - AP and Exit conns need to send an end cell if they can.
  286. * - DNS conns need to fail any resolves that are pending on them.
  287. */
  288. void
  289. connection_about_to_close_connection(connection_t *conn)
  290. {
  291. circuit_t *circ;
  292. assert(conn->marked_for_close);
  293. if (CONN_IS_EDGE(conn)) {
  294. if (!conn->has_sent_end) {
  295. log_warn(LD_BUG, "Harmless bug: Edge connection (marked at %s:%d) "
  296. "hasn't sent end yet?",
  297. conn->marked_for_close_file, conn->marked_for_close);
  298. tor_fragile_assert();
  299. }
  300. }
  301. switch (conn->type) {
  302. case CONN_TYPE_DIR:
  303. if (conn->state < DIR_CONN_STATE_CLIENT_FINISHED) {
  304. /* It's a directory connection and connecting or fetching
  305. * failed: forget about this router, and maybe try again. */
  306. connection_dir_request_failed(conn);
  307. // XXX if it's rend desc we may want to retry -RD
  308. }
  309. if (conn->purpose == DIR_PURPOSE_FETCH_RENDDESC)
  310. rend_client_desc_here(conn->rend_query); /* give it a try */
  311. break;
  312. case CONN_TYPE_OR:
  313. /* Remember why we're closing this connection. */
  314. if (conn->state != OR_CONN_STATE_OPEN) {
  315. if (connection_or_nonopen_was_started_here(conn)) {
  316. rep_hist_note_connect_failed(conn->identity_digest, time(NULL));
  317. entry_guard_set_status(conn->identity_digest, 0);
  318. router_set_status(conn->identity_digest, 0);
  319. control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED);
  320. }
  321. } else if (conn->hold_open_until_flushed) {
  322. /* XXXX009 We used to have an arg that told us whether we closed the
  323. * connection on purpose or not. Can we use hold_open_until_flushed
  324. * instead? We only set it when we are intentionally closing a
  325. * connection. -NM
  326. *
  327. * (Of course, now things we set to close which expire rather than
  328. * flushing still get noted as dead, not disconnected. But this is an
  329. * improvement. -NM
  330. */
  331. rep_hist_note_disconnect(conn->identity_digest, time(NULL));
  332. control_event_or_conn_status(conn, OR_CONN_EVENT_CLOSED);
  333. } else if (conn->identity_digest) {
  334. rep_hist_note_connection_died(conn->identity_digest, time(NULL));
  335. control_event_or_conn_status(conn, OR_CONN_EVENT_CLOSED);
  336. }
  337. break;
  338. case CONN_TYPE_AP:
  339. if (conn->socks_request->has_finished == 0) {
  340. /* since conn gets removed right after this function finishes,
  341. * there's no point trying to send back a reply at this point. */
  342. log_warn(LD_BUG,"Bug: Closing stream (marked at %s:%d) without sending"
  343. " back a socks reply.",
  344. conn->marked_for_close_file, conn->marked_for_close);
  345. } else {
  346. control_event_stream_status(conn, STREAM_EVENT_CLOSED);
  347. }
  348. break;
  349. case CONN_TYPE_EXIT:
  350. if (conn->state == EXIT_CONN_STATE_RESOLVING) {
  351. circ = circuit_get_by_edge_conn(conn);
  352. if (circ)
  353. circuit_detach_stream(circ, conn);
  354. connection_dns_remove(conn);
  355. }
  356. break;
  357. case CONN_TYPE_DNSWORKER:
  358. if (conn->state == DNSWORKER_STATE_BUSY) {
  359. dns_cancel_pending_resolve(conn->address);
  360. }
  361. break;
  362. }
  363. }
  364. /** Close the underlying socket for <b>conn</b>, so we don't try to
  365. * flush it. Must be used in conjunction with (right before)
  366. * connection_mark_for_close().
  367. */
  368. void
  369. connection_close_immediate(connection_t *conn)
  370. {
  371. assert_connection_ok(conn,0);
  372. if (conn->s < 0) {
  373. log_err(LD_BUG,"Bug: Attempt to close already-closed connection.");
  374. tor_fragile_assert();
  375. return;
  376. }
  377. if (conn->outbuf_flushlen) {
  378. log_info(LD_NET,"fd %d, type %s, state %s, %d bytes on outbuf.",
  379. conn->s, conn_type_to_string(conn->type),
  380. conn_state_to_string(conn->type, conn->state),
  381. (int)conn->outbuf_flushlen);
  382. }
  383. connection_unregister(conn);
  384. tor_close_socket(conn->s);
  385. conn->s = -1;
  386. if (!connection_is_listener(conn)) {
  387. buf_clear(conn->outbuf);
  388. conn->outbuf_flushlen = 0;
  389. }
  390. }
  391. /** Mark <b>conn</b> to be closed next time we loop through
  392. * conn_close_if_marked() in main.c. */
  393. void
  394. _connection_mark_for_close(connection_t *conn, int line, const char *file)
  395. {
  396. assert_connection_ok(conn,0);
  397. tor_assert(line);
  398. tor_assert(file);
  399. if (conn->marked_for_close) {
  400. log(LOG_WARN,LD_BUG,"Duplicate call to connection_mark_for_close at %s:%d"
  401. " (first at %s:%d)", file, line, conn->marked_for_close_file,
  402. conn->marked_for_close);
  403. tor_fragile_assert();
  404. return;
  405. }
  406. conn->marked_for_close = line;
  407. conn->marked_for_close_file = file;
  408. add_connection_to_closeable_list(conn);
  409. /* in case we're going to be held-open-til-flushed, reset
  410. * the number of seconds since last successful write, so
  411. * we get our whole 15 seconds */
  412. conn->timestamp_lastwritten = time(NULL);
  413. }
  414. /** Find each connection that has hold_open_until_flushed set to
  415. * 1 but hasn't written in the past 15 seconds, and set
  416. * hold_open_until_flushed to 0. This means it will get cleaned
  417. * up in the next loop through close_if_marked() in main.c.
  418. */
  419. void
  420. connection_expire_held_open(void)
  421. {
  422. connection_t **carray, *conn;
  423. int n, i;
  424. time_t now;
  425. now = time(NULL);
  426. get_connection_array(&carray, &n);
  427. for (i = 0; i < n; ++i) {
  428. conn = carray[i];
  429. /* If we've been holding the connection open, but we haven't written
  430. * for 15 seconds...
  431. */
  432. if (conn->hold_open_until_flushed) {
  433. tor_assert(conn->marked_for_close);
  434. if (now - conn->timestamp_lastwritten >= 15) {
  435. int severity;
  436. if (conn->type == CONN_TYPE_EXIT ||
  437. (conn->type == CONN_TYPE_DIR &&
  438. conn->purpose == DIR_PURPOSE_SERVER))
  439. severity = LOG_INFO;
  440. else
  441. severity = LOG_NOTICE;
  442. log_fn(severity, LD_NET,
  443. "Giving up on marked_for_close conn that's been flushing "
  444. "for 15s (fd %d, type %s, state %s).",
  445. conn->s, conn_type_to_string(conn->type),
  446. conn_state_to_string(conn->type, conn->state));
  447. conn->hold_open_until_flushed = 0;
  448. }
  449. }
  450. }
  451. }
  452. /** Bind a new non-blocking socket listening to
  453. * <b>listenaddress</b>:<b>listenport</b>, and add this new connection
  454. * (of type <b>type</b>) to the connection array.
  455. *
  456. * If <b>listenaddress</b> includes a port, we bind on that port;
  457. * otherwise, we use listenport.
  458. */
  459. static connection_t *
  460. connection_create_listener(const char *listenaddress, uint16_t listenport,
  461. int type)
  462. {
  463. struct sockaddr_in listenaddr; /* where to bind */
  464. char *address = NULL;
  465. connection_t *conn;
  466. uint16_t usePort;
  467. uint32_t addr;
  468. int s; /* the socket we're going to make */
  469. #ifndef MS_WINDOWS
  470. int one=1;
  471. #endif
  472. memset(&listenaddr,0,sizeof(struct sockaddr_in));
  473. if (parse_addr_port(listenaddress, &address, &addr, &usePort)<0) {
  474. log_warn(LD_CONFIG,
  475. "Error parsing/resolving ListenAddress %s", listenaddress);
  476. return NULL;
  477. }
  478. if (usePort==0)
  479. usePort = listenport;
  480. listenaddr.sin_addr.s_addr = htonl(addr);
  481. listenaddr.sin_family = AF_INET;
  482. listenaddr.sin_port = htons((uint16_t) usePort);
  483. log_notice(LD_NET, "Opening %s on %s:%d",
  484. conn_type_to_string(type), address, usePort);
  485. s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
  486. if (s < 0) {
  487. log_warn(LD_NET,"Socket creation failed.");
  488. goto err;
  489. } else if (!SOCKET_IS_POLLABLE(s)) {
  490. log_warn(LD_NET,"Too many connections; can't create pollable listener.");
  491. tor_close_socket(s);
  492. goto err;
  493. }
  494. #ifndef MS_WINDOWS
  495. /* REUSEADDR on normal places means you can rebind to the port
  496. * right after somebody else has let it go. But REUSEADDR on win32
  497. * means you can bind to the port _even when somebody else
  498. * already has it bound_. So, don't do that on Win32. */
  499. setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*) &one, sizeof(one));
  500. #endif
  501. if (bind(s,(struct sockaddr *)&listenaddr,sizeof(listenaddr)) < 0) {
  502. const char *helpfulhint = "";
  503. int e = tor_socket_errno(s);
  504. if (ERRNO_IS_EADDRINUSE(e))
  505. helpfulhint = ". Is Tor already running?";
  506. log_warn(LD_NET, "Could not bind to %s:%u: %s%s", address, usePort,
  507. tor_socket_strerror(e), helpfulhint);
  508. goto err;
  509. }
  510. if (listen(s,SOMAXCONN) < 0) {
  511. log_warn(LD_NET, "Could not listen on %s:%u: %s", address, usePort,
  512. tor_socket_strerror(tor_socket_errno(s)));
  513. goto err;
  514. }
  515. set_socket_nonblocking(s);
  516. conn = connection_new(type);
  517. conn->s = s;
  518. conn->address = address;
  519. address = NULL;
  520. conn->port = usePort;
  521. if (connection_add(conn) < 0) { /* no space, forget it */
  522. log_warn(LD_NET,"connection_add failed. Giving up.");
  523. connection_free(conn);
  524. goto err;
  525. }
  526. log_debug(LD_NET,"%s listening on port %u.",
  527. conn_type_to_string(type), usePort);
  528. conn->state = LISTENER_STATE_READY;
  529. connection_start_reading(conn);
  530. return conn;
  531. err:
  532. tor_free(address);
  533. return NULL;
  534. }
  535. /** Do basic sanity checking on a newly received socket. Return 0
  536. * if it looks ok, else return -1. */
  537. static int
  538. check_sockaddr_in(struct sockaddr *sa, int len, int level)
  539. {
  540. int ok = 1;
  541. struct sockaddr_in *sin=(struct sockaddr_in*)sa;
  542. if (len != sizeof(struct sockaddr_in)) {
  543. log_fn(level, LD_NET, "Length of address not as expected: %d vs %d",
  544. len,(int)sizeof(struct sockaddr_in));
  545. ok = 0;
  546. }
  547. if (sa->sa_family != AF_INET) {
  548. log_fn(level, LD_NET, "Family of address not as expected: %d vs %d",
  549. sa->sa_family, AF_INET);
  550. ok = 0;
  551. }
  552. if (sin->sin_addr.s_addr == 0 || sin->sin_port == 0) {
  553. log_fn(level, LD_NET,
  554. "Address for new connection has address/port equal to zero.");
  555. ok = 0;
  556. }
  557. return ok ? 0 : -1;
  558. }
  559. /** The listener connection <b>conn</b> told poll() it wanted to read.
  560. * Call accept() on conn-\>s, and add the new connection if necessary.
  561. */
  562. static int
  563. connection_handle_listener_read(connection_t *conn, int new_type)
  564. {
  565. int news; /* the new socket */
  566. connection_t *newconn;
  567. /* information about the remote peer when connecting to other routers */
  568. struct sockaddr_in remote;
  569. char addrbuf[256];
  570. /* length of the remote address. Must be whatever accept() needs. */
  571. socklen_t remotelen = 256;
  572. char tmpbuf[INET_NTOA_BUF_LEN];
  573. tor_assert((size_t)remotelen >= sizeof(struct sockaddr_in));
  574. memset(addrbuf, 0, sizeof(addrbuf));
  575. news = accept(conn->s,(struct sockaddr *)&addrbuf,&remotelen);
  576. if (!SOCKET_IS_POLLABLE(news)) {
  577. /* accept() error, or too many conns to poll */
  578. int e;
  579. if (news>=0) {
  580. /* Too many conns to poll. */
  581. log_warn(LD_NET,"Too many connections; couldn't accept connection.");
  582. tor_close_socket(news);
  583. return 0;
  584. }
  585. e = tor_socket_errno(conn->s);
  586. if (ERRNO_IS_ACCEPT_EAGAIN(e)) {
  587. return 0; /* he hung up before we could accept(). that's fine. */
  588. } else if (ERRNO_IS_ACCEPT_RESOURCE_LIMIT(e)) {
  589. log_notice(LD_NET,"accept failed: %s. Dropping incoming connection.",
  590. tor_socket_strerror(e));
  591. return 0;
  592. }
  593. /* else there was a real error. */
  594. log_warn(LD_NET,"accept() failed: %s. Closing listener.",
  595. tor_socket_strerror(e));
  596. connection_mark_for_close(conn);
  597. return -1;
  598. }
  599. log_debug(LD_NET,
  600. "Connection accepted on socket %d (child of fd %d).",
  601. news,conn->s);
  602. set_socket_nonblocking(news);
  603. if (check_sockaddr_in((struct sockaddr*)addrbuf, remotelen, LOG_INFO)<0) {
  604. log_info(LD_NET,
  605. "accept() returned a strange address; trying getsockname().");
  606. remotelen=256;
  607. memset(addrbuf, 0, sizeof(addrbuf));
  608. if (getsockname(news, (struct sockaddr*)addrbuf, &remotelen)<0) {
  609. log_warn(LD_NET, "getsockname() failed.");
  610. } else {
  611. if (check_sockaddr_in((struct sockaddr*)addrbuf, remotelen,
  612. LOG_WARN) < 0) {
  613. log_warn(LD_NET,"Something's wrong with this conn. Closing it.");
  614. tor_close_socket(news);
  615. return 0;
  616. }
  617. }
  618. }
  619. memcpy(&remote, addrbuf, sizeof(struct sockaddr_in));
  620. /* process entrance policies here, before we even create the connection */
  621. if (new_type == CONN_TYPE_AP) {
  622. /* check sockspolicy to see if we should accept it */
  623. if (socks_policy_permits_address(ntohl(remote.sin_addr.s_addr)) == 0) {
  624. tor_inet_ntoa(&remote.sin_addr, tmpbuf, sizeof(tmpbuf));
  625. log_notice(LD_APP,"Denying socks connection from untrusted address %s.",
  626. tmpbuf);
  627. tor_close_socket(news);
  628. return 0;
  629. }
  630. }
  631. if (new_type == CONN_TYPE_DIR) {
  632. /* check dirpolicy to see if we should accept it */
  633. if (dir_policy_permits_address(ntohl(remote.sin_addr.s_addr)) == 0) {
  634. tor_inet_ntoa(&remote.sin_addr, tmpbuf, sizeof(tmpbuf));
  635. log_notice(LD_DIRSERV,"Denying dir connection from address %s.",
  636. tmpbuf);
  637. tor_close_socket(news);
  638. return 0;
  639. }
  640. }
  641. newconn = connection_new(new_type);
  642. newconn->s = news;
  643. /* remember the remote address */
  644. newconn->addr = ntohl(remote.sin_addr.s_addr);
  645. newconn->port = ntohs(remote.sin_port);
  646. newconn->address = tor_dup_addr(newconn->addr);
  647. if (connection_add(newconn) < 0) { /* no space, forget it */
  648. connection_free(newconn);
  649. return 0; /* no need to tear down the parent */
  650. }
  651. if (connection_init_accepted_conn(newconn) < 0) {
  652. connection_mark_for_close(newconn);
  653. return 0;
  654. }
  655. return 0;
  656. }
  657. /** Initialize states for newly accepted connection <b>conn</b>.
  658. * If conn is an OR, start the tls handshake.
  659. */
  660. static int
  661. connection_init_accepted_conn(connection_t *conn)
  662. {
  663. connection_start_reading(conn);
  664. switch (conn->type) {
  665. case CONN_TYPE_OR:
  666. control_event_or_conn_status(conn, OR_CONN_EVENT_NEW);
  667. return connection_tls_start_handshake(conn, 1);
  668. case CONN_TYPE_AP:
  669. conn->state = AP_CONN_STATE_SOCKS_WAIT;
  670. break;
  671. case CONN_TYPE_DIR:
  672. conn->purpose = DIR_PURPOSE_SERVER;
  673. conn->state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
  674. break;
  675. case CONN_TYPE_CONTROL:
  676. conn->state = CONTROL_CONN_STATE_NEEDAUTH_V0;
  677. break;
  678. }
  679. return 0;
  680. }
  681. /** Take conn, make a nonblocking socket; try to connect to
  682. * addr:port (they arrive in *host order*). If fail, return -1. Else
  683. * assign s to conn-\>s: if connected return 1, if EAGAIN return 0.
  684. *
  685. * address is used to make the logs useful.
  686. *
  687. * On success, add conn to the list of polled connections.
  688. */
  689. int
  690. connection_connect(connection_t *conn, char *address,
  691. uint32_t addr, uint16_t port)
  692. {
  693. int s, inprogress = 0;
  694. struct sockaddr_in dest_addr;
  695. or_options_t *options = get_options();
  696. s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
  697. if (s < 0) {
  698. log_warn(LD_NET,"Error creating network socket: %s",
  699. tor_socket_strerror(tor_socket_errno(-1)));
  700. return -1;
  701. } else if (!SOCKET_IS_POLLABLE(s)) {
  702. log_warn(LD_NET,
  703. "Too many connections; can't create pollable connection to %s",
  704. escaped_safe_str(address));
  705. tor_close_socket(s);
  706. return -1;
  707. }
  708. if (options->OutboundBindAddress) {
  709. struct sockaddr_in ext_addr;
  710. memset(&ext_addr, 0, sizeof(ext_addr));
  711. ext_addr.sin_family = AF_INET;
  712. ext_addr.sin_port = 0;
  713. if (!tor_inet_aton(options->OutboundBindAddress, &ext_addr.sin_addr)) {
  714. log_warn(LD_CONFIG,"Outbound bind address '%s' didn't parse. Ignoring.",
  715. options->OutboundBindAddress);
  716. } else {
  717. if (bind(s, (struct sockaddr*)&ext_addr, sizeof(ext_addr)) < 0) {
  718. log_warn(LD_NET,"Error binding network socket: %s",
  719. tor_socket_strerror(tor_socket_errno(s)));
  720. return -1;
  721. }
  722. }
  723. }
  724. set_socket_nonblocking(s);
  725. memset(&dest_addr,0,sizeof(dest_addr));
  726. dest_addr.sin_family = AF_INET;
  727. dest_addr.sin_port = htons(port);
  728. dest_addr.sin_addr.s_addr = htonl(addr);
  729. log_debug(LD_NET,"Connecting to %s:%u.",escaped_safe_str(address),port);
  730. if (connect(s,(struct sockaddr *)&dest_addr,sizeof(dest_addr)) < 0) {
  731. int e = tor_socket_errno(s);
  732. if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
  733. /* yuck. kill it. */
  734. log_info(LD_NET,
  735. "connect() to %s:%u failed: %s",escaped_safe_str(address),
  736. port, tor_socket_strerror(e));
  737. tor_close_socket(s);
  738. return -1;
  739. } else {
  740. inprogress = 1;
  741. }
  742. }
  743. if (!server_mode(options))
  744. client_check_address_changed(s);
  745. /* it succeeded. we're connected. */
  746. log_fn(inprogress?LOG_DEBUG:LOG_INFO, LD_NET,
  747. "Connection to %s:%u %s (sock %d).",escaped_safe_str(address),
  748. port, inprogress?"in progress":"established", s);
  749. conn->s = s;
  750. if (connection_add(conn) < 0) /* no space, forget it */
  751. return -1;
  752. return inprogress ? 0 : 1;
  753. }
  754. /**
  755. * Launch any configured listener connections of type <b>type</b>. (A
  756. * listener is configured if <b>port_option</b> is non-zero. If any
  757. * ListenAddress configuration options are given in <b>cfg</b>, create a
  758. * connection binding to each one. Otherwise, create a single
  759. * connection binding to the address <b>default_addr</b>.)
  760. *
  761. * If <b>force</b> is true, close and re-open all listener connections.
  762. * Otherwise, only relaunch the listeners of this type if the number of
  763. * existing connections is not as configured (e.g., because one died),
  764. * or if the existing connections do not match those configured.
  765. *
  766. * Add all old conns that should be closed to <b>replaced_conns</b>.
  767. * Add all new connections to <b>new_conns</b>.
  768. */
  769. static int
  770. retry_listeners(int type, config_line_t *cfg,
  771. int port_option, const char *default_addr, int force,
  772. smartlist_t *replaced_conns,
  773. smartlist_t *new_conns)
  774. {
  775. smartlist_t *launch = smartlist_create();
  776. int free_launch_elts = 1;
  777. config_line_t *c;
  778. int n_conn, i;
  779. connection_t *conn;
  780. connection_t **carray;
  781. config_line_t *line;
  782. if (cfg && port_option) {
  783. for (c = cfg; c; c = c->next) {
  784. smartlist_add(launch, c);
  785. }
  786. free_launch_elts = 0;
  787. } else if (port_option) {
  788. line = tor_malloc_zero(sizeof(config_line_t));
  789. line->key = tor_strdup("");
  790. line->value = tor_strdup(default_addr);
  791. smartlist_add(launch, line);
  792. }
  793. /*
  794. SMARTLIST_FOREACH(launch, config_line_t *, l,
  795. log_fn(LOG_NOTICE, "#%s#%s", l->key, l->value));
  796. */
  797. get_connection_array(&carray,&n_conn);
  798. for (i=0; i < n_conn; ++i) {
  799. conn = carray[i];
  800. if (conn->type != type || conn->marked_for_close)
  801. continue;
  802. if (force) {
  803. /* It's a listener, and we're relaunching all listeners of this
  804. * type. Close this one. */
  805. log_fn(LOG_NOTICE, LD_NET, "Closing %s on %s:%d",
  806. conn_type_to_string(type), conn->address, conn->port);
  807. connection_close_immediate(conn);
  808. connection_mark_for_close(conn);
  809. continue;
  810. }
  811. /* Okay, so this is a listener. Is it configured? */
  812. line = NULL;
  813. SMARTLIST_FOREACH(launch, config_line_t *, wanted,
  814. {
  815. char *address=NULL;
  816. uint16_t port;
  817. if (! parse_addr_port(wanted->value, &address, NULL, &port)) {
  818. int addr_matches = !strcasecmp(address, conn->address);
  819. tor_free(address);
  820. if (! port)
  821. port = port_option;
  822. if (port == conn->port && addr_matches) {
  823. line = wanted;
  824. break;
  825. }
  826. }
  827. });
  828. if (! line) {
  829. /* This one isn't configured. Close it. */
  830. log_notice(LD_NET, "Closing %s on %s:%d",
  831. conn_type_to_string(type), conn->address, conn->port);
  832. if (replaced_conns) {
  833. smartlist_add(replaced_conns, conn);
  834. } else {
  835. connection_close_immediate(conn);
  836. connection_mark_for_close(conn);
  837. }
  838. } else {
  839. /* It's configured; we don't need to launch it. */
  840. // log_debug(LD_NET, "Already have %s on %s:%d",
  841. // conn_type_to_string(type), conn->address, conn->port);
  842. smartlist_remove(launch, line);
  843. if (free_launch_elts)
  844. config_free_lines(line);
  845. }
  846. }
  847. /* Now open all the listeners that are configured but not opened. */
  848. i = 0;
  849. SMARTLIST_FOREACH(launch, config_line_t *, cfg,
  850. {
  851. conn = connection_create_listener(cfg->value, (uint16_t) port_option,
  852. type);
  853. if (!conn) {
  854. i = -1;
  855. } else {
  856. if (new_conns)
  857. smartlist_add(new_conns, conn);
  858. }
  859. });
  860. if (free_launch_elts) {
  861. SMARTLIST_FOREACH(launch, config_line_t *, cfg,
  862. config_free_lines(cfg));
  863. }
  864. smartlist_free(launch);
  865. return i;
  866. }
  867. /** (Re)launch listeners for each port you should have open. If
  868. * <b>force</b> is true, close and relaunch all listeners. If <b>force</b>
  869. * is false, then only relaunch listeners when we have the wrong number of
  870. * connections for a given type.
  871. *
  872. * Add all old conns that should be closed to <b>replaced_conns</b>.
  873. * Add all new connections to <b>new_conns</b>.
  874. */
  875. int
  876. retry_all_listeners(int force, smartlist_t *replaced_conns,
  877. smartlist_t *new_conns)
  878. {
  879. or_options_t *options = get_options();
  880. if (server_mode(options) &&
  881. retry_listeners(CONN_TYPE_OR_LISTENER, options->ORListenAddress,
  882. options->ORPort, "0.0.0.0", force,
  883. replaced_conns, new_conns)<0)
  884. return -1;
  885. if (retry_listeners(CONN_TYPE_DIR_LISTENER, options->DirListenAddress,
  886. options->DirPort, "0.0.0.0", force,
  887. replaced_conns, new_conns)<0)
  888. return -1;
  889. if (retry_listeners(CONN_TYPE_AP_LISTENER, options->SocksListenAddress,
  890. options->SocksPort, "127.0.0.1", force,
  891. replaced_conns, new_conns)<0)
  892. return -1;
  893. if (retry_listeners(CONN_TYPE_CONTROL_LISTENER,
  894. options->ControlListenAddress,
  895. options->ControlPort, "127.0.0.1", force,
  896. replaced_conns, new_conns)<0)
  897. return -1;
  898. return 0;
  899. }
  900. extern int global_read_bucket, global_write_bucket;
  901. /** How many bytes at most can we read onto this connection? */
  902. static int
  903. connection_bucket_read_limit(connection_t *conn)
  904. {
  905. int at_most;
  906. int base = connection_speaks_cells(conn) ?
  907. CELL_NETWORK_SIZE : RELAY_PAYLOAD_SIZE;
  908. /* Do a rudimentary round-robin so one circuit can't hog a connection.
  909. * Pick at most 32 cells, at least 4 cells if possible, and if we're in
  910. * the middle pick 1/8 of the available bandwidth. */
  911. at_most = global_read_bucket / 8;
  912. at_most -= (at_most % base); /* round down */
  913. if (at_most > 32*base) /* 16 KB */
  914. at_most = 32*base;
  915. else if (at_most < 4*base) /* 2 KB */
  916. at_most = 4*base;
  917. if (at_most > global_read_bucket)
  918. at_most = global_read_bucket;
  919. if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN)
  920. if (at_most > conn->receiver_bucket)
  921. at_most = conn->receiver_bucket;
  922. if (at_most < 0)
  923. return 0;
  924. return at_most;
  925. }
  926. /** How many bytes at most can we write onto this connection? */
  927. int
  928. connection_bucket_write_limit(connection_t *conn)
  929. {
  930. unsigned int at_most;
  931. /* do a rudimentary round-robin so one circuit can't hog a connection */
  932. if (connection_speaks_cells(conn)) {
  933. at_most = 32*(CELL_NETWORK_SIZE);
  934. } else {
  935. at_most = 32*(RELAY_PAYLOAD_SIZE);
  936. }
  937. if (at_most > conn->outbuf_flushlen)
  938. at_most = conn->outbuf_flushlen;
  939. #if 0 /* don't enable til we actually do write limiting */
  940. if (at_most > global_write_bucket)
  941. at_most = global_write_bucket;
  942. #endif
  943. return at_most;
  944. }
  945. /** Return 1 if the global write bucket has no bytes in it,
  946. * or return 0 if it does. */
  947. int
  948. global_write_bucket_empty(void)
  949. {
  950. return global_write_bucket <= 0;
  951. }
  952. /** We just read num_read onto conn. Decrement buckets appropriately. */
  953. static void
  954. connection_read_bucket_decrement(connection_t *conn, int num_read)
  955. {
  956. global_read_bucket -= num_read;
  957. //tor_assert(global_read_bucket >= 0);
  958. if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
  959. conn->receiver_bucket -= num_read;
  960. //tor_assert(conn->receiver_bucket >= 0);
  961. }
  962. }
  963. /** If we have exhaused our global read bucket, or the read bucket for conn,
  964. * stop reading. */
  965. static void
  966. connection_consider_empty_buckets(connection_t *conn)
  967. {
  968. if (global_read_bucket <= 0) {
  969. LOG_FN_CONN(conn, (LOG_DEBUG,LD_NET,"global bucket exhausted. Pausing."));
  970. conn->wants_to_read = 1;
  971. connection_stop_reading(conn);
  972. return;
  973. }
  974. if (connection_speaks_cells(conn) &&
  975. conn->state == OR_CONN_STATE_OPEN &&
  976. conn->receiver_bucket <= 0) {
  977. LOG_FN_CONN(conn,
  978. (LOG_DEBUG,LD_NET,"receiver bucket exhausted. Pausing."));
  979. conn->wants_to_read = 1;
  980. connection_stop_reading(conn);
  981. }
  982. }
  983. /** Initialize the global read bucket to options->BandwidthBurst,
  984. * and current_time to the current time. */
  985. void
  986. connection_bucket_init(void)
  987. {
  988. or_options_t *options = get_options();
  989. /* start it at max traffic */
  990. global_read_bucket = (int)options->BandwidthBurst;
  991. global_write_bucket = (int)options->BandwidthBurst;
  992. }
  993. /** A second has rolled over; increment buckets appropriately. */
  994. void
  995. connection_bucket_refill(struct timeval *now)
  996. {
  997. int i, n;
  998. connection_t *conn;
  999. connection_t **carray;
  1000. or_options_t *options = get_options();
  1001. /* refill the global buckets */
  1002. if (global_read_bucket < (int)options->BandwidthBurst) {
  1003. global_read_bucket += (int)options->BandwidthRate;
  1004. log_debug(LD_NET,"global_read_bucket now %d.", global_read_bucket);
  1005. }
  1006. if (global_write_bucket < (int)options->BandwidthBurst) {
  1007. global_write_bucket += (int)options->BandwidthRate;
  1008. log_debug(LD_NET,"global_write_bucket now %d.", global_write_bucket);
  1009. }
  1010. /* refill the per-connection buckets */
  1011. get_connection_array(&carray,&n);
  1012. for (i=0;i<n;i++) {
  1013. conn = carray[i];
  1014. if (connection_receiver_bucket_should_increase(conn)) {
  1015. conn->receiver_bucket = conn->bandwidth;
  1016. //log_fn(LOG_DEBUG,"Receiver bucket %d now %d.", i,
  1017. // conn->receiver_bucket);
  1018. }
  1019. if (conn->wants_to_read == 1 /* it's marked to turn reading back on now */
  1020. && global_read_bucket > 0 /* and we're allowed to read */
  1021. && global_write_bucket > 0 /* and we're allowed to write (XXXX,
  1022. * not the best place to check this.) */
  1023. && (!connection_speaks_cells(conn) ||
  1024. conn->state != OR_CONN_STATE_OPEN ||
  1025. conn->receiver_bucket > 0)) {
  1026. /* and either a non-cell conn or a cell conn with non-empty bucket */
  1027. LOG_FN_CONN(conn, (LOG_DEBUG,LD_NET,"waking up conn (fd %d)",conn->s));
  1028. conn->wants_to_read = 0;
  1029. connection_start_reading(conn);
  1030. if (conn->wants_to_write == 1) {
  1031. conn->wants_to_write = 0;
  1032. connection_start_writing(conn);
  1033. }
  1034. }
  1035. }
  1036. }
  1037. /** Is the receiver bucket for connection <b>conn</b> low enough that we
  1038. * should add another pile of tokens to it?
  1039. */
  1040. static int
  1041. connection_receiver_bucket_should_increase(connection_t *conn)
  1042. {
  1043. tor_assert(conn);
  1044. if (!connection_speaks_cells(conn))
  1045. return 0; /* edge connections don't use receiver_buckets */
  1046. if (conn->state != OR_CONN_STATE_OPEN)
  1047. return 0; /* only open connections play the rate limiting game */
  1048. if (conn->receiver_bucket >= conn->bandwidth)
  1049. return 0;
  1050. return 1;
  1051. }
  1052. /** Read bytes from conn-\>s and process them.
  1053. *
  1054. * This function gets called from conn_read() in main.c, either
  1055. * when poll() has declared that conn wants to read, or (for OR conns)
  1056. * when there are pending TLS bytes.
  1057. *
  1058. * It calls connection_read_to_buf() to bring in any new bytes,
  1059. * and then calls connection_process_inbuf() to process them.
  1060. *
  1061. * Mark the connection and return -1 if you want to close it, else
  1062. * return 0.
  1063. */
  1064. int
  1065. connection_handle_read(connection_t *conn)
  1066. {
  1067. int max_to_read=-1, try_to_read;
  1068. if (conn->marked_for_close)
  1069. return 0; /* do nothing */
  1070. conn->timestamp_lastread = time(NULL);
  1071. switch (conn->type) {
  1072. case CONN_TYPE_OR_LISTENER:
  1073. return connection_handle_listener_read(conn, CONN_TYPE_OR);
  1074. case CONN_TYPE_AP_LISTENER:
  1075. return connection_handle_listener_read(conn, CONN_TYPE_AP);
  1076. case CONN_TYPE_DIR_LISTENER:
  1077. return connection_handle_listener_read(conn, CONN_TYPE_DIR);
  1078. case CONN_TYPE_CONTROL_LISTENER:
  1079. return connection_handle_listener_read(conn, CONN_TYPE_CONTROL);
  1080. }
  1081. loop_again:
  1082. try_to_read = max_to_read;
  1083. tor_assert(!conn->marked_for_close);
  1084. if (connection_read_to_buf(conn, &max_to_read) < 0) {
  1085. /* There's a read error; kill the connection.*/
  1086. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  1087. if (CONN_IS_EDGE(conn)) {
  1088. connection_edge_end_errno(conn, conn->cpath_layer);
  1089. if (conn->socks_request) /* broken, so don't send a socks reply back */
  1090. conn->socks_request->has_finished = 1;
  1091. }
  1092. connection_mark_for_close(conn);
  1093. return -1;
  1094. }
  1095. if (CONN_IS_EDGE(conn) &&
  1096. try_to_read != max_to_read) {
  1097. /* instruct it not to try to package partial cells. */
  1098. if (connection_process_inbuf(conn, 0) < 0) {
  1099. return -1;
  1100. }
  1101. if (!conn->marked_for_close &&
  1102. connection_is_reading(conn) &&
  1103. !conn->inbuf_reached_eof &&
  1104. max_to_read > 0)
  1105. goto loop_again; /* try reading again, in case more is here now */
  1106. }
  1107. /* one last try, packaging partial cells and all. */
  1108. if (!conn->marked_for_close &&
  1109. connection_process_inbuf(conn, 1) < 0) {
  1110. return -1;
  1111. }
  1112. if (!conn->marked_for_close &&
  1113. conn->inbuf_reached_eof &&
  1114. connection_reached_eof(conn) < 0) {
  1115. return -1;
  1116. }
  1117. return 0;
  1118. }
  1119. /** Pull in new bytes from conn-\>s onto conn-\>inbuf, either
  1120. * directly or via TLS. Reduce the token buckets by the number of
  1121. * bytes read.
  1122. *
  1123. * If *max_to_read is -1, then decide it ourselves, else go with the
  1124. * value passed to us. When returning, if it's changed, subtract the
  1125. * number of bytes we read from *max_to_read.
  1126. *
  1127. * Return -1 if we want to break conn, else return 0.
  1128. */
  1129. static int
  1130. connection_read_to_buf(connection_t *conn, int *max_to_read)
  1131. {
  1132. int result, at_most = *max_to_read;
  1133. size_t bytes_in_buf, more_to_read;
  1134. if (at_most == -1) { /* we need to initialize it */
  1135. /* how many bytes are we allowed to read? */
  1136. at_most = connection_bucket_read_limit(conn);
  1137. }
  1138. bytes_in_buf = buf_capacity(conn->inbuf) - buf_datalen(conn->inbuf);
  1139. again:
  1140. if ((size_t)at_most > bytes_in_buf && bytes_in_buf >= 1024) {
  1141. more_to_read = at_most - bytes_in_buf;
  1142. at_most = bytes_in_buf;
  1143. } else {
  1144. more_to_read = 0;
  1145. }
  1146. if (connection_speaks_cells(conn) &&
  1147. conn->state > OR_CONN_STATE_PROXY_READING) {
  1148. int pending;
  1149. if (conn->state == OR_CONN_STATE_HANDSHAKING) {
  1150. /* continue handshaking even if global token bucket is empty */
  1151. return connection_tls_continue_handshake(conn);
  1152. }
  1153. log_debug(LD_NET,
  1154. "%d: starting, inbuf_datalen %d (%d pending in tls object)."
  1155. " at_most %d.",
  1156. conn->s,(int)buf_datalen(conn->inbuf),
  1157. tor_tls_get_pending_bytes(conn->tls), at_most);
  1158. /* else open, or closing */
  1159. result = read_to_buf_tls(conn->tls, at_most, conn->inbuf);
  1160. switch (result) {
  1161. case TOR_TLS_CLOSE:
  1162. log_info(LD_NET,"TLS connection closed on read. Closing. "
  1163. "(Nickname %s, address %s",
  1164. conn->nickname ? conn->nickname : "not set", conn->address);
  1165. return -1;
  1166. case TOR_TLS_ERROR:
  1167. log_info(LD_NET,"tls error. breaking (nickname %s, address %s).",
  1168. conn->nickname ? conn->nickname : "not set", conn->address);
  1169. return -1;
  1170. case TOR_TLS_WANTWRITE:
  1171. connection_start_writing(conn);
  1172. return 0;
  1173. case TOR_TLS_WANTREAD: /* we're already reading */
  1174. case TOR_TLS_DONE: /* no data read, so nothing to process */
  1175. result = 0;
  1176. break; /* so we call bucket_decrement below */
  1177. default:
  1178. break;
  1179. }
  1180. pending = tor_tls_get_pending_bytes(conn->tls);
  1181. if (pending) {
  1182. /* XXXX If we have any pending bytes, read them now. This *can*
  1183. * take us over our read allotment, but really we shouldn't be
  1184. * believing that SSL bytes are the same as TCP bytes anyway. */
  1185. int r2 = read_to_buf_tls(conn->tls, pending, conn->inbuf);
  1186. if (r2<0) {
  1187. log_warn(LD_BUG, "Bug: apparently, reading pending bytes can fail.");
  1188. return -1;
  1189. } else {
  1190. result += r2;
  1191. }
  1192. }
  1193. } else {
  1194. CONN_LOG_PROTECT(conn,
  1195. result = read_to_buf(conn->s, at_most, conn->inbuf,
  1196. &conn->inbuf_reached_eof));
  1197. // log_fn(LOG_DEBUG,"read_to_buf returned %d.",read_result);
  1198. if (result < 0)
  1199. return -1;
  1200. }
  1201. if (result > 0) { /* change *max_to_read */
  1202. *max_to_read = at_most - result;
  1203. }
  1204. if (result > 0 && !is_local_IP(conn->addr)) { /* remember it */
  1205. rep_hist_note_bytes_read(result, time(NULL));
  1206. connection_read_bucket_decrement(conn, result);
  1207. }
  1208. if (more_to_read && result == at_most) {
  1209. bytes_in_buf = buf_capacity(conn->inbuf) - buf_datalen(conn->inbuf);
  1210. tor_assert(bytes_in_buf < 1024);
  1211. at_most = more_to_read;
  1212. goto again;
  1213. }
  1214. /* Call even if result is 0, since the global read bucket may
  1215. * have reached 0 on a different conn, and this guy needs to
  1216. * know to stop reading. */
  1217. connection_consider_empty_buckets(conn);
  1218. return 0;
  1219. }
  1220. /** A pass-through to fetch_from_buf. */
  1221. int
  1222. connection_fetch_from_buf(char *string, size_t len, connection_t *conn)
  1223. {
  1224. return fetch_from_buf(string, len, conn->inbuf);
  1225. }
  1226. /** Return conn-\>outbuf_flushlen: how many bytes conn wants to flush
  1227. * from its outbuf. */
  1228. int
  1229. connection_wants_to_flush(connection_t *conn)
  1230. {
  1231. return conn->outbuf_flushlen;
  1232. }
  1233. /** Are there too many bytes on edge connection <b>conn</b>'s outbuf to
  1234. * send back a relay-level sendme yet? Return 1 if so, 0 if not. Used by
  1235. * connection_edge_consider_sending_sendme().
  1236. */
  1237. int
  1238. connection_outbuf_too_full(connection_t *conn)
  1239. {
  1240. return (conn->outbuf_flushlen > 10*CELL_PAYLOAD_SIZE);
  1241. }
  1242. /** Try to flush more bytes onto conn-\>s.
  1243. *
  1244. * This function gets called either from conn_write() in main.c
  1245. * when poll() has declared that conn wants to write, or below
  1246. * from connection_write_to_buf() when an entire TLS record is ready.
  1247. *
  1248. * Update conn-\>timestamp_lastwritten to now, and call flush_buf
  1249. * or flush_buf_tls appropriately. If it succeeds and there no more
  1250. * more bytes on conn->outbuf, then call connection_finished_flushing
  1251. * on it too.
  1252. *
  1253. * Mark the connection and return -1 if you want to close it, else
  1254. * return 0.
  1255. */
  1256. int
  1257. connection_handle_write(connection_t *conn)
  1258. {
  1259. int e;
  1260. socklen_t len=sizeof(e);
  1261. int result;
  1262. int max_to_write;
  1263. time_t now = time(NULL);
  1264. tor_assert(!connection_is_listener(conn));
  1265. if (conn->marked_for_close)
  1266. return 0; /* do nothing */
  1267. conn->timestamp_lastwritten = now;
  1268. /* Sometimes, "writable" means "connected". */
  1269. if (connection_state_is_connecting(conn)) {
  1270. if (getsockopt(conn->s, SOL_SOCKET, SO_ERROR, (void*)&e, &len) < 0) {
  1271. log_warn(LD_BUG,
  1272. "getsockopt() syscall failed?! Please report to tor-ops.");
  1273. if (CONN_IS_EDGE(conn))
  1274. connection_edge_end_errno(conn, conn->cpath_layer);
  1275. connection_mark_for_close(conn);
  1276. return -1;
  1277. }
  1278. if (e) {
  1279. /* some sort of error, but maybe just inprogress still */
  1280. if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
  1281. log_info(LD_NET,"in-progress connect failed. Removing.");
  1282. if (CONN_IS_EDGE(conn))
  1283. connection_edge_end_errno(conn, conn->cpath_layer);
  1284. connection_close_immediate(conn);
  1285. connection_mark_for_close(conn);
  1286. /* it's safe to pass OPs to router_set_status(), since it just
  1287. * ignores unrecognized routers
  1288. */
  1289. if (conn->type == CONN_TYPE_OR && !get_options()->HttpsProxy)
  1290. router_set_status(conn->identity_digest, 0);
  1291. return -1;
  1292. } else {
  1293. return 0; /* no change, see if next time is better */
  1294. }
  1295. }
  1296. /* The connection is successful. */
  1297. if (connection_finished_connecting(conn)<0)
  1298. return -1;
  1299. }
  1300. max_to_write = connection_bucket_write_limit(conn);
  1301. if (connection_speaks_cells(conn) &&
  1302. conn->state > OR_CONN_STATE_PROXY_READING) {
  1303. if (conn->state == OR_CONN_STATE_HANDSHAKING) {
  1304. connection_stop_writing(conn);
  1305. if (connection_tls_continue_handshake(conn) < 0) {
  1306. /* Don't flush; connection is dead. */
  1307. connection_close_immediate(conn);
  1308. connection_mark_for_close(conn);
  1309. return -1;
  1310. }
  1311. return 0;
  1312. }
  1313. /* else open, or closing */
  1314. result = flush_buf_tls(conn->tls, conn->outbuf,
  1315. max_to_write, &conn->outbuf_flushlen);
  1316. switch (result) {
  1317. case TOR_TLS_ERROR:
  1318. case TOR_TLS_CLOSE:
  1319. log_info(LD_NET,result==TOR_TLS_ERROR?
  1320. "tls error. breaking.":"TLS connection closed on flush");
  1321. /* Don't flush; connection is dead. */
  1322. connection_close_immediate(conn);
  1323. connection_mark_for_close(conn);
  1324. return -1;
  1325. case TOR_TLS_WANTWRITE:
  1326. log_debug(LD_NET,"wanted write.");
  1327. /* we're already writing */
  1328. return 0;
  1329. case TOR_TLS_WANTREAD:
  1330. /* Make sure to avoid a loop if the receive buckets are empty. */
  1331. log_debug(LD_NET,"wanted read.");
  1332. if (!connection_is_reading(conn)) {
  1333. connection_stop_writing(conn);
  1334. conn->wants_to_write = 1;
  1335. /* we'll start reading again when the next second arrives,
  1336. * and then also start writing again.
  1337. */
  1338. }
  1339. /* else no problem, we're already reading */
  1340. return 0;
  1341. /* case TOR_TLS_DONE:
  1342. * for TOR_TLS_DONE, fall through to check if the flushlen
  1343. * is empty, so we can stop writing.
  1344. */
  1345. }
  1346. } else {
  1347. CONN_LOG_PROTECT(conn,
  1348. result = flush_buf(conn->s, conn->outbuf,
  1349. max_to_write, &conn->outbuf_flushlen));
  1350. if (result < 0) {
  1351. if (CONN_IS_EDGE(conn))
  1352. connection_edge_end_errno(conn, conn->cpath_layer);
  1353. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  1354. connection_mark_for_close(conn);
  1355. return -1;
  1356. }
  1357. }
  1358. if (result > 0 && !is_local_IP(conn->addr)) { /* remember it */
  1359. rep_hist_note_bytes_written(result, now);
  1360. global_write_bucket -= result;
  1361. }
  1362. if (!connection_wants_to_flush(conn)) { /* it's done flushing */
  1363. if (connection_finished_flushing(conn) < 0) {
  1364. /* already marked */
  1365. return -1;
  1366. }
  1367. }
  1368. return 0;
  1369. }
  1370. /* A controller event has just happened with such urgency that we
  1371. * need to write it onto controller <b>conn</b> immediately. */
  1372. void
  1373. _connection_controller_force_write(connection_t *conn)
  1374. {
  1375. /* XXX This is hideous code duplication, but raising it seems a little
  1376. * tricky for now. Think more about this one. We only call it for
  1377. * EVENT_ERR_MSG, so messing with buckets a little isn't such a big problem.
  1378. */
  1379. int result;
  1380. tor_assert(conn);
  1381. tor_assert(!conn->tls);
  1382. tor_assert(conn->type == CONN_TYPE_CONTROL);
  1383. if (conn->marked_for_close || conn->s < 0)
  1384. return;
  1385. CONN_LOG_PROTECT(conn,
  1386. result = flush_buf(conn->s, conn->outbuf,
  1387. conn->outbuf_flushlen, &conn->outbuf_flushlen));
  1388. if (result < 0) {
  1389. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  1390. connection_mark_for_close(conn);
  1391. return;
  1392. }
  1393. if (result > 0 && !is_local_IP(conn->addr)) { /* remember it */
  1394. rep_hist_note_bytes_written(result, time(NULL));
  1395. global_write_bucket -= result;
  1396. }
  1397. if (!connection_wants_to_flush(conn)) { /* it's done flushing */
  1398. if (connection_finished_flushing(conn) < 0) {
  1399. /* already marked */
  1400. return;
  1401. }
  1402. }
  1403. }
  1404. /** Append <b>len</b> bytes of <b>string</b> onto <b>conn</b>'s
  1405. * outbuf, and ask it to start writing.
  1406. */
  1407. void
  1408. connection_write_to_buf(const char *string, size_t len, connection_t *conn)
  1409. {
  1410. int r;
  1411. if (!len)
  1412. return;
  1413. /* if it's marked for close, only allow write if we mean to flush it */
  1414. if (conn->marked_for_close && !conn->hold_open_until_flushed)
  1415. return;
  1416. CONN_LOG_PROTECT(conn, r = write_to_buf(string, len, conn->outbuf));
  1417. if (r < 0) {
  1418. if (CONN_IS_EDGE(conn)) {
  1419. /* if it failed, it means we have our package/delivery windows set
  1420. wrong compared to our max outbuf size. close the whole circuit. */
  1421. log_warn(LD_NET,
  1422. "write_to_buf failed. Closing circuit (fd %d).", conn->s);
  1423. circuit_mark_for_close(circuit_get_by_edge_conn(conn),
  1424. END_CIRC_REASON_INTERNAL);
  1425. } else {
  1426. log_warn(LD_NET,
  1427. "write_to_buf failed. Closing connection (fd %d).", conn->s);
  1428. connection_mark_for_close(conn);
  1429. }
  1430. return;
  1431. }
  1432. connection_start_writing(conn);
  1433. conn->outbuf_flushlen += len;
  1434. }
  1435. /** Return the conn to addr/port that has the most recent
  1436. * timestamp_created, or NULL if no such conn exists. */
  1437. connection_t *
  1438. connection_or_exact_get_by_addr_port(uint32_t addr, uint16_t port)
  1439. {
  1440. int i, n;
  1441. connection_t *conn, *best=NULL;
  1442. connection_t **carray;
  1443. get_connection_array(&carray,&n);
  1444. for (i=0;i<n;i++) {
  1445. conn = carray[i];
  1446. if (conn->type == CONN_TYPE_OR &&
  1447. conn->addr == addr &&
  1448. conn->port == port &&
  1449. !conn->marked_for_close &&
  1450. (!best || best->timestamp_created < conn->timestamp_created))
  1451. best = conn;
  1452. }
  1453. return best;
  1454. }
  1455. /** Return a connection with given type, address, port, and purpose;
  1456. * or NULL if no such connection exists. */
  1457. connection_t *
  1458. connection_get_by_type_addr_port_purpose(int type,
  1459. uint32_t addr, uint16_t port,
  1460. int purpose)
  1461. {
  1462. int i, n;
  1463. connection_t *conn;
  1464. connection_t **carray;
  1465. get_connection_array(&carray,&n);
  1466. for (i=0;i<n;i++) {
  1467. conn = carray[i];
  1468. if (conn->type == type &&
  1469. conn->addr == addr &&
  1470. conn->port == port &&
  1471. conn->purpose == purpose &&
  1472. !conn->marked_for_close)
  1473. return conn;
  1474. }
  1475. return NULL;
  1476. }
  1477. /** Return the connection with id <b>id</b> if it is not already marked for
  1478. * close.
  1479. */
  1480. connection_t *
  1481. connection_get_by_global_id(uint32_t id)
  1482. {
  1483. int i, n;
  1484. connection_t *conn;
  1485. connection_t **carray;
  1486. get_connection_array(&carray,&n);
  1487. for (i=0;i<n;i++) {
  1488. conn = carray[i];
  1489. if (conn->global_identifier == id) {
  1490. if (!conn->marked_for_close)
  1491. return conn;
  1492. else
  1493. return NULL;
  1494. }
  1495. }
  1496. return NULL;
  1497. }
  1498. /** Return a connection of type <b>type</b> that is not marked for close.
  1499. */
  1500. connection_t *
  1501. connection_get_by_type(int type)
  1502. {
  1503. int i, n;
  1504. connection_t *conn;
  1505. connection_t **carray;
  1506. get_connection_array(&carray,&n);
  1507. for (i=0;i<n;i++) {
  1508. conn = carray[i];
  1509. if (conn->type == type && !conn->marked_for_close)
  1510. return conn;
  1511. }
  1512. return NULL;
  1513. }
  1514. /** Return a connection of type <b>type</b> that is in state <b>state</b>,
  1515. * and that is not marked for close.
  1516. */
  1517. connection_t *
  1518. connection_get_by_type_state(int type, int state)
  1519. {
  1520. int i, n;
  1521. connection_t *conn;
  1522. connection_t **carray;
  1523. get_connection_array(&carray,&n);
  1524. for (i=0;i<n;i++) {
  1525. conn = carray[i];
  1526. if (conn->type == type && conn->state == state && !conn->marked_for_close)
  1527. return conn;
  1528. }
  1529. return NULL;
  1530. }
  1531. /** Return the connection of type <b>type</b> that is in state
  1532. * <b>state</b>, that was written to least recently, and that is not
  1533. * marked for close.
  1534. */
  1535. connection_t *
  1536. connection_get_by_type_state_lastwritten(int type, int state)
  1537. {
  1538. int i, n;
  1539. connection_t *conn, *best=NULL;
  1540. connection_t **carray;
  1541. get_connection_array(&carray,&n);
  1542. for (i=0;i<n;i++) {
  1543. conn = carray[i];
  1544. if (conn->type == type && conn->state == state && !conn->marked_for_close)
  1545. if (!best || conn->timestamp_lastwritten < best->timestamp_lastwritten)
  1546. best = conn;
  1547. }
  1548. return best;
  1549. }
  1550. /** Return a connection of type <b>type</b> that has rendquery equal
  1551. * to <b>rendquery</b>, and that is not marked for close. If state
  1552. * is non-zero, conn must be of that state too.
  1553. */
  1554. connection_t *
  1555. connection_get_by_type_state_rendquery(int type, int state,
  1556. const char *rendquery)
  1557. {
  1558. int i, n;
  1559. connection_t *conn;
  1560. connection_t **carray;
  1561. get_connection_array(&carray,&n);
  1562. for (i=0;i<n;i++) {
  1563. conn = carray[i];
  1564. if (conn->type == type &&
  1565. !conn->marked_for_close &&
  1566. (!state || state == conn->state) &&
  1567. !rend_cmp_service_ids(rendquery, conn->rend_query))
  1568. return conn;
  1569. }
  1570. return NULL;
  1571. }
  1572. /** Return an open, non-marked connection of a given type and purpose, or NULL
  1573. * if no such connection exists. */
  1574. connection_t *
  1575. connection_get_by_type_purpose(int type, int purpose)
  1576. {
  1577. int i, n;
  1578. connection_t *conn;
  1579. connection_t **carray;
  1580. get_connection_array(&carray,&n);
  1581. for (i=0;i<n;i++) {
  1582. conn = carray[i];
  1583. if (conn->type == type &&
  1584. !conn->marked_for_close &&
  1585. (purpose == conn->purpose))
  1586. return conn;
  1587. }
  1588. return NULL;
  1589. }
  1590. /** Return 1 if <b>conn</b> is a listener conn, else return 0. */
  1591. int
  1592. connection_is_listener(connection_t *conn)
  1593. {
  1594. if (conn->type == CONN_TYPE_OR_LISTENER ||
  1595. conn->type == CONN_TYPE_AP_LISTENER ||
  1596. conn->type == CONN_TYPE_DIR_LISTENER ||
  1597. conn->type == CONN_TYPE_CONTROL_LISTENER)
  1598. return 1;
  1599. return 0;
  1600. }
  1601. /** Return 1 if <b>conn</b> is in state "open" and is not marked
  1602. * for close, else return 0.
  1603. */
  1604. int
  1605. connection_state_is_open(connection_t *conn)
  1606. {
  1607. tor_assert(conn);
  1608. if (conn->marked_for_close)
  1609. return 0;
  1610. if ((conn->type == CONN_TYPE_OR && conn->state == OR_CONN_STATE_OPEN) ||
  1611. (conn->type == CONN_TYPE_AP && conn->state == AP_CONN_STATE_OPEN) ||
  1612. (conn->type == CONN_TYPE_EXIT && conn->state == EXIT_CONN_STATE_OPEN) ||
  1613. (conn->type == CONN_TYPE_CONTROL &&
  1614. (conn->state == CONTROL_CONN_STATE_OPEN_V0 ||
  1615. conn->state == CONTROL_CONN_STATE_OPEN_V1)))
  1616. return 1;
  1617. return 0;
  1618. }
  1619. /** Return 1 if conn is in 'connecting' state, else return 0. */
  1620. int
  1621. connection_state_is_connecting(connection_t *conn)
  1622. {
  1623. tor_assert(conn);
  1624. if (conn->marked_for_close)
  1625. return 0;
  1626. switch (conn->type)
  1627. {
  1628. case CONN_TYPE_OR:
  1629. return conn->state == OR_CONN_STATE_CONNECTING;
  1630. case CONN_TYPE_EXIT:
  1631. return conn->state == EXIT_CONN_STATE_CONNECTING;
  1632. case CONN_TYPE_DIR:
  1633. return conn->state == DIR_CONN_STATE_CONNECTING;
  1634. }
  1635. return 0;
  1636. }
  1637. /** Alloocates a base64'ed authenticator for use in http or https
  1638. * auth, based on the input string <b>authenticator</b>. Returns it
  1639. * if success, else returns NULL. */
  1640. char *
  1641. alloc_http_authenticator(const char *authenticator)
  1642. {
  1643. /* an authenticator in Basic authentication
  1644. * is just the string "username:password" */
  1645. const int authenticator_length = strlen(authenticator);
  1646. /* The base64_encode function needs a minimum buffer length
  1647. * of 66 bytes. */
  1648. const int base64_authenticator_length = (authenticator_length/48+1)*66;
  1649. char *base64_authenticator = tor_malloc(base64_authenticator_length);
  1650. if (base64_encode(base64_authenticator, base64_authenticator_length,
  1651. authenticator, authenticator_length) < 0) {
  1652. tor_free(base64_authenticator); /* free and set to null */
  1653. } else {
  1654. /* remove extra \n at end of encoding */
  1655. base64_authenticator[strlen(base64_authenticator) - 1] = 0;
  1656. }
  1657. return base64_authenticator;
  1658. }
  1659. /** Given a socket handle, check whether the local address (sockname) of the
  1660. * socket is one that we've connected from before. If so, double-check
  1661. * whether our address has changed and we need to generate keys. If we do,
  1662. * call init_keys().
  1663. */
  1664. /* XXXX Handle IPv6, eventually. */
  1665. static void
  1666. client_check_address_changed(int sock)
  1667. {
  1668. uint32_t iface_ip, ip_out;
  1669. struct sockaddr_in out_addr;
  1670. socklen_t out_addr_len = sizeof(out_addr);
  1671. uint32_t *ip;
  1672. if (!last_interface_ip)
  1673. get_interface_address(&last_interface_ip);
  1674. if (!outgoing_addrs)
  1675. outgoing_addrs = smartlist_create();
  1676. if (getsockname(sock, (struct sockaddr*)&out_addr, &out_addr_len)<0) {
  1677. int e = tor_socket_errno(sock);
  1678. log_warn(LD_NET, "getsockname() failed: %s", tor_socket_strerror(e));
  1679. return;
  1680. }
  1681. /* Okay. If we've used this address previously, we're okay. */
  1682. ip_out = ntohl(out_addr.sin_addr.s_addr);
  1683. SMARTLIST_FOREACH(outgoing_addrs, uint32_t*, ip,
  1684. if (*ip == ip_out) return;
  1685. );
  1686. /* Uh-oh. We haven't connected from this address before. Has the interface
  1687. * address changed? */
  1688. if (get_interface_address(&iface_ip)<0)
  1689. return;
  1690. ip = tor_malloc(sizeof(uint32_t));
  1691. *ip = ip_out;
  1692. if (iface_ip == last_interface_ip) {
  1693. /* Nope, it hasn't changed. Add this address to the list. */
  1694. smartlist_add(outgoing_addrs, ip);
  1695. } else {
  1696. /* The interface changed. We're a client, so we need to regenerate our
  1697. * keys. First, reset the state. */
  1698. log(LOG_NOTICE, LD_NET, "Our IP has changed. Rotating keys...");
  1699. last_interface_ip = iface_ip;
  1700. SMARTLIST_FOREACH(outgoing_addrs, void*, ip, tor_free(ip));
  1701. smartlist_clear(outgoing_addrs);
  1702. smartlist_add(outgoing_addrs, ip);
  1703. /* Okay, now change our keys. */
  1704. init_keys(); /* XXXX NM return value-- safe to ignore? */
  1705. }
  1706. }
  1707. /** Process new bytes that have arrived on conn-\>inbuf.
  1708. *
  1709. * This function just passes conn to the connection-specific
  1710. * connection_*_process_inbuf() function. It also passes in
  1711. * package_partial if wanted.
  1712. */
  1713. static int
  1714. connection_process_inbuf(connection_t *conn, int package_partial)
  1715. {
  1716. tor_assert(conn);
  1717. switch (conn->type) {
  1718. case CONN_TYPE_OR:
  1719. return connection_or_process_inbuf(conn);
  1720. case CONN_TYPE_EXIT:
  1721. case CONN_TYPE_AP:
  1722. return connection_edge_process_inbuf(conn, package_partial);
  1723. case CONN_TYPE_DIR:
  1724. return connection_dir_process_inbuf(conn);
  1725. case CONN_TYPE_DNSWORKER:
  1726. return connection_dns_process_inbuf(conn);
  1727. case CONN_TYPE_CPUWORKER:
  1728. return connection_cpu_process_inbuf(conn);
  1729. case CONN_TYPE_CONTROL:
  1730. return connection_control_process_inbuf(conn);
  1731. default:
  1732. log_err(LD_BUG,"Bug: got unexpected conn type %d.", conn->type);
  1733. tor_fragile_assert();
  1734. return -1;
  1735. }
  1736. }
  1737. /** We just finished flushing bytes from conn-\>outbuf, and there
  1738. * are no more bytes remaining.
  1739. *
  1740. * This function just passes conn to the connection-specific
  1741. * connection_*_finished_flushing() function.
  1742. */
  1743. static int
  1744. connection_finished_flushing(connection_t *conn)
  1745. {
  1746. tor_assert(conn);
  1747. // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
  1748. switch (conn->type) {
  1749. case CONN_TYPE_OR:
  1750. return connection_or_finished_flushing(conn);
  1751. case CONN_TYPE_AP:
  1752. case CONN_TYPE_EXIT:
  1753. return connection_edge_finished_flushing(conn);
  1754. case CONN_TYPE_DIR:
  1755. return connection_dir_finished_flushing(conn);
  1756. case CONN_TYPE_DNSWORKER:
  1757. return connection_dns_finished_flushing(conn);
  1758. case CONN_TYPE_CPUWORKER:
  1759. return connection_cpu_finished_flushing(conn);
  1760. case CONN_TYPE_CONTROL:
  1761. return connection_control_finished_flushing(conn);
  1762. default:
  1763. log_err(LD_BUG,"Bug: got unexpected conn type %d.", conn->type);
  1764. tor_fragile_assert();
  1765. return -1;
  1766. }
  1767. }
  1768. /** Called when our attempt to connect() to another server has just
  1769. * succeeded.
  1770. *
  1771. * This function just passes conn to the connection-specific
  1772. * connection_*_finished_connecting() function.
  1773. */
  1774. static int
  1775. connection_finished_connecting(connection_t *conn)
  1776. {
  1777. tor_assert(conn);
  1778. switch (conn->type)
  1779. {
  1780. case CONN_TYPE_OR:
  1781. return connection_or_finished_connecting(conn);
  1782. case CONN_TYPE_EXIT:
  1783. return connection_edge_finished_connecting(conn);
  1784. case CONN_TYPE_DIR:
  1785. return connection_dir_finished_connecting(conn);
  1786. default:
  1787. log_err(LD_BUG,"Bug: got unexpected conn type %d.", conn->type);
  1788. tor_fragile_assert();
  1789. return -1;
  1790. }
  1791. }
  1792. /** Callback: invoked when a connection reaches an EOF event. */
  1793. static int
  1794. connection_reached_eof(connection_t *conn)
  1795. {
  1796. switch (conn->type) {
  1797. case CONN_TYPE_OR:
  1798. return connection_or_reached_eof(conn);
  1799. case CONN_TYPE_AP:
  1800. case CONN_TYPE_EXIT:
  1801. return connection_edge_reached_eof(conn);
  1802. case CONN_TYPE_DIR:
  1803. return connection_dir_reached_eof(conn);
  1804. case CONN_TYPE_DNSWORKER:
  1805. return connection_dns_reached_eof(conn);
  1806. case CONN_TYPE_CPUWORKER:
  1807. return connection_cpu_reached_eof(conn);
  1808. case CONN_TYPE_CONTROL:
  1809. return connection_control_reached_eof(conn);
  1810. default:
  1811. log_err(LD_BUG,"Bug: got unexpected conn type %d.", conn->type);
  1812. tor_fragile_assert();
  1813. return -1;
  1814. }
  1815. }
  1816. /** Verify that connection <b>conn</b> has all of its invariants
  1817. * correct. Trigger an assert if anything is invalid.
  1818. */
  1819. void
  1820. assert_connection_ok(connection_t *conn, time_t now)
  1821. {
  1822. tor_assert(conn);
  1823. tor_assert(conn->magic == CONNECTION_MAGIC);
  1824. tor_assert(conn->type >= _CONN_TYPE_MIN);
  1825. tor_assert(conn->type <= _CONN_TYPE_MAX);
  1826. if (conn->outbuf_flushlen > 0) {
  1827. tor_assert(connection_is_writing(conn) || conn->wants_to_write);
  1828. }
  1829. if (conn->hold_open_until_flushed)
  1830. tor_assert(conn->marked_for_close);
  1831. /* XXX check: wants_to_read, wants_to_write, s, poll_index,
  1832. * marked_for_close. */
  1833. /* buffers */
  1834. if (!connection_is_listener(conn)) {
  1835. assert_buf_ok(conn->inbuf);
  1836. assert_buf_ok(conn->outbuf);
  1837. }
  1838. /* XXX Fix this; no longer so.*/
  1839. #if 0
  1840. if (conn->type != CONN_TYPE_OR && conn->type != CONN_TYPE_DIR)
  1841. tor_assert(!conn->pkey);
  1842. /* pkey is set if we're a dir client, or if we're an OR in state OPEN
  1843. * connected to another OR.
  1844. */
  1845. #endif
  1846. if (conn->type != CONN_TYPE_OR) {
  1847. tor_assert(!conn->tls);
  1848. } else {
  1849. if (conn->state == OR_CONN_STATE_OPEN) {
  1850. /* tor_assert(conn->bandwidth > 0); */
  1851. /* the above isn't necessarily true: if we just did a TLS
  1852. * handshake but we didn't recognize the other peer, or it
  1853. * gave a bad cert/etc, then we won't have assigned bandwidth,
  1854. * yet it will be open. -RD
  1855. */
  1856. // tor_assert(conn->receiver_bucket >= 0);
  1857. }
  1858. // tor_assert(conn->addr && conn->port);
  1859. tor_assert(conn->address);
  1860. if (conn->state > OR_CONN_STATE_PROXY_READING)
  1861. tor_assert(conn->tls);
  1862. }
  1863. if (! CONN_IS_EDGE(conn)) {
  1864. tor_assert(!conn->stream_id);
  1865. tor_assert(!conn->next_stream);
  1866. tor_assert(!conn->cpath_layer);
  1867. tor_assert(!conn->package_window);
  1868. tor_assert(!conn->deliver_window);
  1869. #if 0
  1870. tor_assert(!conn->done_sending);
  1871. tor_assert(!conn->done_receiving);
  1872. #endif
  1873. } else {
  1874. /* XXX unchecked: package window, deliver window. */
  1875. }
  1876. if (conn->type == CONN_TYPE_AP) {
  1877. tor_assert(conn->socks_request);
  1878. if (conn->state == AP_CONN_STATE_OPEN) {
  1879. tor_assert(conn->socks_request->has_finished);
  1880. if (!conn->marked_for_close) {
  1881. tor_assert(conn->cpath_layer);
  1882. assert_cpath_layer_ok(conn->cpath_layer);
  1883. }
  1884. }
  1885. } else {
  1886. tor_assert(!conn->socks_request);
  1887. }
  1888. if (conn->type == CONN_TYPE_EXIT) {
  1889. tor_assert(conn->purpose == EXIT_PURPOSE_CONNECT ||
  1890. conn->purpose == EXIT_PURPOSE_RESOLVE);
  1891. } else if (conn->type != CONN_TYPE_DIR) {
  1892. tor_assert(!conn->purpose); /* only used for dir types currently */
  1893. }
  1894. if (conn->type != CONN_TYPE_DIR) {
  1895. tor_assert(!conn->requested_resource);
  1896. }
  1897. switch (conn->type)
  1898. {
  1899. case CONN_TYPE_OR_LISTENER:
  1900. case CONN_TYPE_AP_LISTENER:
  1901. case CONN_TYPE_DIR_LISTENER:
  1902. case CONN_TYPE_CONTROL_LISTENER:
  1903. tor_assert(conn->state == LISTENER_STATE_READY);
  1904. break;
  1905. case CONN_TYPE_OR:
  1906. tor_assert(conn->state >= _OR_CONN_STATE_MIN);
  1907. tor_assert(conn->state <= _OR_CONN_STATE_MAX);
  1908. tor_assert(conn->n_circuits >= 0);
  1909. break;
  1910. case CONN_TYPE_EXIT:
  1911. tor_assert(conn->state >= _EXIT_CONN_STATE_MIN);
  1912. tor_assert(conn->state <= _EXIT_CONN_STATE_MAX);
  1913. tor_assert(conn->purpose >= _EXIT_PURPOSE_MIN);
  1914. tor_assert(conn->purpose <= _EXIT_PURPOSE_MAX);
  1915. break;
  1916. case CONN_TYPE_AP:
  1917. tor_assert(conn->state >= _AP_CONN_STATE_MIN);
  1918. tor_assert(conn->state <= _AP_CONN_STATE_MAX);
  1919. tor_assert(conn->socks_request);
  1920. break;
  1921. case CONN_TYPE_DIR:
  1922. tor_assert(conn->state >= _DIR_CONN_STATE_MIN);
  1923. tor_assert(conn->state <= _DIR_CONN_STATE_MAX);
  1924. tor_assert(conn->purpose >= _DIR_PURPOSE_MIN);
  1925. tor_assert(conn->purpose <= _DIR_PURPOSE_MAX);
  1926. break;
  1927. case CONN_TYPE_DNSWORKER:
  1928. tor_assert(conn->state >= _DNSWORKER_STATE_MIN);
  1929. tor_assert(conn->state <= _DNSWORKER_STATE_MAX);
  1930. break;
  1931. case CONN_TYPE_CPUWORKER:
  1932. tor_assert(conn->state >= _CPUWORKER_STATE_MIN);
  1933. tor_assert(conn->state <= _CPUWORKER_STATE_MAX);
  1934. break;
  1935. case CONN_TYPE_CONTROL:
  1936. tor_assert(conn->state >= _CONTROL_CONN_STATE_MIN);
  1937. tor_assert(conn->state <= _CONTROL_CONN_STATE_MAX);
  1938. break;
  1939. default:
  1940. tor_assert(0);
  1941. }
  1942. }