connection.c 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682
  1. /* Copyright 2001 Matej Pfajfar.
  2. * Copyright 2001-2004 Roger Dingledine.
  3. * Copyright 2004 Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char connection_c_id[] = "$Id$";
  7. /**
  8. * \file connection.c
  9. * \brief General high-level functions to handle reading and writing
  10. * on connections.
  11. **/
  12. #include "or.h"
  13. /********* START VARIABLES **********/
  14. /** Array of strings to make conn-\>type human-readable. */
  15. const char *conn_type_to_string[] = {
  16. "", /* 0 */
  17. "OP listener", /* 1 */
  18. "OP", /* 2 */
  19. "OR listener", /* 3 */
  20. "OR", /* 4 */
  21. "Exit", /* 5 */
  22. "App listener",/* 6 */
  23. "App", /* 7 */
  24. "Dir listener",/* 8 */
  25. "Dir", /* 9 */
  26. "DNS worker", /* 10 */
  27. "CPU worker", /* 11 */
  28. "Control listener", /* 12 */
  29. "Control", /* 13 */
  30. };
  31. /** Array of string arrays to make {conn-\>type,conn-\>state} human-readable. */
  32. const char *conn_state_to_string[][_CONN_TYPE_MAX+1] = {
  33. { NULL }, /* no type associated with 0 */
  34. { NULL }, /* op listener, obsolete */
  35. { NULL }, /* op, obsolete */
  36. { "ready" }, /* or listener, 0 */
  37. { "", /* OR, 0 */
  38. "connect()ing", /* 1 */
  39. "handshaking", /* 2 */
  40. "open" }, /* 3 */
  41. { "", /* exit, 0 */
  42. "waiting for dest info", /* 1 */
  43. "connecting", /* 2 */
  44. "open", /* 3 */
  45. "resolve failed" }, /* 4 */
  46. { "ready" }, /* app listener, 0 */
  47. { "", /* 0 */
  48. "", /* 1 */
  49. "", /* 2 */
  50. "", /* 3 */
  51. "", /* 4 */
  52. "awaiting dest info", /* app, 5 */
  53. "waiting for rendezvous desc", /* 6 */
  54. "waiting for safe circuit", /* 7 */
  55. "waiting for connected", /* 8 */
  56. "waiting for resolve", /* 9 */
  57. "open" }, /* 10 */
  58. { "ready" }, /* dir listener, 0 */
  59. { "", /* dir, 0 */
  60. "connecting", /* 1 */
  61. "client sending", /* 2 */
  62. "client reading", /* 3 */
  63. "awaiting command", /* 4 */
  64. "writing" }, /* 5 */
  65. { "", /* dns worker, 0 */
  66. "idle", /* 1 */
  67. "busy" }, /* 2 */
  68. { "", /* cpu worker, 0 */
  69. "idle", /* 1 */
  70. "busy with onion", /* 2 */
  71. "busy with handshake" }, /* 3 */
  72. { "ready" }, /* control listener, 0 */
  73. { "", /* control, 0 */
  74. "ready", /* 1 */
  75. "waiting for authentication", }, /* 2 */
  76. };
  77. /********* END VARIABLES ************/
  78. static int connection_create_listener(const char *bindaddress,
  79. uint16_t bindport, int type);
  80. static int connection_init_accepted_conn(connection_t *conn);
  81. static int connection_handle_listener_read(connection_t *conn, int new_type);
  82. static int connection_receiver_bucket_should_increase(connection_t *conn);
  83. static int connection_finished_flushing(connection_t *conn);
  84. static int connection_finished_connecting(connection_t *conn);
  85. static int connection_reached_eof(connection_t *conn);
  86. static int connection_read_to_buf(connection_t *conn, int *max_to_read);
  87. static int connection_process_inbuf(connection_t *conn, int package_partial);
  88. static int connection_bucket_read_limit(connection_t *conn);
  89. /**************************************************************/
  90. /** Allocate space for a new connection_t. This function just initializes
  91. * conn; you must call connection_add() to link it into the main array.
  92. *
  93. * Set conn-\>type to <b>type</b>. Set conn-\>s and conn-\>poll_index to
  94. * -1 to signify they are not yet assigned.
  95. *
  96. * If conn is not a listener type, allocate buffers for it. If it's
  97. * an AP type, allocate space to store the socks_request.
  98. *
  99. * Assign a pseudorandom next_circ_id between 0 and 2**15.
  100. *
  101. * Initialize conn's timestamps to now.
  102. */
  103. connection_t *connection_new(int type) {
  104. static uint32_t n_connections_allocated = 0;
  105. connection_t *conn;
  106. time_t now = time(NULL);
  107. conn = tor_malloc_zero(sizeof(connection_t));
  108. conn->magic = CONNECTION_MAGIC;
  109. conn->s = -1; /* give it a default of 'not used' */
  110. conn->poll_index = -1; /* also default to 'not used' */
  111. conn->global_identifier = n_connections_allocated++;
  112. conn->type = type;
  113. if (!connection_is_listener(conn)) { /* listeners never use their buf */
  114. conn->inbuf = buf_new();
  115. conn->outbuf = buf_new();
  116. }
  117. if (type == CONN_TYPE_AP) {
  118. conn->socks_request = tor_malloc_zero(sizeof(socks_request_t));
  119. }
  120. conn->next_circ_id = crypto_pseudo_rand_int(1<<15);
  121. conn->timestamp_created = now;
  122. conn->timestamp_lastread = now;
  123. conn->timestamp_lastwritten = now;
  124. return conn;
  125. }
  126. /** Tell libevent that we don't care about <b>conn</b> any more. */
  127. void
  128. connection_unregister(connection_t *conn)
  129. {
  130. if (conn->read_event) {
  131. if (event_del(conn->read_event))
  132. log_fn(LOG_WARN, "Error removing read event for %d", (int)conn->s);
  133. tor_free(conn->read_event);
  134. }
  135. if (conn->write_event) {
  136. if (event_del(conn->write_event))
  137. log_fn(LOG_WARN, "Error removing write event for %d", (int)conn->s);
  138. tor_free(conn->write_event);
  139. }
  140. }
  141. /** Deallocate memory used by <b>conn</b>. Deallocate its buffers if necessary,
  142. * close its socket if necessary, and mark the directory as dirty if <b>conn</b>
  143. * is an OR or OP connection.
  144. */
  145. static void
  146. _connection_free(connection_t *conn) {
  147. tor_assert(conn->magic == CONNECTION_MAGIC);
  148. if (!connection_is_listener(conn)) {
  149. buf_free(conn->inbuf);
  150. buf_free(conn->outbuf);
  151. }
  152. tor_free(conn->address);
  153. tor_free(conn->chosen_exit_name);
  154. if (connection_speaks_cells(conn)) {
  155. if (conn->state == OR_CONN_STATE_OPEN)
  156. directory_set_dirty();
  157. if (conn->tls) {
  158. tor_tls_free(conn->tls);
  159. conn->tls = NULL;
  160. }
  161. }
  162. if (conn->identity_pkey)
  163. crypto_free_pk_env(conn->identity_pkey);
  164. tor_free(conn->nickname);
  165. tor_free(conn->socks_request);
  166. connection_unregister(conn);
  167. if (conn->s >= 0) {
  168. log_fn(LOG_INFO,"closing fd %d.",conn->s);
  169. tor_close_socket(conn->s);
  170. }
  171. memset(conn, 0xAA, sizeof(connection_t)); /* poison memory */
  172. tor_free(conn);
  173. }
  174. /** Make sure <b>conn</b> isn't in any of the global conn lists; then free it.
  175. */
  176. void connection_free(connection_t *conn) {
  177. tor_assert(conn);
  178. tor_assert(!connection_is_on_closeable_list(conn));
  179. tor_assert(!connection_in_array(conn));
  180. _connection_free(conn);
  181. }
  182. /** Call _connection_free() on every connection in our array.
  183. * This is used by cpuworkers and dnsworkers when they fork,
  184. * so they don't keep resources held open (especially sockets).
  185. *
  186. * Don't do the checks in connection_free(), because they will
  187. * fail.
  188. */
  189. void connection_free_all(void) {
  190. int i, n;
  191. connection_t **carray;
  192. get_connection_array(&carray,&n);
  193. for (i=0;i<n;i++)
  194. _connection_free(carray[i]);
  195. }
  196. /** Do any cleanup needed:
  197. * - Directory conns that failed to fetch a rendezvous descriptor
  198. * need to inform pending rendezvous streams.
  199. * - OR conns need to call rep_hist_note_*() to record status.
  200. * - AP conns need to send a socks reject if necessary.
  201. * - Exit conns need to call connection_dns_remove() if necessary.
  202. * - AP and Exit conns need to send an end cell if they can.
  203. * - DNS conns need to fail any resolves that are pending on them.
  204. */
  205. void connection_about_to_close_connection(connection_t *conn)
  206. {
  207. circuit_t *circ;
  208. assert(conn->marked_for_close);
  209. if (CONN_IS_EDGE(conn)) {
  210. if (!conn->has_sent_end) {
  211. log_fn(LOG_WARN,"Harmless bug: Edge connection (marked at %s:%d) hasn't sent end yet?", conn->marked_for_close_file, conn->marked_for_close);
  212. #ifdef TOR_FRAGILE
  213. tor_assert(0);
  214. #endif
  215. }
  216. }
  217. switch (conn->type) {
  218. case CONN_TYPE_DIR:
  219. if (conn->state == DIR_CONN_STATE_CONNECTING) {
  220. /* it's a directory server and connecting failed: forget about
  221. this router */
  222. connection_dir_connect_failed(conn);
  223. }
  224. if (conn->purpose == DIR_PURPOSE_FETCH_RENDDESC)
  225. rend_client_desc_here(conn->rend_query); /* give it a try */
  226. break;
  227. case CONN_TYPE_OR:
  228. /* Remember why we're closing this connection. */
  229. if (conn->state != OR_CONN_STATE_OPEN) {
  230. if (connection_or_nonopen_was_started_here(conn)) {
  231. rep_hist_note_connect_failed(conn->identity_digest, time(NULL));
  232. control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED);
  233. }
  234. } else if (conn->hold_open_until_flushed) {
  235. /* XXXX009 We used to have an arg that told us whether we closed the
  236. * connection on purpose or not. Can we use hold_open_until_flushed
  237. * instead? We only set it when we are intentionally closing a
  238. * connection. -NM
  239. *
  240. * (Of course, now things we set to close which expire rather than
  241. * flushing still get noted as dead, not disconnected. But this is an
  242. * improvement. -NM
  243. */
  244. rep_hist_note_disconnect(conn->identity_digest, time(NULL));
  245. control_event_or_conn_status(conn, OR_CONN_EVENT_CLOSED);
  246. } else if (conn->identity_digest) {
  247. rep_hist_note_connection_died(conn->identity_digest, time(NULL));
  248. control_event_or_conn_status(conn, OR_CONN_EVENT_CLOSED);
  249. }
  250. break;
  251. case CONN_TYPE_AP:
  252. if (conn->socks_request->has_finished == 0) {
  253. /* since conn gets removed right after this function finishes,
  254. * there's no point trying to send back a reply at this point. */
  255. log_fn(LOG_WARN,"Bug: Closing stream without sending back a socks reply.");
  256. } else {
  257. control_event_stream_status(conn, STREAM_EVENT_CLOSED);
  258. }
  259. break;
  260. case CONN_TYPE_EXIT:
  261. if (conn->state == EXIT_CONN_STATE_RESOLVING) {
  262. circ = circuit_get_by_conn(conn);
  263. if (circ)
  264. circuit_detach_stream(circ, conn);
  265. connection_dns_remove(conn);
  266. }
  267. break;
  268. case CONN_TYPE_DNSWORKER:
  269. if (conn->state == DNSWORKER_STATE_BUSY) {
  270. dns_cancel_pending_resolve(conn->address);
  271. }
  272. break;
  273. }
  274. }
  275. /** Close the underlying socket for <b>conn</b>, so we don't try to
  276. * flush it. Must be used in conjunction with (right before)
  277. * connection_mark_for_close().
  278. */
  279. void connection_close_immediate(connection_t *conn)
  280. {
  281. assert_connection_ok(conn,0);
  282. if (conn->s < 0) {
  283. log_fn(LOG_WARN,"Bug: Attempt to close already-closed connection.");
  284. #ifdef TOR_FRAGILE
  285. tor_assert(0);
  286. #endif
  287. return;
  288. }
  289. if (conn->outbuf_flushlen) {
  290. log_fn(LOG_INFO,"fd %d, type %s, state %d, %d bytes on outbuf.",
  291. conn->s, CONN_TYPE_TO_STRING(conn->type),
  292. conn->state, (int)conn->outbuf_flushlen);
  293. }
  294. connection_unregister(conn);
  295. tor_close_socket(conn->s);
  296. conn->s = -1;
  297. if (!connection_is_listener(conn)) {
  298. buf_clear(conn->outbuf);
  299. conn->outbuf_flushlen = 0;
  300. }
  301. }
  302. /** Mark <b>conn</b> to be closed next time we loop through
  303. * conn_close_if_marked() in main.c. */
  304. int
  305. _connection_mark_for_close(connection_t *conn)
  306. {
  307. assert_connection_ok(conn,0);
  308. if (conn->marked_for_close) {
  309. log(LOG_WARN, "Bug: Double mark-for-close on connection.");
  310. #ifdef TOR_FRAGILE
  311. tor_assert(0);
  312. #endif
  313. return -1;
  314. }
  315. conn->marked_for_close = 1;
  316. add_connection_to_closeable_list(conn);
  317. /* in case we're going to be held-open-til-flushed, reset
  318. * the number of seconds since last successful write, so
  319. * we get our whole 15 seconds */
  320. conn->timestamp_lastwritten = time(NULL);
  321. return 0;
  322. }
  323. /** Find each connection that has hold_open_until_flushed set to
  324. * 1 but hasn't written in the past 15 seconds, and set
  325. * hold_open_until_flushed to 0. This means it will get cleaned
  326. * up in the next loop through close_if_marked() in main.c.
  327. */
  328. void connection_expire_held_open(void)
  329. {
  330. connection_t **carray, *conn;
  331. int n, i;
  332. time_t now;
  333. now = time(NULL);
  334. get_connection_array(&carray, &n);
  335. for (i = 0; i < n; ++i) {
  336. conn = carray[i];
  337. /* If we've been holding the connection open, but we haven't written
  338. * for 15 seconds...
  339. */
  340. if (conn->hold_open_until_flushed) {
  341. tor_assert(conn->marked_for_close);
  342. if (now - conn->timestamp_lastwritten >= 15) {
  343. log_fn(LOG_NOTICE,"Giving up on marked_for_close conn that's been flushing for 15s (fd %d, type %s, state %d).",
  344. conn->s, CONN_TYPE_TO_STRING(conn->type), conn->state);
  345. conn->hold_open_until_flushed = 0;
  346. }
  347. }
  348. }
  349. }
  350. /** Bind a new non-blocking socket listening to
  351. * <b>bindaddress</b>:<b>bindport</b>, and add this new connection
  352. * (of type <b>type</b>) to the connection array.
  353. *
  354. * If <b>bindaddress</b> includes a port, we bind on that port; otherwise, we
  355. * use bindport.
  356. */
  357. static int connection_create_listener(const char *bindaddress, uint16_t bindport, int type) {
  358. struct sockaddr_in bindaddr; /* where to bind */
  359. connection_t *conn;
  360. uint16_t usePort;
  361. uint32_t addr;
  362. int s; /* the socket we're going to make */
  363. #ifndef MS_WINDOWS
  364. int one=1;
  365. #endif
  366. memset(&bindaddr,0,sizeof(struct sockaddr_in));
  367. if (parse_addr_port(bindaddress, NULL, &addr, &usePort)<0) {
  368. log_fn(LOG_WARN, "Error parsing/resolving BindAddress %s",bindaddress);
  369. return -1;
  370. }
  371. if (usePort==0)
  372. usePort = bindport;
  373. bindaddr.sin_addr.s_addr = htonl(addr);
  374. bindaddr.sin_family = AF_INET;
  375. bindaddr.sin_port = htons((uint16_t) usePort);
  376. s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
  377. if (s < 0) {
  378. log_fn(LOG_WARN,"Socket creation failed.");
  379. return -1;
  380. } else if (!SOCKET_IS_POLLABLE(s)) {
  381. log_fn(LOG_WARN,"Too many connections; can't create pollable listener.");
  382. tor_close_socket(s);
  383. return -1;
  384. }
  385. #ifndef MS_WINDOWS
  386. /* REUSEADDR on normal places means you can rebind to the port
  387. * right after somebody else has let it go. But REUSEADDR on win32
  388. * means to let you bind to the port _even when somebody else
  389. * already has it bound_. So, don't do that on Win32. */
  390. setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*) &one, sizeof(one));
  391. #endif
  392. if (bind(s,(struct sockaddr *)&bindaddr,sizeof(bindaddr)) < 0) {
  393. log_fn(LOG_WARN,"Could not bind to port %u: %s",usePort,
  394. tor_socket_strerror(tor_socket_errno(s)));
  395. return -1;
  396. }
  397. if (listen(s,SOMAXCONN) < 0) {
  398. log_fn(LOG_WARN,"Could not listen on port %u: %s",usePort,
  399. tor_socket_strerror(tor_socket_errno(s)));
  400. return -1;
  401. }
  402. set_socket_nonblocking(s);
  403. conn = connection_new(type);
  404. conn->s = s;
  405. if (connection_add(conn) < 0) { /* no space, forget it */
  406. log_fn(LOG_WARN,"connection_add failed. Giving up.");
  407. connection_free(conn);
  408. return -1;
  409. }
  410. log_fn(LOG_DEBUG,"%s listening on port %u.",conn_type_to_string[type], usePort);
  411. conn->state = LISTENER_STATE_READY;
  412. connection_start_reading(conn);
  413. return 0;
  414. }
  415. /** The listener connection <b>conn</b> told poll() it wanted to read.
  416. * Call accept() on conn-\>s, and add the new connection if necessary.
  417. */
  418. static int connection_handle_listener_read(connection_t *conn, int new_type) {
  419. int news; /* the new socket */
  420. connection_t *newconn;
  421. /* information about the remote peer when connecting to other routers */
  422. struct sockaddr_in remote;
  423. /* length of the remote address. Must be an int, since accept() needs that. */
  424. int remotelen = sizeof(struct sockaddr_in);
  425. char tmpbuf[INET_NTOA_BUF_LEN];
  426. news = accept(conn->s,(struct sockaddr *)&remote,&remotelen);
  427. if (!SOCKET_IS_POLLABLE(news)) {
  428. /* accept() error, or too many conns to poll */
  429. int e;
  430. if (news>=0) {
  431. /* Too many conns to poll. */
  432. log_fn(LOG_WARN,"Too many connections; couldn't accept connection.");
  433. tor_close_socket(news);
  434. return 0;
  435. }
  436. e = tor_socket_errno(conn->s);
  437. if (ERRNO_IS_ACCEPT_EAGAIN(e)) {
  438. return 0; /* he hung up before we could accept(). that's fine. */
  439. } else if (ERRNO_IS_ACCEPT_RESOURCE_LIMIT(e)) {
  440. log_fn(LOG_NOTICE,"accept failed: %s. Dropping incoming connection.",
  441. tor_socket_strerror(e));
  442. return 0;
  443. }
  444. /* else there was a real error. */
  445. log_fn(LOG_WARN,"accept() failed: %s. Closing listener.",
  446. tor_socket_strerror(e));
  447. connection_mark_for_close(conn);
  448. return -1;
  449. }
  450. log(LOG_INFO,"Connection accepted on socket %d (child of fd %d).",news, conn->s);
  451. set_socket_nonblocking(news);
  452. /* process entrance policies here, before we even create the connection */
  453. if (new_type == CONN_TYPE_AP) {
  454. /* check sockspolicy to see if we should accept it */
  455. if (socks_policy_permits_address(ntohl(remote.sin_addr.s_addr)) == 0) {
  456. tor_inet_ntoa(&remote.sin_addr, tmpbuf, sizeof(tmpbuf));
  457. log_fn(LOG_NOTICE,"Denying socks connection from untrusted address %s.",
  458. tmpbuf);
  459. tor_close_socket(news);
  460. return 0;
  461. }
  462. }
  463. if (new_type == CONN_TYPE_DIR) {
  464. /* check dirpolicy to see if we should accept it */
  465. if (dir_policy_permits_address(ntohl(remote.sin_addr.s_addr)) == 0) {
  466. tor_inet_ntoa(&remote.sin_addr, tmpbuf, sizeof(tmpbuf));
  467. log_fn(LOG_NOTICE,"Denying dir connection from address %s.",
  468. tmpbuf);
  469. tor_close_socket(news);
  470. return 0;
  471. }
  472. }
  473. newconn = connection_new(new_type);
  474. newconn->s = news;
  475. /* remember the remote address */
  476. newconn->address = tor_malloc(INET_NTOA_BUF_LEN);
  477. tor_inet_ntoa(&remote.sin_addr, newconn->address, INET_NTOA_BUF_LEN);
  478. newconn->addr = ntohl(remote.sin_addr.s_addr);
  479. newconn->port = ntohs(remote.sin_port);
  480. if (connection_add(newconn) < 0) { /* no space, forget it */
  481. connection_free(newconn);
  482. return 0; /* no need to tear down the parent */
  483. }
  484. if (connection_init_accepted_conn(newconn) < 0) {
  485. connection_mark_for_close(newconn);
  486. return 0;
  487. }
  488. return 0;
  489. }
  490. /** Initialize states for newly accepted connection <b>conn</b>.
  491. * If conn is an OR, start the tls handshake.
  492. */
  493. static int connection_init_accepted_conn(connection_t *conn) {
  494. connection_start_reading(conn);
  495. switch (conn->type) {
  496. case CONN_TYPE_OR:
  497. return connection_tls_start_handshake(conn, 1);
  498. case CONN_TYPE_AP:
  499. conn->state = AP_CONN_STATE_SOCKS_WAIT;
  500. break;
  501. case CONN_TYPE_DIR:
  502. conn->purpose = DIR_PURPOSE_SERVER;
  503. conn->state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
  504. break;
  505. case CONN_TYPE_CONTROL:
  506. conn->state = CONTROL_CONN_STATE_NEEDAUTH;
  507. break;
  508. }
  509. return 0;
  510. }
  511. /** Take conn, make a nonblocking socket; try to connect to
  512. * addr:port (they arrive in *host order*). If fail, return -1. Else
  513. * assign s to conn->\s: if connected return 1, if EAGAIN return 0.
  514. *
  515. * address is used to make the logs useful.
  516. *
  517. * On success, add conn to the list of polled connections.
  518. */
  519. int connection_connect(connection_t *conn, char *address, uint32_t addr, uint16_t port) {
  520. int s;
  521. struct sockaddr_in dest_addr;
  522. or_options_t *options = get_options();
  523. s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
  524. if (s < 0) {
  525. log_fn(LOG_WARN,"Error creating network socket: %s",
  526. tor_socket_strerror(tor_socket_errno(-1)));
  527. return -1;
  528. } else if (!SOCKET_IS_POLLABLE(s)) {
  529. log_fn(LOG_WARN,
  530. "Too many connections; can't create pollable connection to %s", address);
  531. tor_close_socket(s);
  532. return -1;
  533. }
  534. if (options->OutboundBindAddress) {
  535. struct sockaddr_in ext_addr;
  536. memset(&ext_addr, 0, sizeof(ext_addr));
  537. ext_addr.sin_family = AF_INET;
  538. ext_addr.sin_port = 0;
  539. if (!tor_inet_aton(options->OutboundBindAddress, &ext_addr.sin_addr)) {
  540. log_fn(LOG_WARN,"Outbound bind address '%s' didn't parse. Ignoring.",
  541. options->OutboundBindAddress);
  542. } else {
  543. if (bind(s, (struct sockaddr*)&ext_addr, sizeof(ext_addr)) < 0) {
  544. log_fn(LOG_WARN,"Error binding network socket: %s",
  545. tor_socket_strerror(tor_socket_errno(s)));
  546. return -1;
  547. }
  548. }
  549. }
  550. set_socket_nonblocking(s);
  551. memset(&dest_addr,0,sizeof(dest_addr));
  552. dest_addr.sin_family = AF_INET;
  553. dest_addr.sin_port = htons(port);
  554. dest_addr.sin_addr.s_addr = htonl(addr);
  555. log_fn(LOG_DEBUG,"Connecting to %s:%u.",address,port);
  556. if (connect(s,(struct sockaddr *)&dest_addr,sizeof(dest_addr)) < 0) {
  557. int e = tor_socket_errno(s);
  558. if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
  559. /* yuck. kill it. */
  560. log_fn(LOG_INFO,"Connect() to %s:%u failed: %s",address,port,
  561. tor_socket_strerror(e));
  562. tor_close_socket(s);
  563. return -1;
  564. } else {
  565. /* it's in progress. set state appropriately and return. */
  566. conn->s = s;
  567. if (connection_add(conn) < 0) /* no space, forget it */
  568. return -1;
  569. log_fn(LOG_DEBUG,"connect in progress, socket %d.",s);
  570. return 0;
  571. }
  572. }
  573. /* it succeeded. we're connected. */
  574. log_fn(LOG_INFO,"Connection to %s:%u established.",address,port);
  575. conn->s = s;
  576. if (connection_add(conn) < 0) /* no space, forget it */
  577. return -1;
  578. return 1;
  579. }
  580. /** If there exist any listeners of type <b>type</b> in the connection
  581. * array, mark them for close.
  582. */
  583. static void listener_close_if_present(int type) {
  584. connection_t *conn;
  585. connection_t **carray;
  586. int i,n;
  587. tor_assert(type == CONN_TYPE_OR_LISTENER ||
  588. type == CONN_TYPE_AP_LISTENER ||
  589. type == CONN_TYPE_DIR_LISTENER ||
  590. type == CONN_TYPE_CONTROL_LISTENER);
  591. get_connection_array(&carray,&n);
  592. for (i=0;i<n;i++) {
  593. conn = carray[i];
  594. if (conn->type == type && !conn->marked_for_close) {
  595. connection_close_immediate(conn);
  596. connection_mark_for_close(conn);
  597. }
  598. }
  599. }
  600. /**
  601. * Launch any configured listener connections of type <b>type</b>. (A
  602. * listener is configured if <b>port_option</b> is non-zero. If any
  603. * BindAddress configuration options are given in <b>cfg</b>, create a
  604. * connection binding to each one. Otherwise, create a single
  605. * connection binding to the address <b>default_addr</b>.)
  606. *
  607. * If <b>force</b> is true, close and re-open all listener connections.
  608. * Otherwise, only relaunch the listeners of this type if the number of
  609. * existing connections is not as configured (e.g., because one died).
  610. */
  611. static int retry_listeners(int type, struct config_line_t *cfg,
  612. int port_option, const char *default_addr,
  613. int force)
  614. {
  615. if (!force) {
  616. int want, have, n_conn, i;
  617. struct config_line_t *c;
  618. connection_t *conn;
  619. connection_t **carray;
  620. /* How many should there be? */
  621. if (cfg && port_option) {
  622. want = 0;
  623. for (c = cfg; c; c = c->next)
  624. ++want;
  625. } else if (port_option) {
  626. want = 1;
  627. } else {
  628. want = 0;
  629. }
  630. /* How many are there actually? */
  631. have = 0;
  632. get_connection_array(&carray,&n_conn);
  633. for (i=0;i<n_conn;i++) {
  634. conn = carray[i];
  635. if (conn->type == type && !conn->marked_for_close)
  636. ++have;
  637. }
  638. /* If we have the right number of listeners, do nothing. */
  639. if (have == want)
  640. return 0;
  641. /* Otherwise, warn the user and relaunch. */
  642. log_fn(LOG_NOTICE,"We have %d %s(s) open, but we want %d; relaunching.",
  643. have, conn_type_to_string[type], want);
  644. }
  645. listener_close_if_present(type);
  646. if (port_option) {
  647. if (!cfg) {
  648. if (connection_create_listener(default_addr, (uint16_t) port_option,
  649. type)<0)
  650. return -1;
  651. } else {
  652. for ( ; cfg; cfg = cfg->next) {
  653. if (connection_create_listener(cfg->value, (uint16_t) port_option,
  654. type)<0)
  655. return -1;
  656. }
  657. }
  658. }
  659. return 0;
  660. }
  661. /** (Re)launch listeners for each port you should have open. If
  662. * <b>force</b> is true, close and relaunch all listeners. If <b>force</b>
  663. * is false, then only relaunch listeners when we have the wrong number of
  664. * connections for a given type.
  665. */
  666. int retry_all_listeners(int force) {
  667. or_options_t *options = get_options();
  668. if (retry_listeners(CONN_TYPE_OR_LISTENER, options->ORBindAddress,
  669. options->ORPort, "0.0.0.0", force)<0)
  670. return -1;
  671. if (retry_listeners(CONN_TYPE_DIR_LISTENER, options->DirBindAddress,
  672. options->DirPort, "0.0.0.0", force)<0)
  673. return -1;
  674. if (retry_listeners(CONN_TYPE_AP_LISTENER, options->SocksBindAddress,
  675. options->SocksPort, "127.0.0.1", force)<0)
  676. return -1;
  677. if (retry_listeners(CONN_TYPE_CONTROL_LISTENER, NULL,
  678. options->ControlPort, "127.0.0.1", force)<0)
  679. return -1;
  680. return 0;
  681. }
  682. extern int global_read_bucket, global_write_bucket;
  683. /** How many bytes at most can we read onto this connection? */
  684. static int connection_bucket_read_limit(connection_t *conn) {
  685. int at_most;
  686. /* do a rudimentary round-robin so one circuit can't hog a connection */
  687. if (connection_speaks_cells(conn)) {
  688. at_most = 32*(CELL_NETWORK_SIZE);
  689. } else {
  690. at_most = 32*(RELAY_PAYLOAD_SIZE);
  691. }
  692. if (at_most > global_read_bucket)
  693. at_most = global_read_bucket;
  694. if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN)
  695. if (at_most > conn->receiver_bucket)
  696. at_most = conn->receiver_bucket;
  697. if (at_most < 0)
  698. return 0;
  699. return at_most;
  700. }
  701. /** We just read num_read onto conn. Decrement buckets appropriately. */
  702. static void connection_read_bucket_decrement(connection_t *conn, int num_read) {
  703. global_read_bucket -= num_read; //tor_assert(global_read_bucket >= 0);
  704. if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
  705. conn->receiver_bucket -= num_read; //tor_assert(conn->receiver_bucket >= 0);
  706. }
  707. }
  708. static void connection_consider_empty_buckets(connection_t *conn) {
  709. if (global_read_bucket <= 0) {
  710. log_fn(LOG_DEBUG,"global bucket exhausted. Pausing.");
  711. conn->wants_to_read = 1;
  712. connection_stop_reading(conn);
  713. return;
  714. }
  715. if (connection_speaks_cells(conn) &&
  716. conn->state == OR_CONN_STATE_OPEN &&
  717. conn->receiver_bucket <= 0) {
  718. log_fn(LOG_DEBUG,"receiver bucket exhausted. Pausing.");
  719. conn->wants_to_read = 1;
  720. connection_stop_reading(conn);
  721. }
  722. }
  723. /** Initialize the global read bucket to options->BandwidthBurst,
  724. * and current_time to the current time. */
  725. void connection_bucket_init(void) {
  726. or_options_t *options = get_options();
  727. global_read_bucket = (int)options->BandwidthBurst; /* start it at max traffic */
  728. global_write_bucket = (int)options->BandwidthBurst; /* start it at max traffic */
  729. }
  730. /** A second has rolled over; increment buckets appropriately. */
  731. void connection_bucket_refill(struct timeval *now) {
  732. int i, n;
  733. connection_t *conn;
  734. connection_t **carray;
  735. or_options_t *options = get_options();
  736. /* refill the global buckets */
  737. if (global_read_bucket < (int)options->BandwidthBurst) {
  738. global_read_bucket += (int)options->BandwidthRate;
  739. log_fn(LOG_DEBUG,"global_read_bucket now %d.", global_read_bucket);
  740. }
  741. if (global_write_bucket < (int)options->BandwidthBurst) {
  742. global_write_bucket += (int)options->BandwidthRate;
  743. log_fn(LOG_DEBUG,"global_write_bucket now %d.", global_write_bucket);
  744. }
  745. /* refill the per-connection buckets */
  746. get_connection_array(&carray,&n);
  747. for (i=0;i<n;i++) {
  748. conn = carray[i];
  749. if (connection_receiver_bucket_should_increase(conn)) {
  750. conn->receiver_bucket = conn->bandwidth;
  751. //log_fn(LOG_DEBUG,"Receiver bucket %d now %d.", i, conn->receiver_bucket);
  752. }
  753. if (conn->wants_to_read == 1 /* it's marked to turn reading back on now */
  754. && global_read_bucket > 0 /* and we're allowed to read */
  755. && global_write_bucket > 0 /* and we're allowed to write (XXXX,
  756. * not the best place to check this.) */
  757. && (!connection_speaks_cells(conn) ||
  758. conn->state != OR_CONN_STATE_OPEN ||
  759. conn->receiver_bucket > 0)) {
  760. /* and either a non-cell conn or a cell conn with non-empty bucket */
  761. log_fn(LOG_DEBUG,"waking up conn (fd %d)",conn->s);
  762. conn->wants_to_read = 0;
  763. connection_start_reading(conn);
  764. if (conn->wants_to_write == 1) {
  765. conn->wants_to_write = 0;
  766. connection_start_writing(conn);
  767. }
  768. }
  769. }
  770. }
  771. /** Is the receiver bucket for connection <b>conn</b> low enough that we
  772. * should add another pile of tokens to it?
  773. */
  774. static int connection_receiver_bucket_should_increase(connection_t *conn) {
  775. tor_assert(conn);
  776. if (!connection_speaks_cells(conn))
  777. return 0; /* edge connections don't use receiver_buckets */
  778. if (conn->state != OR_CONN_STATE_OPEN)
  779. return 0; /* only open connections play the rate limiting game */
  780. if (conn->receiver_bucket >= conn->bandwidth)
  781. return 0;
  782. return 1;
  783. }
  784. /** Read bytes from conn->\s and process them.
  785. *
  786. * This function gets called from conn_read() in main.c, either
  787. * when poll() has declared that conn wants to read, or (for OR conns)
  788. * when there are pending TLS bytes.
  789. *
  790. * It calls connection_read_to_buf() to bring in any new bytes,
  791. * and then calls connection_process_inbuf() to process them.
  792. *
  793. * Mark the connection and return -1 if you want to close it, else
  794. * return 0.
  795. */
  796. int connection_handle_read(connection_t *conn) {
  797. int max_to_read=-1, try_to_read;
  798. conn->timestamp_lastread = time(NULL);
  799. switch (conn->type) {
  800. case CONN_TYPE_OR_LISTENER:
  801. return connection_handle_listener_read(conn, CONN_TYPE_OR);
  802. case CONN_TYPE_AP_LISTENER:
  803. return connection_handle_listener_read(conn, CONN_TYPE_AP);
  804. case CONN_TYPE_DIR_LISTENER:
  805. return connection_handle_listener_read(conn, CONN_TYPE_DIR);
  806. case CONN_TYPE_CONTROL_LISTENER:
  807. return connection_handle_listener_read(conn, CONN_TYPE_CONTROL);
  808. }
  809. loop_again:
  810. try_to_read = max_to_read;
  811. tor_assert(!conn->marked_for_close);
  812. if (connection_read_to_buf(conn, &max_to_read) < 0) {
  813. /* There's a read error; kill the connection.*/
  814. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  815. if (CONN_IS_EDGE(conn)) {
  816. connection_edge_end_errno(conn, conn->cpath_layer);
  817. }
  818. connection_mark_for_close(conn);
  819. return -1;
  820. }
  821. if (CONN_IS_EDGE(conn) &&
  822. try_to_read != max_to_read) {
  823. /* instruct it not to try to package partial cells. */
  824. if (connection_process_inbuf(conn, 0) < 0) {
  825. return -1;
  826. }
  827. if (!conn->marked_for_close &&
  828. connection_is_reading(conn) &&
  829. !conn->inbuf_reached_eof &&
  830. max_to_read > 0)
  831. goto loop_again; /* try reading again, in case more is here now */
  832. }
  833. /* one last try, packaging partial cells and all. */
  834. if (!conn->marked_for_close &&
  835. connection_process_inbuf(conn, 1) < 0) {
  836. return -1;
  837. }
  838. if (!conn->marked_for_close &&
  839. conn->inbuf_reached_eof &&
  840. connection_reached_eof(conn) < 0) {
  841. return -1;
  842. }
  843. return 0;
  844. }
  845. /** Pull in new bytes from conn-\>s onto conn-\>inbuf, either
  846. * directly or via TLS. Reduce the token buckets by the number of
  847. * bytes read.
  848. *
  849. * If *max_to_read is -1, then decide it ourselves, else go with the
  850. * value passed to us. When returning, if it's changed, subtract the
  851. * number of bytes we read from *max_to_read.
  852. *
  853. * Return -1 if we want to break conn, else return 0.
  854. */
  855. static int connection_read_to_buf(connection_t *conn, int *max_to_read) {
  856. int result, at_most = *max_to_read;
  857. if (at_most == -1) { /* we need to initialize it */
  858. /* how many bytes are we allowed to read? */
  859. at_most = connection_bucket_read_limit(conn);
  860. }
  861. if (connection_speaks_cells(conn) && conn->state > OR_CONN_STATE_PROXY_READING) {
  862. int pending;
  863. if (conn->state == OR_CONN_STATE_HANDSHAKING) {
  864. /* continue handshaking even if global token bucket is empty */
  865. return connection_tls_continue_handshake(conn);
  866. }
  867. log_fn(LOG_DEBUG,"%d: starting, inbuf_datalen %d (%d pending in tls object). at_most %d.",
  868. conn->s,(int)buf_datalen(conn->inbuf),tor_tls_get_pending_bytes(conn->tls), at_most);
  869. /* else open, or closing */
  870. result = read_to_buf_tls(conn->tls, at_most, conn->inbuf);
  871. switch (result) {
  872. case TOR_TLS_CLOSE:
  873. log_fn(LOG_INFO,"TLS connection closed on read. Closing. (Nickname %s, address %s",
  874. conn->nickname ? conn->nickname : "not set", conn->address);
  875. return -1;
  876. case TOR_TLS_ERROR:
  877. log_fn(LOG_INFO,"tls error. breaking (nickname %s, address %s).",
  878. conn->nickname ? conn->nickname : "not set", conn->address);
  879. return -1;
  880. case TOR_TLS_WANTWRITE:
  881. connection_start_writing(conn);
  882. return 0;
  883. case TOR_TLS_WANTREAD: /* we're already reading */
  884. case TOR_TLS_DONE: /* no data read, so nothing to process */
  885. result = 0;
  886. break; /* so we call bucket_decrement below */
  887. default:
  888. break;
  889. }
  890. pending = tor_tls_get_pending_bytes(conn->tls);
  891. if (pending) {
  892. /* XXXX If we have any pending bytes, read them now. This *can*
  893. * take us over our read alotment, but really we shouldn't be
  894. * believing that SSL bytes are the same as TCP bytes anyway. */
  895. int r2 = read_to_buf_tls(conn->tls, pending, conn->inbuf);
  896. if (r2<0) {
  897. log_fn(LOG_WARN, "Bug: apparently, reading pending bytes can fail.");
  898. return -1;
  899. } else {
  900. result += r2;
  901. }
  902. }
  903. } else {
  904. result = read_to_buf(conn->s, at_most, conn->inbuf,
  905. &conn->inbuf_reached_eof);
  906. // log_fn(LOG_DEBUG,"read_to_buf returned %d.",read_result);
  907. if (result < 0)
  908. return -1;
  909. }
  910. if (result > 0) { /* change *max_to_read */
  911. *max_to_read = at_most - result;
  912. }
  913. if (result > 0 && !is_local_IP(conn->addr)) { /* remember it */
  914. rep_hist_note_bytes_read(result, time(NULL));
  915. connection_read_bucket_decrement(conn, result);
  916. }
  917. /* Call even if result is 0, since the global read bucket may
  918. * have reached 0 on a different conn, and this guy needs to
  919. * know to stop reading. */
  920. connection_consider_empty_buckets(conn);
  921. return 0;
  922. }
  923. /** A pass-through to fetch_from_buf. */
  924. int connection_fetch_from_buf(char *string, size_t len, connection_t *conn) {
  925. return fetch_from_buf(string, len, conn->inbuf);
  926. }
  927. /** Return conn-\>outbuf_flushlen: how many bytes conn wants to flush
  928. * from its outbuf. */
  929. int connection_wants_to_flush(connection_t *conn) {
  930. return conn->outbuf_flushlen;
  931. }
  932. /** Are there too many bytes on edge connection <b>conn</b>'s outbuf to
  933. * send back a relay-level sendme yet? Return 1 if so, 0 if not. Used by
  934. * connection_edge_consider_sending_sendme().
  935. */
  936. int connection_outbuf_too_full(connection_t *conn) {
  937. return (conn->outbuf_flushlen > 10*CELL_PAYLOAD_SIZE);
  938. }
  939. /** Try to flush more bytes onto conn-\>s.
  940. *
  941. * This function gets called either from conn_write() in main.c
  942. * when poll() has declared that conn wants to write, or below
  943. * from connection_write_to_buf() when an entire TLS record is ready.
  944. *
  945. * Update conn-\>timestamp_lastwritten to now, and call flush_buf
  946. * or flush_buf_tls appropriately. If it succeeds and there no more
  947. * more bytes on conn->outbuf, then call connection_finished_flushing
  948. * on it too.
  949. *
  950. * Mark the connection and return -1 if you want to close it, else
  951. * return 0.
  952. */
  953. int connection_handle_write(connection_t *conn) {
  954. int e, len=sizeof(e);
  955. int result;
  956. time_t now = time(NULL);
  957. tor_assert(!connection_is_listener(conn));
  958. conn->timestamp_lastwritten = now;
  959. /* Sometimes, "writable" means "connected". */
  960. if (connection_state_is_connecting(conn)) {
  961. if (getsockopt(conn->s, SOL_SOCKET, SO_ERROR, (void*)&e, &len) < 0) {
  962. log_fn(LOG_WARN,"getsockopt() syscall failed?! Please report to tor-ops.");
  963. if (CONN_IS_EDGE(conn))
  964. connection_edge_end_errno(conn, conn->cpath_layer);
  965. connection_mark_for_close(conn);
  966. return -1;
  967. }
  968. if (e) {
  969. /* some sort of error, but maybe just inprogress still */
  970. if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
  971. log_fn(LOG_INFO,"in-progress connect failed. Removing.");
  972. if (CONN_IS_EDGE(conn))
  973. connection_edge_end_errno(conn, conn->cpath_layer);
  974. connection_close_immediate(conn);
  975. connection_mark_for_close(conn);
  976. /* it's safe to pass OPs to router_mark_as_down(), since it just
  977. * ignores unrecognized routers
  978. */
  979. if (conn->type == CONN_TYPE_OR && !get_options()->HttpsProxy)
  980. router_mark_as_down(conn->identity_digest);
  981. return -1;
  982. } else {
  983. return 0; /* no change, see if next time is better */
  984. }
  985. }
  986. /* The connection is successful. */
  987. if (connection_finished_connecting(conn)<0)
  988. return -1;
  989. }
  990. if (connection_speaks_cells(conn) && conn->state > OR_CONN_STATE_PROXY_READING) {
  991. if (conn->state == OR_CONN_STATE_HANDSHAKING) {
  992. connection_stop_writing(conn);
  993. if (connection_tls_continue_handshake(conn) < 0) {
  994. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  995. connection_mark_for_close(conn);
  996. return -1;
  997. }
  998. return 0;
  999. }
  1000. /* else open, or closing */
  1001. result = flush_buf_tls(conn->tls, conn->outbuf, &conn->outbuf_flushlen);
  1002. switch (result) {
  1003. case TOR_TLS_ERROR:
  1004. case TOR_TLS_CLOSE:
  1005. log_fn(LOG_INFO,result==TOR_TLS_ERROR?
  1006. "tls error. breaking.":"TLS connection closed on flush");
  1007. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  1008. connection_mark_for_close(conn);
  1009. return -1;
  1010. case TOR_TLS_WANTWRITE:
  1011. log_fn(LOG_DEBUG,"wanted write.");
  1012. /* we're already writing */
  1013. return 0;
  1014. case TOR_TLS_WANTREAD:
  1015. /* Make sure to avoid a loop if the receive buckets are empty. */
  1016. log_fn(LOG_DEBUG,"wanted read.");
  1017. if (!connection_is_reading(conn)) {
  1018. connection_stop_writing(conn);
  1019. conn->wants_to_write = 1;
  1020. /* we'll start reading again when the next second arrives,
  1021. * and then also start writing again.
  1022. */
  1023. }
  1024. /* else no problem, we're already reading */
  1025. return 0;
  1026. /* case TOR_TLS_DONE:
  1027. * for TOR_TLS_DONE, fall through to check if the flushlen
  1028. * is empty, so we can stop writing.
  1029. */
  1030. }
  1031. } else {
  1032. result = flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen);
  1033. if (result < 0) {
  1034. if (CONN_IS_EDGE(conn))
  1035. connection_edge_end_errno(conn, conn->cpath_layer);
  1036. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  1037. conn->has_sent_end = 1;
  1038. connection_mark_for_close(conn);
  1039. return -1;
  1040. }
  1041. }
  1042. if (result > 0 && !is_local_IP(conn->addr)) { /* remember it */
  1043. rep_hist_note_bytes_written(result, now);
  1044. global_write_bucket -= result;
  1045. }
  1046. if (!connection_wants_to_flush(conn)) { /* it's done flushing */
  1047. if (connection_finished_flushing(conn) < 0) {
  1048. /* already marked */
  1049. return -1;
  1050. }
  1051. }
  1052. return 0;
  1053. }
  1054. /** Append <b>len</b> bytes of <b>string</b> onto <b>conn</b>'s
  1055. * outbuf, and ask it to start writing.
  1056. */
  1057. void connection_write_to_buf(const char *string, size_t len, connection_t *conn) {
  1058. if (!len)
  1059. return;
  1060. /* if it's marked for close, only allow write if we mean to flush it */
  1061. if (conn->marked_for_close && !conn->hold_open_until_flushed)
  1062. return;
  1063. if (write_to_buf(string, len, conn->outbuf) < 0) {
  1064. if (CONN_IS_EDGE(conn)) {
  1065. /* if it failed, it means we have our package/delivery windows set
  1066. wrong compared to our max outbuf size. close the whole circuit. */
  1067. log_fn(LOG_WARN,"write_to_buf failed. Closing circuit (fd %d).", conn->s);
  1068. circuit_mark_for_close(circuit_get_by_conn(conn));
  1069. } else {
  1070. log_fn(LOG_WARN,"write_to_buf failed. Closing connection (fd %d).", conn->s);
  1071. connection_mark_for_close(conn);
  1072. }
  1073. return;
  1074. }
  1075. connection_start_writing(conn);
  1076. conn->outbuf_flushlen += len;
  1077. }
  1078. /** Return the conn to addr/port that has the most recent
  1079. * timestamp_created, or NULL if no such conn exists. */
  1080. connection_t *connection_exact_get_by_addr_port(uint32_t addr, uint16_t port) {
  1081. int i, n;
  1082. connection_t *conn, *best=NULL;
  1083. connection_t **carray;
  1084. get_connection_array(&carray,&n);
  1085. for (i=0;i<n;i++) {
  1086. conn = carray[i];
  1087. if (conn->addr == addr && conn->port == port && !conn->marked_for_close &&
  1088. (!best || best->timestamp_created < conn->timestamp_created))
  1089. best = conn;
  1090. }
  1091. return best;
  1092. }
  1093. connection_t *connection_get_by_identity_digest(const char *digest, int type)
  1094. {
  1095. int i, n;
  1096. connection_t *conn, *best=NULL;
  1097. connection_t **carray;
  1098. get_connection_array(&carray,&n);
  1099. for (i=0;i<n;i++) {
  1100. conn = carray[i];
  1101. if (conn->type != type)
  1102. continue;
  1103. if (!memcmp(conn->identity_digest, digest, DIGEST_LEN) &&
  1104. !conn->marked_for_close &&
  1105. (!best || best->timestamp_created < conn->timestamp_created))
  1106. best = conn;
  1107. }
  1108. return best;
  1109. }
  1110. /** Return the connection with id <b>id</b> if it is not already
  1111. * marked for close.
  1112. */
  1113. connection_t *
  1114. connection_get_by_global_id(uint32_t id) {
  1115. int i, n;
  1116. connection_t *conn;
  1117. connection_t **carray;
  1118. get_connection_array(&carray,&n);
  1119. for (i=0;i<n;i++) {
  1120. conn = carray[i];
  1121. if (conn->global_identifier == id) {
  1122. if (!conn->marked_for_close)
  1123. return conn;
  1124. else
  1125. return NULL;
  1126. }
  1127. }
  1128. return NULL;
  1129. }
  1130. /** Return a connection of type <b>type</b> that is not marked for
  1131. * close.
  1132. */
  1133. connection_t *connection_get_by_type(int type) {
  1134. int i, n;
  1135. connection_t *conn;
  1136. connection_t **carray;
  1137. get_connection_array(&carray,&n);
  1138. for (i=0;i<n;i++) {
  1139. conn = carray[i];
  1140. if (conn->type == type && !conn->marked_for_close)
  1141. return conn;
  1142. }
  1143. return NULL;
  1144. }
  1145. /** Return a connection of type <b>type</b> that is in state <b>state</b>,
  1146. * and that is not marked for close.
  1147. */
  1148. connection_t *connection_get_by_type_state(int type, int state) {
  1149. int i, n;
  1150. connection_t *conn;
  1151. connection_t **carray;
  1152. get_connection_array(&carray,&n);
  1153. for (i=0;i<n;i++) {
  1154. conn = carray[i];
  1155. if (conn->type == type && conn->state == state && !conn->marked_for_close)
  1156. return conn;
  1157. }
  1158. return NULL;
  1159. }
  1160. /** Return a connection of type <b>type</b> that has purpose <b>purpose</b>,
  1161. * and that is not marked for close.
  1162. */
  1163. connection_t *connection_get_by_type_purpose(int type, int purpose) {
  1164. int i, n;
  1165. connection_t *conn;
  1166. connection_t **carray;
  1167. get_connection_array(&carray,&n);
  1168. for (i=0;i<n;i++) {
  1169. conn = carray[i];
  1170. if (conn->type == type && conn->purpose == purpose && !conn->marked_for_close)
  1171. return conn;
  1172. }
  1173. return NULL;
  1174. }
  1175. /** Return the connection of type <b>type</b> that is in state
  1176. * <b>state</b>, that was written to least recently, and that is not
  1177. * marked for close.
  1178. */
  1179. connection_t *connection_get_by_type_state_lastwritten(int type, int state) {
  1180. int i, n;
  1181. connection_t *conn, *best=NULL;
  1182. connection_t **carray;
  1183. get_connection_array(&carray,&n);
  1184. for (i=0;i<n;i++) {
  1185. conn = carray[i];
  1186. if (conn->type == type && conn->state == state && !conn->marked_for_close)
  1187. if (!best || conn->timestamp_lastwritten < best->timestamp_lastwritten)
  1188. best = conn;
  1189. }
  1190. return best;
  1191. }
  1192. /** Return a connection of type <b>type</b> that has rendquery equal
  1193. * to <b>rendquery</b>, and that is not marked for close. If state
  1194. * is non-zero, conn must be of that state too.
  1195. */
  1196. connection_t *
  1197. connection_get_by_type_state_rendquery(int type, int state, const char *rendquery) {
  1198. int i, n;
  1199. connection_t *conn;
  1200. connection_t **carray;
  1201. get_connection_array(&carray,&n);
  1202. for (i=0;i<n;i++) {
  1203. conn = carray[i];
  1204. if (conn->type == type &&
  1205. !conn->marked_for_close &&
  1206. (!state || state == conn->state) &&
  1207. !rend_cmp_service_ids(rendquery, conn->rend_query))
  1208. return conn;
  1209. }
  1210. return NULL;
  1211. }
  1212. /** Return 1 if <b>conn</b> is a listener conn, else return 0. */
  1213. int connection_is_listener(connection_t *conn) {
  1214. if (conn->type == CONN_TYPE_OR_LISTENER ||
  1215. conn->type == CONN_TYPE_AP_LISTENER ||
  1216. conn->type == CONN_TYPE_DIR_LISTENER ||
  1217. conn->type == CONN_TYPE_CONTROL_LISTENER)
  1218. return 1;
  1219. return 0;
  1220. }
  1221. /** Return 1 if <b>conn</b> is in state "open" and is not marked
  1222. * for close, else return 0.
  1223. */
  1224. int connection_state_is_open(connection_t *conn) {
  1225. tor_assert(conn);
  1226. if (conn->marked_for_close)
  1227. return 0;
  1228. if ((conn->type == CONN_TYPE_OR && conn->state == OR_CONN_STATE_OPEN) ||
  1229. (conn->type == CONN_TYPE_AP && conn->state == AP_CONN_STATE_OPEN) ||
  1230. (conn->type == CONN_TYPE_EXIT && conn->state == EXIT_CONN_STATE_OPEN) ||
  1231. (conn->type == CONN_TYPE_CONTROL && conn->state ==CONTROL_CONN_STATE_OPEN))
  1232. return 1;
  1233. return 0;
  1234. }
  1235. /** Return 1 if conn is in 'connecting' state, else return 0. */
  1236. int connection_state_is_connecting(connection_t *conn) {
  1237. tor_assert(conn);
  1238. if (conn->marked_for_close)
  1239. return 0;
  1240. switch (conn->type)
  1241. {
  1242. case CONN_TYPE_OR:
  1243. return conn->state == OR_CONN_STATE_CONNECTING;
  1244. case CONN_TYPE_EXIT:
  1245. return conn->state == EXIT_CONN_STATE_CONNECTING;
  1246. case CONN_TYPE_DIR:
  1247. return conn->state == DIR_CONN_STATE_CONNECTING;
  1248. }
  1249. return 0;
  1250. }
  1251. /** Write a destroy cell with circ ID <b>circ_id</b> onto OR connection
  1252. * <b>conn</b>.
  1253. *
  1254. * Return 0.
  1255. */
  1256. int connection_send_destroy(uint16_t circ_id, connection_t *conn) {
  1257. cell_t cell;
  1258. tor_assert(conn);
  1259. tor_assert(connection_speaks_cells(conn));
  1260. memset(&cell, 0, sizeof(cell_t));
  1261. cell.circ_id = circ_id;
  1262. cell.command = CELL_DESTROY;
  1263. log_fn(LOG_INFO,"Sending destroy (circID %d).", circ_id);
  1264. connection_or_write_cell_to_buf(&cell, conn);
  1265. return 0;
  1266. }
  1267. /** Process new bytes that have arrived on conn-\>inbuf.
  1268. *
  1269. * This function just passes conn to the connection-specific
  1270. * connection_*_process_inbuf() function. It also passes in
  1271. * package_partial if wanted.
  1272. */
  1273. static int connection_process_inbuf(connection_t *conn, int package_partial) {
  1274. tor_assert(conn);
  1275. switch (conn->type) {
  1276. case CONN_TYPE_OR:
  1277. return connection_or_process_inbuf(conn);
  1278. case CONN_TYPE_EXIT:
  1279. case CONN_TYPE_AP:
  1280. return connection_edge_process_inbuf(conn, package_partial);
  1281. case CONN_TYPE_DIR:
  1282. return connection_dir_process_inbuf(conn);
  1283. case CONN_TYPE_DNSWORKER:
  1284. return connection_dns_process_inbuf(conn);
  1285. case CONN_TYPE_CPUWORKER:
  1286. return connection_cpu_process_inbuf(conn);
  1287. case CONN_TYPE_CONTROL:
  1288. return connection_control_process_inbuf(conn);
  1289. default:
  1290. log_fn(LOG_WARN,"Bug: got unexpected conn type %d.", conn->type);
  1291. #ifdef TOR_FRAGILE
  1292. tor_assert(0);
  1293. #endif
  1294. return -1;
  1295. }
  1296. }
  1297. /** We just finished flushing bytes from conn-\>outbuf, and there
  1298. * are no more bytes remaining.
  1299. *
  1300. * This function just passes conn to the connection-specific
  1301. * connection_*_finished_flushing() function.
  1302. */
  1303. static int connection_finished_flushing(connection_t *conn) {
  1304. tor_assert(conn);
  1305. // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
  1306. switch (conn->type) {
  1307. case CONN_TYPE_OR:
  1308. return connection_or_finished_flushing(conn);
  1309. case CONN_TYPE_AP:
  1310. case CONN_TYPE_EXIT:
  1311. return connection_edge_finished_flushing(conn);
  1312. case CONN_TYPE_DIR:
  1313. return connection_dir_finished_flushing(conn);
  1314. case CONN_TYPE_DNSWORKER:
  1315. return connection_dns_finished_flushing(conn);
  1316. case CONN_TYPE_CPUWORKER:
  1317. return connection_cpu_finished_flushing(conn);
  1318. case CONN_TYPE_CONTROL:
  1319. return connection_control_finished_flushing(conn);
  1320. default:
  1321. log_fn(LOG_WARN,"Bug: got unexpected conn type %d.", conn->type);
  1322. #ifdef TOR_FRAGILE
  1323. tor_assert(0);
  1324. #endif
  1325. return -1;
  1326. }
  1327. }
  1328. /** Called when our attempt to connect() to another server has just
  1329. * succeeded.
  1330. *
  1331. * This function just passes conn to the connection-specific
  1332. * connection_*_finished_connecting() function.
  1333. */
  1334. static int connection_finished_connecting(connection_t *conn)
  1335. {
  1336. tor_assert(conn);
  1337. switch (conn->type)
  1338. {
  1339. case CONN_TYPE_OR:
  1340. return connection_or_finished_connecting(conn);
  1341. case CONN_TYPE_EXIT:
  1342. return connection_edge_finished_connecting(conn);
  1343. case CONN_TYPE_DIR:
  1344. return connection_dir_finished_connecting(conn);
  1345. default:
  1346. log_fn(LOG_WARN,"Bug: got unexpected conn type %d.", conn->type);
  1347. #ifdef TOR_FRAGILE
  1348. tor_assert(0);
  1349. #endif
  1350. return -1;
  1351. }
  1352. }
  1353. static int connection_reached_eof(connection_t *conn)
  1354. {
  1355. switch (conn->type) {
  1356. case CONN_TYPE_OR:
  1357. return connection_or_reached_eof(conn);
  1358. case CONN_TYPE_AP:
  1359. case CONN_TYPE_EXIT:
  1360. return connection_edge_reached_eof(conn);
  1361. case CONN_TYPE_DIR:
  1362. return connection_dir_reached_eof(conn);
  1363. case CONN_TYPE_DNSWORKER:
  1364. return connection_dns_reached_eof(conn);
  1365. case CONN_TYPE_CPUWORKER:
  1366. return connection_cpu_reached_eof(conn);
  1367. case CONN_TYPE_CONTROL:
  1368. return connection_control_reached_eof(conn);
  1369. default:
  1370. log_fn(LOG_WARN,"Bug: got unexpected conn type %d.", conn->type);
  1371. #ifdef TOR_FRAGILE
  1372. tor_assert(0);
  1373. #endif
  1374. return -1;
  1375. }
  1376. }
  1377. /** Verify that connection <b>conn</b> has all of its invariants
  1378. * correct. Trigger an assert if anything is invalid.
  1379. */
  1380. void assert_connection_ok(connection_t *conn, time_t now)
  1381. {
  1382. tor_assert(conn);
  1383. tor_assert(conn->magic == CONNECTION_MAGIC);
  1384. tor_assert(conn->type >= _CONN_TYPE_MIN);
  1385. tor_assert(conn->type <= _CONN_TYPE_MAX);
  1386. if (conn->outbuf_flushlen > 0) {
  1387. tor_assert(connection_is_writing(conn) || conn->wants_to_write);
  1388. }
  1389. if (conn->hold_open_until_flushed)
  1390. tor_assert(conn->marked_for_close);
  1391. /* XXX check: wants_to_read, wants_to_write, s, poll_index,
  1392. * marked_for_close. */
  1393. /* buffers */
  1394. if (!connection_is_listener(conn)) {
  1395. assert_buf_ok(conn->inbuf);
  1396. assert_buf_ok(conn->outbuf);
  1397. }
  1398. #if 0 /* computers often go back in time; no way to know */
  1399. tor_assert(!now || conn->timestamp_lastread <= now);
  1400. tor_assert(!now || conn->timestamp_lastwritten <= now);
  1401. tor_assert(conn->timestamp_created <= conn->timestamp_lastread);
  1402. tor_assert(conn->timestamp_created <= conn->timestamp_lastwritten);
  1403. #endif
  1404. /* XXX Fix this; no longer so.*/
  1405. #if 0
  1406. if (conn->type != CONN_TYPE_OR && conn->type != CONN_TYPE_DIR)
  1407. tor_assert(!conn->pkey);
  1408. /* pkey is set if we're a dir client, or if we're an OR in state OPEN
  1409. * connected to another OR.
  1410. */
  1411. #endif
  1412. if (conn->type != CONN_TYPE_OR) {
  1413. tor_assert(!conn->tls);
  1414. } else {
  1415. if (conn->state == OR_CONN_STATE_OPEN) {
  1416. /* tor_assert(conn->bandwidth > 0); */
  1417. /* the above isn't necessarily true: if we just did a TLS
  1418. * handshake but we didn't recognize the other peer, or it
  1419. * gave a bad cert/etc, then we won't have assigned bandwidth,
  1420. * yet it will be open. -RD
  1421. */
  1422. // tor_assert(conn->receiver_bucket >= 0);
  1423. }
  1424. // tor_assert(conn->addr && conn->port);
  1425. tor_assert(conn->address);
  1426. if (conn->state > OR_CONN_STATE_PROXY_READING)
  1427. tor_assert(conn->tls);
  1428. }
  1429. if (! CONN_IS_EDGE(conn)) {
  1430. tor_assert(!conn->stream_id);
  1431. tor_assert(!conn->next_stream);
  1432. tor_assert(!conn->cpath_layer);
  1433. tor_assert(!conn->package_window);
  1434. tor_assert(!conn->deliver_window);
  1435. tor_assert(!conn->done_sending);
  1436. tor_assert(!conn->done_receiving);
  1437. } else {
  1438. /* XXX unchecked: package window, deliver window. */
  1439. }
  1440. if (conn->type == CONN_TYPE_AP) {
  1441. tor_assert(conn->socks_request);
  1442. if (conn->state == AP_CONN_STATE_OPEN) {
  1443. tor_assert(conn->socks_request->has_finished);
  1444. if (!conn->marked_for_close) {
  1445. tor_assert(conn->cpath_layer);
  1446. assert_cpath_layer_ok(conn->cpath_layer);
  1447. }
  1448. }
  1449. } else {
  1450. tor_assert(!conn->socks_request);
  1451. }
  1452. if (conn->type == CONN_TYPE_EXIT) {
  1453. tor_assert(conn->purpose == EXIT_PURPOSE_CONNECT ||
  1454. conn->purpose == EXIT_PURPOSE_RESOLVE);
  1455. } else if (conn->type != CONN_TYPE_DIR) {
  1456. tor_assert(!conn->purpose); /* only used for dir types currently */
  1457. }
  1458. switch (conn->type)
  1459. {
  1460. case CONN_TYPE_OR_LISTENER:
  1461. case CONN_TYPE_AP_LISTENER:
  1462. case CONN_TYPE_DIR_LISTENER:
  1463. case CONN_TYPE_CONTROL_LISTENER:
  1464. tor_assert(conn->state == LISTENER_STATE_READY);
  1465. break;
  1466. case CONN_TYPE_OR:
  1467. tor_assert(conn->state >= _OR_CONN_STATE_MIN);
  1468. tor_assert(conn->state <= _OR_CONN_STATE_MAX);
  1469. break;
  1470. case CONN_TYPE_EXIT:
  1471. tor_assert(conn->state >= _EXIT_CONN_STATE_MIN);
  1472. tor_assert(conn->state <= _EXIT_CONN_STATE_MAX);
  1473. break;
  1474. case CONN_TYPE_AP:
  1475. tor_assert(conn->state >= _AP_CONN_STATE_MIN);
  1476. tor_assert(conn->state <= _AP_CONN_STATE_MAX);
  1477. tor_assert(conn->socks_request);
  1478. break;
  1479. case CONN_TYPE_DIR:
  1480. tor_assert(conn->state >= _DIR_CONN_STATE_MIN);
  1481. tor_assert(conn->state <= _DIR_CONN_STATE_MAX);
  1482. tor_assert(conn->purpose >= _DIR_PURPOSE_MIN);
  1483. tor_assert(conn->purpose <= _DIR_PURPOSE_MAX);
  1484. break;
  1485. case CONN_TYPE_DNSWORKER:
  1486. tor_assert(conn->state == DNSWORKER_STATE_IDLE ||
  1487. conn->state == DNSWORKER_STATE_BUSY);
  1488. break;
  1489. case CONN_TYPE_CPUWORKER:
  1490. tor_assert(conn->state >= _CPUWORKER_STATE_MIN);
  1491. tor_assert(conn->state <= _CPUWORKER_STATE_MAX);
  1492. break;
  1493. case CONN_TYPE_CONTROL:
  1494. tor_assert(conn->state >= _CONTROL_CONN_STATE_MIN);
  1495. tor_assert(conn->state <= _CONTROL_CONN_STATE_MAX);
  1496. break;
  1497. default:
  1498. tor_assert(0);
  1499. }
  1500. }