connection.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967
  1. /* Copyright 2001,2002,2003 Roger Dingledine, Matej Pfajfar. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. #include "or.h"
  5. /********* START VARIABLES **********/
  6. extern or_options_t options; /* command-line and config-file options */
  7. extern int global_read_bucket;
  8. char *conn_type_to_string[] = {
  9. "", /* 0 */
  10. "OP listener", /* 1 */
  11. "OP", /* 2 */
  12. "OR listener", /* 3 */
  13. "OR", /* 4 */
  14. "Exit", /* 5 */
  15. "App listener",/* 6 */
  16. "App", /* 7 */
  17. "Dir listener",/* 8 */
  18. "Dir", /* 9 */
  19. "DNS worker", /* 10 */
  20. "CPU worker", /* 11 */
  21. };
  22. char *conn_state_to_string[][_CONN_TYPE_MAX+1] = {
  23. { NULL }, /* no type associated with 0 */
  24. { NULL }, /* op listener, obsolete */
  25. { NULL }, /* op, obsolete */
  26. { "ready" }, /* or listener, 0 */
  27. { "", /* OR, 0 */
  28. "connect()ing", /* 1 */
  29. "handshaking", /* 2 */
  30. "open" }, /* 3 */
  31. { "", /* exit, 0 */
  32. "waiting for dest info", /* 1 */
  33. "connecting", /* 2 */
  34. "open" /* 3 */
  35. "resolve failed" }, /* 4 */
  36. { "ready" }, /* app listener, 0 */
  37. { "", /* 0 */
  38. "", /* 1 */
  39. "", /* 2 */
  40. "", /* 3 */
  41. "", /* 4 */
  42. "awaiting dest info", /* app, 5 */
  43. "waiting for safe circuit", /* 6 */
  44. "waiting for connected", /* 7 */
  45. "open" }, /* 8 */
  46. { "ready" }, /* dir listener, 0 */
  47. { "", /* dir, 0 */
  48. "connecting (fetch)", /* 1 */
  49. "connecting (upload)", /* 2 */
  50. "client sending fetch", /* 3 */
  51. "client sending upload", /* 4 */
  52. "client reading fetch", /* 5 */
  53. "client reading upload", /* 6 */
  54. "awaiting command", /* 7 */
  55. "writing" }, /* 8 */
  56. { "", /* dns worker, 0 */
  57. "idle", /* 1 */
  58. "busy" }, /* 2 */
  59. { "", /* cpu worker, 0 */
  60. "idle", /* 1 */
  61. "busy with onion", /* 2 */
  62. "busy with handshake" }, /* 3 */
  63. };
  64. /********* END VARIABLES ************/
  65. static int connection_init_accepted_conn(connection_t *conn);
  66. static int connection_handle_listener_read(connection_t *conn, int new_type);
  67. /**************************************************************/
  68. connection_t *connection_new(int type) {
  69. connection_t *conn;
  70. time_t now = time(NULL);
  71. conn = tor_malloc_zero(sizeof(connection_t));
  72. conn->magic = CONNECTION_MAGIC;
  73. conn->s = -1; /* give it a default of 'not used' */
  74. conn->type = type;
  75. if(!connection_is_listener(conn)) { /* listeners never use their buf */
  76. conn->inbuf = buf_new();
  77. conn->outbuf = buf_new();
  78. }
  79. if (type == CONN_TYPE_AP) {
  80. conn->socks_request = tor_malloc_zero(sizeof(socks_request_t));
  81. }
  82. conn->next_circ_id = crypto_pseudo_rand_int(1<<15);
  83. conn->timestamp_created = now;
  84. conn->timestamp_lastread = now;
  85. conn->timestamp_lastwritten = now;
  86. return conn;
  87. }
  88. void connection_free(connection_t *conn) {
  89. assert(conn);
  90. assert(conn->magic == CONNECTION_MAGIC);
  91. if(!connection_is_listener(conn)) {
  92. buf_free(conn->inbuf);
  93. buf_free(conn->outbuf);
  94. }
  95. tor_free(conn->address);
  96. if(connection_speaks_cells(conn)) {
  97. directory_set_dirty();
  98. if (conn->tls)
  99. tor_tls_free(conn->tls);
  100. }
  101. if (conn->onion_pkey)
  102. crypto_free_pk_env(conn->onion_pkey);
  103. if (conn->link_pkey)
  104. crypto_free_pk_env(conn->link_pkey);
  105. if (conn->identity_pkey)
  106. crypto_free_pk_env(conn->identity_pkey);
  107. tor_free(conn->nickname);
  108. tor_free(conn->socks_request);
  109. if(conn->s >= 0) {
  110. log_fn(LOG_INFO,"closing fd %d.",conn->s);
  111. close(conn->s);
  112. }
  113. memset(conn, 0xAA, sizeof(connection_t)); /* poison memory */
  114. free(conn);
  115. }
  116. void connection_free_all(void) {
  117. int i, n;
  118. connection_t **carray;
  119. get_connection_array(&carray,&n);
  120. for(i=0;i<n;i++)
  121. connection_free(carray[i]);
  122. }
  123. /* Close the underlying socket for conn, so we don't try to flush it.
  124. * Must be used in conjunction with connection_mark_for_close
  125. */
  126. void connection_close_immediate(connection_t *conn)
  127. {
  128. assert_connection_ok(conn,0);
  129. if (conn->s < 0) {
  130. log_fn(LOG_WARN,"Attempt to close already-closed connection.");
  131. return;
  132. }
  133. if (conn->outbuf_flushlen) {
  134. log_fn(LOG_INFO,"Closing connection (fd %d, type %d, state %d) with data on outbuf.",
  135. conn->s, conn->type, conn->state);
  136. }
  137. close(conn->s);
  138. conn->s = -1;
  139. if(!connection_is_listener(conn)) {
  140. buf_clear(conn->outbuf);
  141. conn->outbuf_flushlen = 0;
  142. }
  143. }
  144. int
  145. _connection_mark_for_close(connection_t *conn, char reason)
  146. {
  147. int retval = 0;
  148. assert_connection_ok(conn,0);
  149. if (conn->marked_for_close) {
  150. log(LOG_WARN, "Double mark-for-close on connection.");
  151. return -1;
  152. }
  153. switch (conn->type)
  154. {
  155. case CONN_TYPE_OR_LISTENER:
  156. case CONN_TYPE_AP_LISTENER:
  157. case CONN_TYPE_DIR_LISTENER:
  158. case CONN_TYPE_CPUWORKER:
  159. case CONN_TYPE_DIR:
  160. /* No special processing needed. */
  161. break;
  162. case CONN_TYPE_OR:
  163. /* No special processing needed, I think. */
  164. break;
  165. case CONN_TYPE_EXIT:
  166. case CONN_TYPE_AP:
  167. if (conn->state == EXIT_CONN_STATE_RESOLVING)
  168. connection_dns_remove(conn);
  169. if (!conn->has_sent_end && reason &&
  170. connection_edge_end(conn, reason, conn->cpath_layer) < 0)
  171. retval = -1;
  172. break;
  173. case CONN_TYPE_DNSWORKER:
  174. if (conn->state == DNSWORKER_STATE_BUSY) {
  175. dns_cancel_pending_resolve(conn->address);
  176. }
  177. break;
  178. default:
  179. log(LOG_ERR, "Unknown connection type %d", conn->type);
  180. ;
  181. }
  182. conn->marked_for_close = 1;
  183. return retval;
  184. }
  185. void connection_expire_held_open(void)
  186. {
  187. connection_t **carray, *conn;
  188. int n, i;
  189. time_t now;
  190. now = time(NULL);
  191. get_connection_array(&carray, &n);
  192. for (i = 0; i < n; ++i) {
  193. conn = carray[i];
  194. /* If we've been holding the connection open, but we haven't written
  195. * for 15 seconds...
  196. */
  197. if (conn->hold_open_until_flushed) {
  198. assert(conn->marked_for_close);
  199. if (now - conn->timestamp_lastwritten >= 15) {
  200. log_fn(LOG_WARN,"Giving up on marked_for_close conn that's been flushing for 15s (fd %d, type %d, state %d).", conn->s, conn->type, conn->state);
  201. conn->hold_open_until_flushed = 0;
  202. }
  203. }
  204. }
  205. }
  206. int connection_create_listener(char *bindaddress, uint16_t bindport, int type) {
  207. struct sockaddr_in bindaddr; /* where to bind */
  208. struct hostent *rent;
  209. connection_t *conn;
  210. int s; /* the socket we're going to make */
  211. int one=1;
  212. memset(&bindaddr,0,sizeof(struct sockaddr_in));
  213. bindaddr.sin_family = AF_INET;
  214. bindaddr.sin_port = htons(bindport);
  215. rent = gethostbyname(bindaddress);
  216. if (!rent) {
  217. log_fn(LOG_WARN,"Can't resolve BindAddress %s",bindaddress);
  218. return -1;
  219. }
  220. if(rent->h_length != 4)
  221. return -1; /* XXX complain */
  222. memcpy(&(bindaddr.sin_addr.s_addr),rent->h_addr,rent->h_length);
  223. s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
  224. if (s < 0) {
  225. log_fn(LOG_WARN,"Socket creation failed.");
  226. return -1;
  227. }
  228. setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
  229. if(bind(s,(struct sockaddr *)&bindaddr,sizeof(bindaddr)) < 0) {
  230. log_fn(LOG_WARN,"Could not bind to port %u: %s",bindport,strerror(errno));
  231. return -1;
  232. }
  233. if(listen(s,SOMAXCONN) < 0) {
  234. log_fn(LOG_WARN,"Could not listen on port %u: %s",bindport,strerror(errno));
  235. return -1;
  236. }
  237. set_socket_nonblocking(s);
  238. conn = connection_new(type);
  239. conn->s = s;
  240. if(connection_add(conn) < 0) { /* no space, forget it */
  241. log_fn(LOG_WARN,"connection_add failed. Giving up.");
  242. connection_free(conn);
  243. return -1;
  244. }
  245. log_fn(LOG_DEBUG,"%s listening on port %u.",conn_type_to_string[type], bindport);
  246. conn->state = LISTENER_STATE_READY;
  247. connection_start_reading(conn);
  248. return 0;
  249. }
  250. static int connection_handle_listener_read(connection_t *conn, int new_type) {
  251. int news; /* the new socket */
  252. connection_t *newconn;
  253. struct sockaddr_in remote; /* information about the remote peer when connecting to other routers */
  254. int remotelen = sizeof(struct sockaddr_in); /* length of the remote address */
  255. #ifdef MS_WINDOWS
  256. int e;
  257. #endif
  258. news = accept(conn->s,(struct sockaddr *)&remote,&remotelen);
  259. if (news == -1) { /* accept() error */
  260. if(ERRNO_EAGAIN(errno)) {
  261. #ifdef MS_WINDOWS
  262. e = correct_socket_errno(conn->s);
  263. if (ERRNO_EAGAIN(e))
  264. return 0;
  265. #else
  266. return 0; /* he hung up before we could accept(). that's fine. */
  267. #endif
  268. }
  269. /* else there was a real error. */
  270. log_fn(LOG_WARN,"accept() failed. Closing listener.");
  271. connection_mark_for_close(conn,0);
  272. return -1;
  273. }
  274. log(LOG_INFO,"Connection accepted on socket %d (child of fd %d).",news, conn->s);
  275. set_socket_nonblocking(news);
  276. newconn = connection_new(new_type);
  277. newconn->s = news;
  278. newconn->address = tor_strdup(inet_ntoa(remote.sin_addr)); /* remember the remote address */
  279. newconn->addr = ntohl(remote.sin_addr.s_addr);
  280. newconn->port = ntohs(remote.sin_port);
  281. if(connection_add(newconn) < 0) { /* no space, forget it */
  282. connection_free(newconn);
  283. return 0; /* no need to tear down the parent */
  284. }
  285. if(connection_init_accepted_conn(newconn) < 0) {
  286. connection_mark_for_close(newconn,0);
  287. return 0;
  288. }
  289. return 0;
  290. }
  291. static int connection_init_accepted_conn(connection_t *conn) {
  292. connection_start_reading(conn);
  293. switch(conn->type) {
  294. case CONN_TYPE_OR:
  295. return connection_tls_start_handshake(conn, 1);
  296. case CONN_TYPE_AP:
  297. conn->state = AP_CONN_STATE_SOCKS_WAIT;
  298. break;
  299. case CONN_TYPE_DIR:
  300. conn->state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
  301. break;
  302. }
  303. return 0;
  304. }
  305. /* take conn, make a nonblocking socket; try to connect to
  306. * addr:port (they arrive in *host order*). If fail, return -1. Else
  307. * assign s to conn->s: if connected return 1, if eagain return 0.
  308. * address is used to make the logs useful.
  309. */
  310. int connection_connect(connection_t *conn, char *address, uint32_t addr, uint16_t port) {
  311. int s;
  312. struct sockaddr_in dest_addr;
  313. s=socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
  314. if (s < 0) {
  315. log_fn(LOG_WARN,"Error creating network socket.");
  316. return -1;
  317. }
  318. set_socket_nonblocking(s);
  319. memset(&dest_addr,0,sizeof(dest_addr));
  320. dest_addr.sin_family = AF_INET;
  321. dest_addr.sin_port = htons(port);
  322. dest_addr.sin_addr.s_addr = htonl(addr);
  323. log_fn(LOG_DEBUG,"Connecting to %s:%u.",address,port);
  324. if(connect(s,(struct sockaddr *)&dest_addr,sizeof(dest_addr)) < 0) {
  325. if(!ERRNO_CONN_EINPROGRESS(errno)) {
  326. /* yuck. kill it. */
  327. log_fn(LOG_INFO,"Connect() to %s:%u failed: %s",address,port,strerror(errno));
  328. close(s);
  329. return -1;
  330. } else {
  331. /* it's in progress. set state appropriately and return. */
  332. conn->s = s;
  333. log_fn(LOG_DEBUG,"connect in progress, socket %d.",s);
  334. return 0;
  335. }
  336. }
  337. /* it succeeded. we're connected. */
  338. log_fn(LOG_INFO,"Connection to %s:%u established.",address,port);
  339. conn->s = s;
  340. return 1;
  341. }
  342. static void listener_close_if_present(int type) {
  343. connection_t *conn;
  344. assert(type == CONN_TYPE_OR_LISTENER ||
  345. type == CONN_TYPE_AP_LISTENER ||
  346. type == CONN_TYPE_DIR_LISTENER);
  347. conn = connection_get_by_type(type);
  348. if (conn) {
  349. connection_close_immediate(conn);
  350. connection_mark_for_close(conn,0);
  351. }
  352. }
  353. /* start all connections that should be up but aren't */
  354. int retry_all_connections(void) {
  355. if(options.ORPort) {
  356. router_retry_connections();
  357. }
  358. if(options.ORPort) {
  359. listener_close_if_present(CONN_TYPE_OR_LISTENER);
  360. if(connection_create_listener(options.ORBindAddress, options.ORPort,
  361. CONN_TYPE_OR_LISTENER) < 0)
  362. return -1;
  363. }
  364. if(options.DirPort) {
  365. listener_close_if_present(CONN_TYPE_DIR_LISTENER);
  366. if(connection_create_listener(options.DirBindAddress, options.DirPort,
  367. CONN_TYPE_DIR_LISTENER) < 0)
  368. return -1;
  369. }
  370. if(options.SocksPort) {
  371. listener_close_if_present(CONN_TYPE_AP_LISTENER);
  372. if(connection_create_listener(options.SocksBindAddress, options.SocksPort,
  373. CONN_TYPE_AP_LISTENER) < 0)
  374. return -1;
  375. }
  376. return 0;
  377. }
  378. int connection_handle_read(connection_t *conn) {
  379. conn->timestamp_lastread = time(NULL);
  380. switch(conn->type) {
  381. case CONN_TYPE_OR_LISTENER:
  382. return connection_handle_listener_read(conn, CONN_TYPE_OR);
  383. case CONN_TYPE_AP_LISTENER:
  384. return connection_handle_listener_read(conn, CONN_TYPE_AP);
  385. case CONN_TYPE_DIR_LISTENER:
  386. return connection_handle_listener_read(conn, CONN_TYPE_DIR);
  387. }
  388. if(connection_read_to_buf(conn) < 0) {
  389. if(conn->type == CONN_TYPE_DIR &&
  390. (conn->state == DIR_CONN_STATE_CONNECTING_FETCH ||
  391. conn->state == DIR_CONN_STATE_CONNECTING_UPLOAD)) {
  392. /* it's a directory server and connecting failed: forget about this router */
  393. /* XXX I suspect pollerr may make Windows not get to this point. :( */
  394. router_mark_as_down(conn->nickname);
  395. }
  396. /* There's a read error; kill the connection.*/
  397. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  398. connection_mark_for_close(conn, END_STREAM_REASON_MISC);
  399. return -1;
  400. }
  401. if(connection_process_inbuf(conn) < 0) {
  402. // log_fn(LOG_DEBUG,"connection_process_inbuf returned -1.");
  403. return -1;
  404. }
  405. return 0;
  406. }
  407. /* return -1 if we want to break conn, else return 0 */
  408. int connection_read_to_buf(connection_t *conn) {
  409. int result;
  410. int at_most;
  411. if(options.LinkPadding) {
  412. at_most = global_read_bucket;
  413. } else {
  414. /* do a rudimentary round-robin so one connection can't hog a thickpipe */
  415. if(connection_speaks_cells(conn)) {
  416. at_most = 32*(CELL_NETWORK_SIZE);
  417. } else {
  418. at_most = 32*(RELAY_PAYLOAD_SIZE);
  419. }
  420. if(at_most > global_read_bucket)
  421. at_most = global_read_bucket;
  422. }
  423. if(connection_speaks_cells(conn) && conn->state != OR_CONN_STATE_CONNECTING) {
  424. if(conn->state == OR_CONN_STATE_HANDSHAKING)
  425. return connection_tls_continue_handshake(conn);
  426. /* else open, or closing */
  427. if(at_most > conn->receiver_bucket)
  428. at_most = conn->receiver_bucket;
  429. result = read_to_buf_tls(conn->tls, at_most, conn->inbuf);
  430. switch(result) {
  431. case TOR_TLS_ERROR:
  432. case TOR_TLS_CLOSE:
  433. log_fn(LOG_INFO,"tls error. breaking.");
  434. return -1; /* XXX deal with close better */
  435. case TOR_TLS_WANTWRITE:
  436. connection_start_writing(conn);
  437. return 0;
  438. case TOR_TLS_WANTREAD: /* we're already reading */
  439. case TOR_TLS_DONE: /* no data read, so nothing to process */
  440. return 0;
  441. }
  442. } else {
  443. result = read_to_buf(conn->s, at_most, conn->inbuf,
  444. &conn->inbuf_reached_eof);
  445. // log(LOG_DEBUG,"connection_read_to_buf(): read_to_buf returned %d.",read_result);
  446. if(result < 0)
  447. return -1;
  448. }
  449. global_read_bucket -= result; assert(global_read_bucket >= 0);
  450. if(global_read_bucket == 0) {
  451. log_fn(LOG_DEBUG,"global bucket exhausted. Pausing.");
  452. conn->wants_to_read = 1;
  453. connection_stop_reading(conn);
  454. return 0;
  455. }
  456. if(connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
  457. conn->receiver_bucket -= result; assert(conn->receiver_bucket >= 0);
  458. if(conn->receiver_bucket == 0) {
  459. log_fn(LOG_DEBUG,"receiver bucket exhausted. Pausing.");
  460. conn->wants_to_read = 1;
  461. connection_stop_reading(conn);
  462. return 0;
  463. }
  464. }
  465. return 0;
  466. }
  467. int connection_fetch_from_buf(char *string, int len, connection_t *conn) {
  468. return fetch_from_buf(string, len, conn->inbuf);
  469. }
  470. int connection_find_on_inbuf(char *string, int len, connection_t *conn) {
  471. return find_on_inbuf(string, len, conn->inbuf);
  472. }
  473. int connection_wants_to_flush(connection_t *conn) {
  474. return conn->outbuf_flushlen;
  475. }
  476. int connection_outbuf_too_full(connection_t *conn) {
  477. return (conn->outbuf_flushlen > 10*CELL_PAYLOAD_SIZE);
  478. }
  479. /* return -1 if you want to break the conn, else return 0 */
  480. int connection_handle_write(connection_t *conn) {
  481. assert(!connection_is_listener(conn));
  482. conn->timestamp_lastwritten = time(NULL);
  483. if (connection_speaks_cells(conn) &&
  484. conn->state != OR_CONN_STATE_CONNECTING) {
  485. if (conn->state == OR_CONN_STATE_HANDSHAKING) {
  486. connection_stop_writing(conn);
  487. if(connection_tls_continue_handshake(conn) < 0) {
  488. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  489. connection_mark_for_close(conn, 0);
  490. return -1;
  491. }
  492. return 0;
  493. }
  494. /* else open, or closing */
  495. switch(flush_buf_tls(conn->tls, conn->outbuf, &conn->outbuf_flushlen)) {
  496. case TOR_TLS_ERROR:
  497. case TOR_TLS_CLOSE:
  498. log_fn(LOG_INFO,"tls error. breaking.");
  499. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  500. connection_mark_for_close(conn, 0);
  501. return -1; /* XXX deal with close better */
  502. case TOR_TLS_WANTWRITE:
  503. log_fn(LOG_DEBUG,"wanted write.");
  504. /* we're already writing */
  505. return 0;
  506. case TOR_TLS_WANTREAD:
  507. /* Make sure to avoid a loop if the receive buckets are empty. */
  508. log_fn(LOG_DEBUG,"wanted read.");
  509. if(!connection_is_reading(conn)) {
  510. connection_stop_writing(conn);
  511. conn->wants_to_write = 1;
  512. /* we'll start reading again when the next second arrives,
  513. * and then also start writing again.
  514. */
  515. }
  516. /* else no problem, we're already reading */
  517. return 0;
  518. /* case TOR_TLS_DONE:
  519. * for TOR_TLS_DONE, fall through to check if the flushlen
  520. * is empty, so we can stop writing.
  521. */
  522. }
  523. } else {
  524. if (flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen) < 0) {
  525. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  526. connection_mark_for_close(conn, END_STREAM_REASON_MISC);
  527. return -1;
  528. }
  529. /* conns in CONNECTING state will fall through... */
  530. }
  531. if(!connection_wants_to_flush(conn)) /* it's done flushing */
  532. if(connection_finished_flushing(conn) < 0) /* ...and get handled here. */
  533. return -1;
  534. return 0;
  535. }
  536. void connection_write_to_buf(const char *string, int len, connection_t *conn) {
  537. if(!len || conn->marked_for_close)
  538. return;
  539. if(write_to_buf(string, len, conn->outbuf) < 0) {
  540. log_fn(LOG_WARN,"write_to_buf failed. Closing connection (fd %d).", conn->s);
  541. connection_mark_for_close(conn,0);
  542. return;
  543. }
  544. connection_start_writing(conn);
  545. #define MIN_TLS_FLUSHLEN 15872
  546. /* openssl tls record size is 16383, this is close. The goal here is to
  547. * push data out as soon as we know there's enough for a tls record, so
  548. * during periods of high load we won't read the entire megabyte from
  549. * input before pushing any data out. */
  550. if(connection_speaks_cells(conn) &&
  551. conn->outbuf_flushlen < MIN_TLS_FLUSHLEN &&
  552. conn->outbuf_flushlen+len >= MIN_TLS_FLUSHLEN) {
  553. len -= (MIN_TLS_FLUSHLEN - conn->outbuf_flushlen);
  554. conn->outbuf_flushlen = MIN_TLS_FLUSHLEN;
  555. if(connection_handle_write(conn) < 0) {
  556. log_fn(LOG_WARN,"flushing failed.");
  557. connection_mark_for_close(conn,0);
  558. }
  559. }
  560. if(len > 0) { /* if there's any left over */
  561. conn->outbuf_flushlen += len;
  562. connection_start_writing(conn);
  563. /* because connection_handle_write() above might have stopped writing */
  564. }
  565. }
  566. connection_t *connection_exact_get_by_addr_port(uint32_t addr, uint16_t port) {
  567. int i, n;
  568. connection_t *conn;
  569. connection_t **carray;
  570. get_connection_array(&carray,&n);
  571. for(i=0;i<n;i++) {
  572. conn = carray[i];
  573. if(conn->addr == addr && conn->port == port && !conn->marked_for_close)
  574. return conn;
  575. }
  576. return NULL;
  577. }
  578. connection_t *connection_twin_get_by_addr_port(uint32_t addr, uint16_t port) {
  579. /* Find a connection to the router described by addr and port,
  580. * or alternately any router which knows its key.
  581. * This connection *must* be in 'open' state.
  582. * If not, return NULL.
  583. */
  584. int i, n;
  585. connection_t *conn;
  586. routerinfo_t *router;
  587. connection_t **carray;
  588. /* first check if it's there exactly */
  589. conn = connection_exact_get_by_addr_port(addr,port);
  590. if(conn && connection_state_is_open(conn)) {
  591. log(LOG_DEBUG,"connection_twin_get_by_addr_port(): Found exact match.");
  592. return conn;
  593. }
  594. /* now check if any of the other open connections are a twin for this one */
  595. router = router_get_by_addr_port(addr,port);
  596. if(!router)
  597. return NULL;
  598. get_connection_array(&carray,&n);
  599. for(i=0;i<n;i++) {
  600. conn = carray[i];
  601. assert(conn);
  602. if(connection_state_is_open(conn) &&
  603. !crypto_pk_cmp_keys(conn->onion_pkey, router->onion_pkey)) {
  604. log(LOG_DEBUG,"connection_twin_get_by_addr_port(): Found twin (%s).",conn->address);
  605. return conn;
  606. }
  607. }
  608. return NULL;
  609. }
  610. connection_t *connection_get_by_type(int type) {
  611. int i, n;
  612. connection_t *conn;
  613. connection_t **carray;
  614. get_connection_array(&carray,&n);
  615. for(i=0;i<n;i++) {
  616. conn = carray[i];
  617. if(conn->type == type && !conn->marked_for_close)
  618. return conn;
  619. }
  620. return NULL;
  621. }
  622. connection_t *connection_get_by_type_state(int type, int state) {
  623. int i, n;
  624. connection_t *conn;
  625. connection_t **carray;
  626. get_connection_array(&carray,&n);
  627. for(i=0;i<n;i++) {
  628. conn = carray[i];
  629. if(conn->type == type && conn->state == state && !conn->marked_for_close)
  630. return conn;
  631. }
  632. return NULL;
  633. }
  634. connection_t *connection_get_by_type_state_lastwritten(int type, int state) {
  635. int i, n;
  636. connection_t *conn, *best=NULL;
  637. connection_t **carray;
  638. get_connection_array(&carray,&n);
  639. for(i=0;i<n;i++) {
  640. conn = carray[i];
  641. if(conn->type == type && conn->state == state && !conn->marked_for_close)
  642. if(!best || conn->timestamp_lastwritten < best->timestamp_lastwritten)
  643. best = conn;
  644. }
  645. return best;
  646. }
  647. int connection_receiver_bucket_should_increase(connection_t *conn) {
  648. assert(conn);
  649. if(!connection_speaks_cells(conn))
  650. return 0; /* edge connections don't use receiver_buckets */
  651. if(conn->state != OR_CONN_STATE_OPEN)
  652. return 0; /* only open connections play the rate limiting game */
  653. assert(conn->bandwidth > 0);
  654. if(conn->receiver_bucket > 9*conn->bandwidth)
  655. return 0;
  656. return 1;
  657. }
  658. int connection_is_listener(connection_t *conn) {
  659. if(conn->type == CONN_TYPE_OR_LISTENER ||
  660. conn->type == CONN_TYPE_AP_LISTENER ||
  661. conn->type == CONN_TYPE_DIR_LISTENER)
  662. return 1;
  663. return 0;
  664. }
  665. int connection_state_is_open(connection_t *conn) {
  666. assert(conn);
  667. if(conn->marked_for_close)
  668. return 0;
  669. if((conn->type == CONN_TYPE_OR && conn->state == OR_CONN_STATE_OPEN) ||
  670. (conn->type == CONN_TYPE_AP && conn->state == AP_CONN_STATE_OPEN) ||
  671. (conn->type == CONN_TYPE_EXIT && conn->state == EXIT_CONN_STATE_OPEN))
  672. return 1;
  673. return 0;
  674. }
  675. int connection_send_destroy(uint16_t circ_id, connection_t *conn) {
  676. cell_t cell;
  677. assert(conn);
  678. assert(connection_speaks_cells(conn));
  679. memset(&cell, 0, sizeof(cell_t));
  680. cell.circ_id = circ_id;
  681. cell.command = CELL_DESTROY;
  682. log_fn(LOG_INFO,"Sending destroy (circID %d).", circ_id);
  683. connection_or_write_cell_to_buf(&cell, conn);
  684. return 0;
  685. }
  686. int connection_process_inbuf(connection_t *conn) {
  687. assert(conn);
  688. switch(conn->type) {
  689. case CONN_TYPE_OR:
  690. return connection_or_process_inbuf(conn);
  691. case CONN_TYPE_EXIT:
  692. case CONN_TYPE_AP:
  693. return connection_edge_process_inbuf(conn);
  694. case CONN_TYPE_DIR:
  695. return connection_dir_process_inbuf(conn);
  696. case CONN_TYPE_DNSWORKER:
  697. return connection_dns_process_inbuf(conn);
  698. case CONN_TYPE_CPUWORKER:
  699. return connection_cpu_process_inbuf(conn);
  700. default:
  701. log_fn(LOG_WARN,"got unexpected conn->type %d.", conn->type);
  702. return -1;
  703. }
  704. }
  705. int connection_finished_flushing(connection_t *conn) {
  706. assert(conn);
  707. // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
  708. switch(conn->type) {
  709. case CONN_TYPE_OR:
  710. return connection_or_finished_flushing(conn);
  711. case CONN_TYPE_AP:
  712. case CONN_TYPE_EXIT:
  713. return connection_edge_finished_flushing(conn);
  714. case CONN_TYPE_DIR:
  715. return connection_dir_finished_flushing(conn);
  716. case CONN_TYPE_DNSWORKER:
  717. return connection_dns_finished_flushing(conn);
  718. case CONN_TYPE_CPUWORKER:
  719. return connection_cpu_finished_flushing(conn);
  720. default:
  721. log_fn(LOG_WARN,"got unexpected conn->type %d.", conn->type);
  722. return -1;
  723. }
  724. }
  725. void assert_connection_ok(connection_t *conn, time_t now)
  726. {
  727. assert(conn);
  728. assert(conn->magic == CONNECTION_MAGIC);
  729. assert(conn->type >= _CONN_TYPE_MIN);
  730. assert(conn->type <= _CONN_TYPE_MAX);
  731. if(conn->outbuf_flushlen > 0) {
  732. assert(connection_is_writing(conn) || conn->wants_to_write);
  733. }
  734. if(conn->hold_open_until_flushed)
  735. assert(conn->marked_for_close);
  736. /* XXX check: wants_to_read, wants_to_write, s, poll_index,
  737. * marked_for_close. */
  738. /* buffers */
  739. if (!connection_is_listener(conn)) {
  740. assert_buf_ok(conn->inbuf);
  741. assert_buf_ok(conn->outbuf);
  742. }
  743. assert(!now || conn->timestamp_lastread <= now);
  744. assert(!now || conn->timestamp_lastwritten <= now);
  745. assert(conn->timestamp_created <= conn->timestamp_lastread);
  746. assert(conn->timestamp_created <= conn->timestamp_lastwritten);
  747. /* XXX Fix this; no longer so.*/
  748. #if 0
  749. if(conn->type != CONN_TYPE_OR && conn->type != CONN_TYPE_DIR)
  750. assert(!conn->pkey);
  751. /* pkey is set if we're a dir client, or if we're an OR in state OPEN
  752. * connected to another OR.
  753. */
  754. #endif
  755. if (conn->type != CONN_TYPE_OR) {
  756. assert(!conn->tls);
  757. } else {
  758. if(conn->state == OR_CONN_STATE_OPEN) {
  759. /* assert(conn->bandwidth > 0); */
  760. /* the above isn't necessarily true: if we just did a TLS
  761. * handshake but we didn't recognize the other peer, or it
  762. * gave a bad cert/etc, then we won't have assigned bandwidth,
  763. * yet it will be open. -RD
  764. */
  765. assert(conn->receiver_bucket >= 0);
  766. }
  767. assert(conn->addr && conn->port);
  768. assert(conn->address);
  769. if (conn->state != OR_CONN_STATE_CONNECTING)
  770. assert(conn->tls);
  771. }
  772. if (conn->type != CONN_TYPE_EXIT && conn->type != CONN_TYPE_AP) {
  773. assert(!conn->stream_id);
  774. assert(!conn->next_stream);
  775. assert(!conn->cpath_layer);
  776. assert(!conn->package_window);
  777. assert(!conn->deliver_window);
  778. assert(!conn->done_sending);
  779. assert(!conn->done_receiving);
  780. } else {
  781. if(conn->type == CONN_TYPE_AP && conn->state == AP_CONN_STATE_OPEN)
  782. assert(conn->cpath_layer);
  783. if(conn->cpath_layer)
  784. assert_cpath_layer_ok(conn->cpath_layer);
  785. /* XXX unchecked: package window, deliver window. */
  786. }
  787. if (conn->type != CONN_TYPE_AP) {
  788. assert(!conn->socks_request);
  789. }
  790. switch(conn->type)
  791. {
  792. case CONN_TYPE_OR_LISTENER:
  793. case CONN_TYPE_AP_LISTENER:
  794. case CONN_TYPE_DIR_LISTENER:
  795. assert(conn->state == LISTENER_STATE_READY);
  796. break;
  797. case CONN_TYPE_OR:
  798. assert(conn->state >= _OR_CONN_STATE_MIN &&
  799. conn->state <= _OR_CONN_STATE_MAX);
  800. break;
  801. case CONN_TYPE_EXIT:
  802. assert(conn->state >= _EXIT_CONN_STATE_MIN &&
  803. conn->state <= _EXIT_CONN_STATE_MAX);
  804. break;
  805. case CONN_TYPE_AP:
  806. assert(conn->state >= _AP_CONN_STATE_MIN &&
  807. conn->state <= _AP_CONN_STATE_MAX);
  808. assert(conn->socks_request);
  809. break;
  810. case CONN_TYPE_DIR:
  811. assert(conn->state >= _DIR_CONN_STATE_MIN &&
  812. conn->state <= _DIR_CONN_STATE_MAX);
  813. break;
  814. case CONN_TYPE_DNSWORKER:
  815. assert(conn->state == DNSWORKER_STATE_IDLE ||
  816. conn->state == DNSWORKER_STATE_BUSY);
  817. break;
  818. case CONN_TYPE_CPUWORKER:
  819. assert(conn->state >= _CPUWORKER_STATE_MIN &&
  820. conn->state <= _CPUWORKER_STATE_MAX);
  821. break;
  822. default:
  823. assert(0);
  824. }
  825. }
  826. /*
  827. Local Variables:
  828. mode:c
  829. indent-tabs-mode:nil
  830. c-basic-offset:2
  831. End:
  832. */