connection.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973
  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 (right before) 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 %s, state %d) with data on outbuf.",
  135. conn->s, CONN_TYPE_TO_STRING(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 %s, state %d).",
  201. conn->s, CONN_TYPE_TO_STRING(conn->type), conn->state);
  202. conn->hold_open_until_flushed = 0;
  203. }
  204. }
  205. }
  206. }
  207. int connection_create_listener(char *bindaddress, uint16_t bindport, int type) {
  208. struct sockaddr_in bindaddr; /* where to bind */
  209. struct hostent *rent;
  210. connection_t *conn;
  211. int s; /* the socket we're going to make */
  212. int one=1;
  213. memset(&bindaddr,0,sizeof(struct sockaddr_in));
  214. bindaddr.sin_family = AF_INET;
  215. bindaddr.sin_port = htons(bindport);
  216. rent = gethostbyname(bindaddress);
  217. if (!rent) {
  218. log_fn(LOG_WARN,"Can't resolve BindAddress %s",bindaddress);
  219. return -1;
  220. }
  221. if(rent->h_length != 4)
  222. return -1; /* XXX complain */
  223. memcpy(&(bindaddr.sin_addr.s_addr),rent->h_addr,rent->h_length);
  224. s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
  225. if (s < 0) {
  226. log_fn(LOG_WARN,"Socket creation failed.");
  227. return -1;
  228. }
  229. setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*) &one, sizeof(one));
  230. if(bind(s,(struct sockaddr *)&bindaddr,sizeof(bindaddr)) < 0) {
  231. log_fn(LOG_WARN,"Could not bind to port %u: %s",bindport,strerror(errno));
  232. return -1;
  233. }
  234. if(listen(s,SOMAXCONN) < 0) {
  235. log_fn(LOG_WARN,"Could not listen on port %u: %s",bindport,strerror(errno));
  236. return -1;
  237. }
  238. set_socket_nonblocking(s);
  239. conn = connection_new(type);
  240. conn->s = s;
  241. if(connection_add(conn) < 0) { /* no space, forget it */
  242. log_fn(LOG_WARN,"connection_add failed. Giving up.");
  243. connection_free(conn);
  244. return -1;
  245. }
  246. log_fn(LOG_DEBUG,"%s listening on port %u.",conn_type_to_string[type], bindport);
  247. conn->state = LISTENER_STATE_READY;
  248. connection_start_reading(conn);
  249. return 0;
  250. }
  251. static int connection_handle_listener_read(connection_t *conn, int new_type) {
  252. int news; /* the new socket */
  253. connection_t *newconn;
  254. struct sockaddr_in remote; /* information about the remote peer when connecting to other routers */
  255. int remotelen = sizeof(struct sockaddr_in); /* length of the remote address */
  256. #ifdef MS_WINDOWS
  257. int e;
  258. #endif
  259. news = accept(conn->s,(struct sockaddr *)&remote,&remotelen);
  260. if (news == -1) { /* accept() error */
  261. if(ERRNO_EAGAIN(errno)) {
  262. #ifdef MS_WINDOWS
  263. e = correct_socket_errno(conn->s);
  264. if (ERRNO_EAGAIN(e))
  265. return 0;
  266. #else
  267. return 0; /* he hung up before we could accept(). that's fine. */
  268. #endif
  269. }
  270. /* else there was a real error. */
  271. log_fn(LOG_WARN,"accept() failed. Closing listener.");
  272. connection_mark_for_close(conn,0);
  273. return -1;
  274. }
  275. log(LOG_INFO,"Connection accepted on socket %d (child of fd %d).",news, conn->s);
  276. set_socket_nonblocking(news);
  277. newconn = connection_new(new_type);
  278. newconn->s = news;
  279. newconn->address = tor_strdup(inet_ntoa(remote.sin_addr)); /* remember the remote address */
  280. newconn->addr = ntohl(remote.sin_addr.s_addr);
  281. newconn->port = ntohs(remote.sin_port);
  282. if(connection_add(newconn) < 0) { /* no space, forget it */
  283. connection_free(newconn);
  284. return 0; /* no need to tear down the parent */
  285. }
  286. if(connection_init_accepted_conn(newconn) < 0) {
  287. connection_mark_for_close(newconn,0);
  288. return 0;
  289. }
  290. return 0;
  291. }
  292. static int connection_init_accepted_conn(connection_t *conn) {
  293. connection_start_reading(conn);
  294. switch(conn->type) {
  295. case CONN_TYPE_OR:
  296. return connection_tls_start_handshake(conn, 1);
  297. case CONN_TYPE_AP:
  298. conn->state = AP_CONN_STATE_SOCKS_WAIT;
  299. break;
  300. case CONN_TYPE_DIR:
  301. conn->state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
  302. break;
  303. }
  304. return 0;
  305. }
  306. /* take conn, make a nonblocking socket; try to connect to
  307. * addr:port (they arrive in *host order*). If fail, return -1. Else
  308. * assign s to conn->s: if connected return 1, if eagain return 0.
  309. * address is used to make the logs useful.
  310. */
  311. int connection_connect(connection_t *conn, char *address, uint32_t addr, uint16_t port) {
  312. int s;
  313. struct sockaddr_in dest_addr;
  314. s=socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
  315. if (s < 0) {
  316. log_fn(LOG_WARN,"Error creating network socket.");
  317. return -1;
  318. }
  319. set_socket_nonblocking(s);
  320. memset(&dest_addr,0,sizeof(dest_addr));
  321. dest_addr.sin_family = AF_INET;
  322. dest_addr.sin_port = htons(port);
  323. dest_addr.sin_addr.s_addr = htonl(addr);
  324. log_fn(LOG_DEBUG,"Connecting to %s:%u.",address,port);
  325. if(connect(s,(struct sockaddr *)&dest_addr,sizeof(dest_addr)) < 0) {
  326. if(!ERRNO_CONN_EINPROGRESS(errno)) {
  327. /* yuck. kill it. */
  328. log_fn(LOG_INFO,"Connect() to %s:%u failed: %s",address,port,strerror(errno));
  329. close(s);
  330. return -1;
  331. } else {
  332. /* it's in progress. set state appropriately and return. */
  333. conn->s = s;
  334. log_fn(LOG_DEBUG,"connect in progress, socket %d.",s);
  335. return 0;
  336. }
  337. }
  338. /* it succeeded. we're connected. */
  339. log_fn(LOG_INFO,"Connection to %s:%u established.",address,port);
  340. conn->s = s;
  341. return 1;
  342. }
  343. static void listener_close_if_present(int type) {
  344. connection_t *conn;
  345. assert(type == CONN_TYPE_OR_LISTENER ||
  346. type == CONN_TYPE_AP_LISTENER ||
  347. type == CONN_TYPE_DIR_LISTENER);
  348. conn = connection_get_by_type(type);
  349. if (conn) {
  350. connection_close_immediate(conn);
  351. connection_mark_for_close(conn,0);
  352. }
  353. }
  354. /* start all connections that should be up but aren't */
  355. int retry_all_connections(void) {
  356. if(options.ORPort) {
  357. router_retry_connections();
  358. }
  359. if(options.ORPort) {
  360. listener_close_if_present(CONN_TYPE_OR_LISTENER);
  361. if(connection_create_listener(options.ORBindAddress,
  362. (uint16_t) options.ORPort,
  363. CONN_TYPE_OR_LISTENER) < 0)
  364. return -1;
  365. }
  366. if(options.DirPort) {
  367. listener_close_if_present(CONN_TYPE_DIR_LISTENER);
  368. if(connection_create_listener(options.DirBindAddress,
  369. (uint16_t) options.DirPort,
  370. CONN_TYPE_DIR_LISTENER) < 0)
  371. return -1;
  372. }
  373. if(options.SocksPort) {
  374. listener_close_if_present(CONN_TYPE_AP_LISTENER);
  375. if(connection_create_listener(options.SocksBindAddress,
  376. (uint16_t) options.SocksPort,
  377. CONN_TYPE_AP_LISTENER) < 0)
  378. return -1;
  379. }
  380. return 0;
  381. }
  382. int connection_handle_read(connection_t *conn) {
  383. conn->timestamp_lastread = time(NULL);
  384. switch(conn->type) {
  385. case CONN_TYPE_OR_LISTENER:
  386. return connection_handle_listener_read(conn, CONN_TYPE_OR);
  387. case CONN_TYPE_AP_LISTENER:
  388. return connection_handle_listener_read(conn, CONN_TYPE_AP);
  389. case CONN_TYPE_DIR_LISTENER:
  390. return connection_handle_listener_read(conn, CONN_TYPE_DIR);
  391. }
  392. if(connection_read_to_buf(conn) < 0) {
  393. if(conn->type == CONN_TYPE_DIR &&
  394. (conn->state == DIR_CONN_STATE_CONNECTING_FETCH ||
  395. conn->state == DIR_CONN_STATE_CONNECTING_UPLOAD)) {
  396. /* it's a directory server and connecting failed: forget about this router */
  397. /* XXX I suspect pollerr may make Windows not get to this point. :( */
  398. router_mark_as_down(conn->nickname);
  399. }
  400. /* There's a read error; kill the connection.*/
  401. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  402. connection_mark_for_close(conn, END_STREAM_REASON_MISC);
  403. return -1;
  404. }
  405. if(connection_process_inbuf(conn) < 0) {
  406. // log_fn(LOG_DEBUG,"connection_process_inbuf returned -1.");
  407. return -1;
  408. }
  409. return 0;
  410. }
  411. /* return -1 if we want to break conn, else return 0 */
  412. int connection_read_to_buf(connection_t *conn) {
  413. int result;
  414. int at_most;
  415. if(options.LinkPadding) {
  416. at_most = global_read_bucket;
  417. } else {
  418. /* do a rudimentary round-robin so one connection can't hog a thickpipe */
  419. if(connection_speaks_cells(conn)) {
  420. at_most = 32*(CELL_NETWORK_SIZE);
  421. } else {
  422. at_most = 32*(RELAY_PAYLOAD_SIZE);
  423. }
  424. if(at_most > global_read_bucket)
  425. at_most = global_read_bucket;
  426. }
  427. if(connection_speaks_cells(conn) && conn->state != OR_CONN_STATE_CONNECTING) {
  428. if(conn->state == OR_CONN_STATE_HANDSHAKING)
  429. return connection_tls_continue_handshake(conn);
  430. /* else open, or closing */
  431. if(at_most > conn->receiver_bucket)
  432. at_most = conn->receiver_bucket;
  433. result = read_to_buf_tls(conn->tls, at_most, conn->inbuf);
  434. switch(result) {
  435. case TOR_TLS_ERROR:
  436. case TOR_TLS_CLOSE:
  437. log_fn(LOG_INFO,"tls error. breaking.");
  438. return -1; /* XXX deal with close better */
  439. case TOR_TLS_WANTWRITE:
  440. connection_start_writing(conn);
  441. return 0;
  442. case TOR_TLS_WANTREAD: /* we're already reading */
  443. case TOR_TLS_DONE: /* no data read, so nothing to process */
  444. return 0;
  445. }
  446. } else {
  447. result = read_to_buf(conn->s, at_most, conn->inbuf,
  448. &conn->inbuf_reached_eof);
  449. // log(LOG_DEBUG,"connection_read_to_buf(): read_to_buf returned %d.",read_result);
  450. if(result < 0)
  451. return -1;
  452. }
  453. global_read_bucket -= result; assert(global_read_bucket >= 0);
  454. if(global_read_bucket == 0) {
  455. log_fn(LOG_DEBUG,"global bucket exhausted. Pausing.");
  456. conn->wants_to_read = 1;
  457. connection_stop_reading(conn);
  458. return 0;
  459. }
  460. if(connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
  461. conn->receiver_bucket -= result; assert(conn->receiver_bucket >= 0);
  462. if(conn->receiver_bucket == 0) {
  463. log_fn(LOG_DEBUG,"receiver bucket exhausted. Pausing.");
  464. conn->wants_to_read = 1;
  465. connection_stop_reading(conn);
  466. return 0;
  467. }
  468. }
  469. return 0;
  470. }
  471. int connection_fetch_from_buf(char *string, int len, connection_t *conn) {
  472. return fetch_from_buf(string, len, conn->inbuf);
  473. }
  474. int connection_find_on_inbuf(char *string, int len, connection_t *conn) {
  475. return find_on_inbuf(string, len, conn->inbuf);
  476. }
  477. int connection_wants_to_flush(connection_t *conn) {
  478. return conn->outbuf_flushlen;
  479. }
  480. int connection_outbuf_too_full(connection_t *conn) {
  481. return (conn->outbuf_flushlen > 10*CELL_PAYLOAD_SIZE);
  482. }
  483. /* return -1 if you want to break the conn, else return 0 */
  484. int connection_handle_write(connection_t *conn) {
  485. assert(!connection_is_listener(conn));
  486. conn->timestamp_lastwritten = time(NULL);
  487. if (connection_speaks_cells(conn) &&
  488. conn->state != OR_CONN_STATE_CONNECTING) {
  489. if (conn->state == OR_CONN_STATE_HANDSHAKING) {
  490. connection_stop_writing(conn);
  491. if(connection_tls_continue_handshake(conn) < 0) {
  492. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  493. connection_mark_for_close(conn, 0);
  494. return -1;
  495. }
  496. return 0;
  497. }
  498. /* else open, or closing */
  499. switch(flush_buf_tls(conn->tls, conn->outbuf, &conn->outbuf_flushlen)) {
  500. case TOR_TLS_ERROR:
  501. case TOR_TLS_CLOSE:
  502. log_fn(LOG_INFO,"tls error. breaking.");
  503. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  504. connection_mark_for_close(conn, 0);
  505. return -1; /* XXX deal with close better */
  506. case TOR_TLS_WANTWRITE:
  507. log_fn(LOG_DEBUG,"wanted write.");
  508. /* we're already writing */
  509. return 0;
  510. case TOR_TLS_WANTREAD:
  511. /* Make sure to avoid a loop if the receive buckets are empty. */
  512. log_fn(LOG_DEBUG,"wanted read.");
  513. if(!connection_is_reading(conn)) {
  514. connection_stop_writing(conn);
  515. conn->wants_to_write = 1;
  516. /* we'll start reading again when the next second arrives,
  517. * and then also start writing again.
  518. */
  519. }
  520. /* else no problem, we're already reading */
  521. return 0;
  522. /* case TOR_TLS_DONE:
  523. * for TOR_TLS_DONE, fall through to check if the flushlen
  524. * is empty, so we can stop writing.
  525. */
  526. }
  527. } else {
  528. if (flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen) < 0) {
  529. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  530. connection_mark_for_close(conn, END_STREAM_REASON_MISC);
  531. return -1;
  532. }
  533. /* conns in CONNECTING state will fall through... */
  534. }
  535. if(!connection_wants_to_flush(conn)) /* it's done flushing */
  536. if(connection_finished_flushing(conn) < 0) /* ...and get handled here. */
  537. return -1;
  538. return 0;
  539. }
  540. void connection_write_to_buf(const char *string, int len, connection_t *conn) {
  541. if(!len || conn->marked_for_close)
  542. return;
  543. if(write_to_buf(string, len, conn->outbuf) < 0) {
  544. log_fn(LOG_WARN,"write_to_buf failed. Closing connection (fd %d).", conn->s);
  545. connection_mark_for_close(conn,0);
  546. return;
  547. }
  548. connection_start_writing(conn);
  549. #define MIN_TLS_FLUSHLEN 15872
  550. /* openssl tls record size is 16383, this is close. The goal here is to
  551. * push data out as soon as we know there's enough for a tls record, so
  552. * during periods of high load we won't read the entire megabyte from
  553. * input before pushing any data out. */
  554. if(connection_speaks_cells(conn) &&
  555. conn->outbuf_flushlen < MIN_TLS_FLUSHLEN &&
  556. conn->outbuf_flushlen+len >= MIN_TLS_FLUSHLEN) {
  557. len -= (MIN_TLS_FLUSHLEN - conn->outbuf_flushlen);
  558. conn->outbuf_flushlen = MIN_TLS_FLUSHLEN;
  559. if(connection_handle_write(conn) < 0) {
  560. log_fn(LOG_WARN,"flushing failed.");
  561. connection_mark_for_close(conn,0);
  562. }
  563. }
  564. if(len > 0) { /* if there's any left over */
  565. conn->outbuf_flushlen += len;
  566. connection_start_writing(conn);
  567. /* because connection_handle_write() above might have stopped writing */
  568. }
  569. }
  570. connection_t *connection_exact_get_by_addr_port(uint32_t addr, uint16_t port) {
  571. int i, n;
  572. connection_t *conn;
  573. connection_t **carray;
  574. get_connection_array(&carray,&n);
  575. for(i=0;i<n;i++) {
  576. conn = carray[i];
  577. if(conn->addr == addr && conn->port == port && !conn->marked_for_close)
  578. return conn;
  579. }
  580. return NULL;
  581. }
  582. connection_t *connection_twin_get_by_addr_port(uint32_t addr, uint16_t port) {
  583. /* Find a connection to the router described by addr and port,
  584. * or alternately any router which knows its key.
  585. * This connection *must* be in 'open' state.
  586. * If not, return NULL.
  587. */
  588. int i, n;
  589. connection_t *conn;
  590. routerinfo_t *router;
  591. connection_t **carray;
  592. /* first check if it's there exactly */
  593. conn = connection_exact_get_by_addr_port(addr,port);
  594. if(conn && connection_state_is_open(conn)) {
  595. log(LOG_DEBUG,"connection_twin_get_by_addr_port(): Found exact match.");
  596. return conn;
  597. }
  598. /* now check if any of the other open connections are a twin for this one */
  599. router = router_get_by_addr_port(addr,port);
  600. if(!router)
  601. return NULL;
  602. get_connection_array(&carray,&n);
  603. for(i=0;i<n;i++) {
  604. conn = carray[i];
  605. assert(conn);
  606. if(connection_state_is_open(conn) &&
  607. !crypto_pk_cmp_keys(conn->onion_pkey, router->onion_pkey)) {
  608. log(LOG_DEBUG,"connection_twin_get_by_addr_port(): Found twin (%s).",conn->address);
  609. return conn;
  610. }
  611. }
  612. return NULL;
  613. }
  614. connection_t *connection_get_by_type(int type) {
  615. int i, n;
  616. connection_t *conn;
  617. connection_t **carray;
  618. get_connection_array(&carray,&n);
  619. for(i=0;i<n;i++) {
  620. conn = carray[i];
  621. if(conn->type == type && !conn->marked_for_close)
  622. return conn;
  623. }
  624. return NULL;
  625. }
  626. connection_t *connection_get_by_type_state(int type, int state) {
  627. int i, n;
  628. connection_t *conn;
  629. connection_t **carray;
  630. get_connection_array(&carray,&n);
  631. for(i=0;i<n;i++) {
  632. conn = carray[i];
  633. if(conn->type == type && conn->state == state && !conn->marked_for_close)
  634. return conn;
  635. }
  636. return NULL;
  637. }
  638. connection_t *connection_get_by_type_state_lastwritten(int type, int state) {
  639. int i, n;
  640. connection_t *conn, *best=NULL;
  641. connection_t **carray;
  642. get_connection_array(&carray,&n);
  643. for(i=0;i<n;i++) {
  644. conn = carray[i];
  645. if(conn->type == type && conn->state == state && !conn->marked_for_close)
  646. if(!best || conn->timestamp_lastwritten < best->timestamp_lastwritten)
  647. best = conn;
  648. }
  649. return best;
  650. }
  651. int connection_receiver_bucket_should_increase(connection_t *conn) {
  652. assert(conn);
  653. if(!connection_speaks_cells(conn))
  654. return 0; /* edge connections don't use receiver_buckets */
  655. if(conn->state != OR_CONN_STATE_OPEN)
  656. return 0; /* only open connections play the rate limiting game */
  657. assert(conn->bandwidth > 0);
  658. if(conn->receiver_bucket > 9*conn->bandwidth)
  659. return 0;
  660. return 1;
  661. }
  662. int connection_is_listener(connection_t *conn) {
  663. if(conn->type == CONN_TYPE_OR_LISTENER ||
  664. conn->type == CONN_TYPE_AP_LISTENER ||
  665. conn->type == CONN_TYPE_DIR_LISTENER)
  666. return 1;
  667. return 0;
  668. }
  669. int connection_state_is_open(connection_t *conn) {
  670. assert(conn);
  671. if(conn->marked_for_close)
  672. return 0;
  673. if((conn->type == CONN_TYPE_OR && conn->state == OR_CONN_STATE_OPEN) ||
  674. (conn->type == CONN_TYPE_AP && conn->state == AP_CONN_STATE_OPEN) ||
  675. (conn->type == CONN_TYPE_EXIT && conn->state == EXIT_CONN_STATE_OPEN))
  676. return 1;
  677. return 0;
  678. }
  679. int connection_send_destroy(uint16_t circ_id, connection_t *conn) {
  680. cell_t cell;
  681. assert(conn);
  682. assert(connection_speaks_cells(conn));
  683. memset(&cell, 0, sizeof(cell_t));
  684. cell.circ_id = circ_id;
  685. cell.command = CELL_DESTROY;
  686. log_fn(LOG_INFO,"Sending destroy (circID %d).", circ_id);
  687. connection_or_write_cell_to_buf(&cell, conn);
  688. return 0;
  689. }
  690. int connection_process_inbuf(connection_t *conn) {
  691. assert(conn);
  692. switch(conn->type) {
  693. case CONN_TYPE_OR:
  694. return connection_or_process_inbuf(conn);
  695. case CONN_TYPE_EXIT:
  696. case CONN_TYPE_AP:
  697. return connection_edge_process_inbuf(conn);
  698. case CONN_TYPE_DIR:
  699. return connection_dir_process_inbuf(conn);
  700. case CONN_TYPE_DNSWORKER:
  701. return connection_dns_process_inbuf(conn);
  702. case CONN_TYPE_CPUWORKER:
  703. return connection_cpu_process_inbuf(conn);
  704. default:
  705. log_fn(LOG_WARN,"got unexpected conn->type %d.", conn->type);
  706. return -1;
  707. }
  708. }
  709. int connection_finished_flushing(connection_t *conn) {
  710. assert(conn);
  711. // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
  712. switch(conn->type) {
  713. case CONN_TYPE_OR:
  714. return connection_or_finished_flushing(conn);
  715. case CONN_TYPE_AP:
  716. case CONN_TYPE_EXIT:
  717. return connection_edge_finished_flushing(conn);
  718. case CONN_TYPE_DIR:
  719. return connection_dir_finished_flushing(conn);
  720. case CONN_TYPE_DNSWORKER:
  721. return connection_dns_finished_flushing(conn);
  722. case CONN_TYPE_CPUWORKER:
  723. return connection_cpu_finished_flushing(conn);
  724. default:
  725. log_fn(LOG_WARN,"got unexpected conn->type %d.", conn->type);
  726. return -1;
  727. }
  728. }
  729. void assert_connection_ok(connection_t *conn, time_t now)
  730. {
  731. assert(conn);
  732. assert(conn->magic == CONNECTION_MAGIC);
  733. assert(conn->type >= _CONN_TYPE_MIN);
  734. assert(conn->type <= _CONN_TYPE_MAX);
  735. if(conn->outbuf_flushlen > 0) {
  736. assert(connection_is_writing(conn) || conn->wants_to_write);
  737. }
  738. if(conn->hold_open_until_flushed)
  739. assert(conn->marked_for_close);
  740. /* XXX check: wants_to_read, wants_to_write, s, poll_index,
  741. * marked_for_close. */
  742. /* buffers */
  743. if (!connection_is_listener(conn)) {
  744. assert_buf_ok(conn->inbuf);
  745. assert_buf_ok(conn->outbuf);
  746. }
  747. #if 0 /* computers often go back in time; no way to know */
  748. assert(!now || conn->timestamp_lastread <= now);
  749. assert(!now || conn->timestamp_lastwritten <= now);
  750. assert(conn->timestamp_created <= conn->timestamp_lastread);
  751. assert(conn->timestamp_created <= conn->timestamp_lastwritten);
  752. #endif
  753. /* XXX Fix this; no longer so.*/
  754. #if 0
  755. if(conn->type != CONN_TYPE_OR && conn->type != CONN_TYPE_DIR)
  756. assert(!conn->pkey);
  757. /* pkey is set if we're a dir client, or if we're an OR in state OPEN
  758. * connected to another OR.
  759. */
  760. #endif
  761. if (conn->type != CONN_TYPE_OR) {
  762. assert(!conn->tls);
  763. } else {
  764. if(conn->state == OR_CONN_STATE_OPEN) {
  765. /* assert(conn->bandwidth > 0); */
  766. /* the above isn't necessarily true: if we just did a TLS
  767. * handshake but we didn't recognize the other peer, or it
  768. * gave a bad cert/etc, then we won't have assigned bandwidth,
  769. * yet it will be open. -RD
  770. */
  771. assert(conn->receiver_bucket >= 0);
  772. }
  773. assert(conn->addr && conn->port);
  774. assert(conn->address);
  775. if (conn->state != OR_CONN_STATE_CONNECTING)
  776. assert(conn->tls);
  777. }
  778. if (conn->type != CONN_TYPE_EXIT && conn->type != CONN_TYPE_AP) {
  779. assert(!conn->stream_id);
  780. assert(!conn->next_stream);
  781. assert(!conn->cpath_layer);
  782. assert(!conn->package_window);
  783. assert(!conn->deliver_window);
  784. assert(!conn->done_sending);
  785. assert(!conn->done_receiving);
  786. } else {
  787. if(conn->type == CONN_TYPE_AP && conn->state == AP_CONN_STATE_OPEN)
  788. assert(conn->cpath_layer);
  789. if(conn->cpath_layer)
  790. assert_cpath_layer_ok(conn->cpath_layer);
  791. /* XXX unchecked: package window, deliver window. */
  792. }
  793. if (conn->type != CONN_TYPE_AP) {
  794. assert(!conn->socks_request);
  795. }
  796. switch(conn->type)
  797. {
  798. case CONN_TYPE_OR_LISTENER:
  799. case CONN_TYPE_AP_LISTENER:
  800. case CONN_TYPE_DIR_LISTENER:
  801. assert(conn->state == LISTENER_STATE_READY);
  802. break;
  803. case CONN_TYPE_OR:
  804. assert(conn->state >= _OR_CONN_STATE_MIN &&
  805. conn->state <= _OR_CONN_STATE_MAX);
  806. break;
  807. case CONN_TYPE_EXIT:
  808. assert(conn->state >= _EXIT_CONN_STATE_MIN &&
  809. conn->state <= _EXIT_CONN_STATE_MAX);
  810. break;
  811. case CONN_TYPE_AP:
  812. assert(conn->state >= _AP_CONN_STATE_MIN &&
  813. conn->state <= _AP_CONN_STATE_MAX);
  814. assert(conn->socks_request);
  815. break;
  816. case CONN_TYPE_DIR:
  817. assert(conn->state >= _DIR_CONN_STATE_MIN &&
  818. conn->state <= _DIR_CONN_STATE_MAX);
  819. break;
  820. case CONN_TYPE_DNSWORKER:
  821. assert(conn->state == DNSWORKER_STATE_IDLE ||
  822. conn->state == DNSWORKER_STATE_BUSY);
  823. break;
  824. case CONN_TYPE_CPUWORKER:
  825. assert(conn->state >= _CPUWORKER_STATE_MIN &&
  826. conn->state <= _CPUWORKER_STATE_MAX);
  827. break;
  828. default:
  829. assert(0);
  830. }
  831. }
  832. /*
  833. Local Variables:
  834. mode:c
  835. indent-tabs-mode:nil
  836. c-basic-offset:2
  837. End:
  838. */