connection.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972
  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, (void*) &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,
  361. (uint16_t) options.ORPort,
  362. CONN_TYPE_OR_LISTENER) < 0)
  363. return -1;
  364. }
  365. if(options.DirPort) {
  366. listener_close_if_present(CONN_TYPE_DIR_LISTENER);
  367. if(connection_create_listener(options.DirBindAddress,
  368. (uint16_t) options.DirPort,
  369. CONN_TYPE_DIR_LISTENER) < 0)
  370. return -1;
  371. }
  372. if(options.SocksPort) {
  373. listener_close_if_present(CONN_TYPE_AP_LISTENER);
  374. if(connection_create_listener(options.SocksBindAddress,
  375. (uint16_t) options.SocksPort,
  376. CONN_TYPE_AP_LISTENER) < 0)
  377. return -1;
  378. }
  379. return 0;
  380. }
  381. int connection_handle_read(connection_t *conn) {
  382. conn->timestamp_lastread = time(NULL);
  383. switch(conn->type) {
  384. case CONN_TYPE_OR_LISTENER:
  385. return connection_handle_listener_read(conn, CONN_TYPE_OR);
  386. case CONN_TYPE_AP_LISTENER:
  387. return connection_handle_listener_read(conn, CONN_TYPE_AP);
  388. case CONN_TYPE_DIR_LISTENER:
  389. return connection_handle_listener_read(conn, CONN_TYPE_DIR);
  390. }
  391. if(connection_read_to_buf(conn) < 0) {
  392. if(conn->type == CONN_TYPE_DIR &&
  393. (conn->state == DIR_CONN_STATE_CONNECTING_FETCH ||
  394. conn->state == DIR_CONN_STATE_CONNECTING_UPLOAD)) {
  395. /* it's a directory server and connecting failed: forget about this router */
  396. /* XXX I suspect pollerr may make Windows not get to this point. :( */
  397. router_mark_as_down(conn->nickname);
  398. }
  399. /* There's a read error; kill the connection.*/
  400. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  401. connection_mark_for_close(conn, END_STREAM_REASON_MISC);
  402. return -1;
  403. }
  404. if(connection_process_inbuf(conn) < 0) {
  405. // log_fn(LOG_DEBUG,"connection_process_inbuf returned -1.");
  406. return -1;
  407. }
  408. return 0;
  409. }
  410. /* return -1 if we want to break conn, else return 0 */
  411. int connection_read_to_buf(connection_t *conn) {
  412. int result;
  413. int at_most;
  414. if(options.LinkPadding) {
  415. at_most = global_read_bucket;
  416. } else {
  417. /* do a rudimentary round-robin so one connection can't hog a thickpipe */
  418. if(connection_speaks_cells(conn)) {
  419. at_most = 32*(CELL_NETWORK_SIZE);
  420. } else {
  421. at_most = 32*(RELAY_PAYLOAD_SIZE);
  422. }
  423. if(at_most > global_read_bucket)
  424. at_most = global_read_bucket;
  425. }
  426. if(connection_speaks_cells(conn) && conn->state != OR_CONN_STATE_CONNECTING) {
  427. if(conn->state == OR_CONN_STATE_HANDSHAKING)
  428. return connection_tls_continue_handshake(conn);
  429. /* else open, or closing */
  430. if(at_most > conn->receiver_bucket)
  431. at_most = conn->receiver_bucket;
  432. result = read_to_buf_tls(conn->tls, at_most, conn->inbuf);
  433. switch(result) {
  434. case TOR_TLS_ERROR:
  435. case TOR_TLS_CLOSE:
  436. log_fn(LOG_INFO,"tls error. breaking.");
  437. return -1; /* XXX deal with close better */
  438. case TOR_TLS_WANTWRITE:
  439. connection_start_writing(conn);
  440. return 0;
  441. case TOR_TLS_WANTREAD: /* we're already reading */
  442. case TOR_TLS_DONE: /* no data read, so nothing to process */
  443. return 0;
  444. }
  445. } else {
  446. result = read_to_buf(conn->s, at_most, conn->inbuf,
  447. &conn->inbuf_reached_eof);
  448. // log(LOG_DEBUG,"connection_read_to_buf(): read_to_buf returned %d.",read_result);
  449. if(result < 0)
  450. return -1;
  451. }
  452. global_read_bucket -= result; assert(global_read_bucket >= 0);
  453. if(global_read_bucket == 0) {
  454. log_fn(LOG_DEBUG,"global bucket exhausted. Pausing.");
  455. conn->wants_to_read = 1;
  456. connection_stop_reading(conn);
  457. return 0;
  458. }
  459. if(connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
  460. conn->receiver_bucket -= result; assert(conn->receiver_bucket >= 0);
  461. if(conn->receiver_bucket == 0) {
  462. log_fn(LOG_DEBUG,"receiver bucket exhausted. Pausing.");
  463. conn->wants_to_read = 1;
  464. connection_stop_reading(conn);
  465. return 0;
  466. }
  467. }
  468. return 0;
  469. }
  470. int connection_fetch_from_buf(char *string, int len, connection_t *conn) {
  471. return fetch_from_buf(string, len, conn->inbuf);
  472. }
  473. int connection_find_on_inbuf(char *string, int len, connection_t *conn) {
  474. return find_on_inbuf(string, len, conn->inbuf);
  475. }
  476. int connection_wants_to_flush(connection_t *conn) {
  477. return conn->outbuf_flushlen;
  478. }
  479. int connection_outbuf_too_full(connection_t *conn) {
  480. return (conn->outbuf_flushlen > 10*CELL_PAYLOAD_SIZE);
  481. }
  482. /* return -1 if you want to break the conn, else return 0 */
  483. int connection_handle_write(connection_t *conn) {
  484. assert(!connection_is_listener(conn));
  485. conn->timestamp_lastwritten = time(NULL);
  486. if (connection_speaks_cells(conn) &&
  487. conn->state != OR_CONN_STATE_CONNECTING) {
  488. if (conn->state == OR_CONN_STATE_HANDSHAKING) {
  489. connection_stop_writing(conn);
  490. if(connection_tls_continue_handshake(conn) < 0) {
  491. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  492. connection_mark_for_close(conn, 0);
  493. return -1;
  494. }
  495. return 0;
  496. }
  497. /* else open, or closing */
  498. switch(flush_buf_tls(conn->tls, conn->outbuf, &conn->outbuf_flushlen)) {
  499. case TOR_TLS_ERROR:
  500. case TOR_TLS_CLOSE:
  501. log_fn(LOG_INFO,"tls error. breaking.");
  502. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  503. connection_mark_for_close(conn, 0);
  504. return -1; /* XXX deal with close better */
  505. case TOR_TLS_WANTWRITE:
  506. log_fn(LOG_DEBUG,"wanted write.");
  507. /* we're already writing */
  508. return 0;
  509. case TOR_TLS_WANTREAD:
  510. /* Make sure to avoid a loop if the receive buckets are empty. */
  511. log_fn(LOG_DEBUG,"wanted read.");
  512. if(!connection_is_reading(conn)) {
  513. connection_stop_writing(conn);
  514. conn->wants_to_write = 1;
  515. /* we'll start reading again when the next second arrives,
  516. * and then also start writing again.
  517. */
  518. }
  519. /* else no problem, we're already reading */
  520. return 0;
  521. /* case TOR_TLS_DONE:
  522. * for TOR_TLS_DONE, fall through to check if the flushlen
  523. * is empty, so we can stop writing.
  524. */
  525. }
  526. } else {
  527. if (flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen) < 0) {
  528. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  529. connection_mark_for_close(conn, END_STREAM_REASON_MISC);
  530. return -1;
  531. }
  532. /* conns in CONNECTING state will fall through... */
  533. }
  534. if(!connection_wants_to_flush(conn)) /* it's done flushing */
  535. if(connection_finished_flushing(conn) < 0) /* ...and get handled here. */
  536. return -1;
  537. return 0;
  538. }
  539. void connection_write_to_buf(const char *string, int len, connection_t *conn) {
  540. if(!len || conn->marked_for_close)
  541. return;
  542. if(write_to_buf(string, len, conn->outbuf) < 0) {
  543. log_fn(LOG_WARN,"write_to_buf failed. Closing connection (fd %d).", conn->s);
  544. connection_mark_for_close(conn,0);
  545. return;
  546. }
  547. connection_start_writing(conn);
  548. #define MIN_TLS_FLUSHLEN 15872
  549. /* openssl tls record size is 16383, this is close. The goal here is to
  550. * push data out as soon as we know there's enough for a tls record, so
  551. * during periods of high load we won't read the entire megabyte from
  552. * input before pushing any data out. */
  553. if(connection_speaks_cells(conn) &&
  554. conn->outbuf_flushlen < MIN_TLS_FLUSHLEN &&
  555. conn->outbuf_flushlen+len >= MIN_TLS_FLUSHLEN) {
  556. len -= (MIN_TLS_FLUSHLEN - conn->outbuf_flushlen);
  557. conn->outbuf_flushlen = MIN_TLS_FLUSHLEN;
  558. if(connection_handle_write(conn) < 0) {
  559. log_fn(LOG_WARN,"flushing failed.");
  560. connection_mark_for_close(conn,0);
  561. }
  562. }
  563. if(len > 0) { /* if there's any left over */
  564. conn->outbuf_flushlen += len;
  565. connection_start_writing(conn);
  566. /* because connection_handle_write() above might have stopped writing */
  567. }
  568. }
  569. connection_t *connection_exact_get_by_addr_port(uint32_t addr, uint16_t port) {
  570. int i, n;
  571. connection_t *conn;
  572. connection_t **carray;
  573. get_connection_array(&carray,&n);
  574. for(i=0;i<n;i++) {
  575. conn = carray[i];
  576. if(conn->addr == addr && conn->port == port && !conn->marked_for_close)
  577. return conn;
  578. }
  579. return NULL;
  580. }
  581. connection_t *connection_twin_get_by_addr_port(uint32_t addr, uint16_t port) {
  582. /* Find a connection to the router described by addr and port,
  583. * or alternately any router which knows its key.
  584. * This connection *must* be in 'open' state.
  585. * If not, return NULL.
  586. */
  587. int i, n;
  588. connection_t *conn;
  589. routerinfo_t *router;
  590. connection_t **carray;
  591. /* first check if it's there exactly */
  592. conn = connection_exact_get_by_addr_port(addr,port);
  593. if(conn && connection_state_is_open(conn)) {
  594. log(LOG_DEBUG,"connection_twin_get_by_addr_port(): Found exact match.");
  595. return conn;
  596. }
  597. /* now check if any of the other open connections are a twin for this one */
  598. router = router_get_by_addr_port(addr,port);
  599. if(!router)
  600. return NULL;
  601. get_connection_array(&carray,&n);
  602. for(i=0;i<n;i++) {
  603. conn = carray[i];
  604. assert(conn);
  605. if(connection_state_is_open(conn) &&
  606. !crypto_pk_cmp_keys(conn->onion_pkey, router->onion_pkey)) {
  607. log(LOG_DEBUG,"connection_twin_get_by_addr_port(): Found twin (%s).",conn->address);
  608. return conn;
  609. }
  610. }
  611. return NULL;
  612. }
  613. connection_t *connection_get_by_type(int type) {
  614. int i, n;
  615. connection_t *conn;
  616. connection_t **carray;
  617. get_connection_array(&carray,&n);
  618. for(i=0;i<n;i++) {
  619. conn = carray[i];
  620. if(conn->type == type && !conn->marked_for_close)
  621. return conn;
  622. }
  623. return NULL;
  624. }
  625. connection_t *connection_get_by_type_state(int type, int state) {
  626. int i, n;
  627. connection_t *conn;
  628. connection_t **carray;
  629. get_connection_array(&carray,&n);
  630. for(i=0;i<n;i++) {
  631. conn = carray[i];
  632. if(conn->type == type && conn->state == state && !conn->marked_for_close)
  633. return conn;
  634. }
  635. return NULL;
  636. }
  637. connection_t *connection_get_by_type_state_lastwritten(int type, int state) {
  638. int i, n;
  639. connection_t *conn, *best=NULL;
  640. connection_t **carray;
  641. get_connection_array(&carray,&n);
  642. for(i=0;i<n;i++) {
  643. conn = carray[i];
  644. if(conn->type == type && conn->state == state && !conn->marked_for_close)
  645. if(!best || conn->timestamp_lastwritten < best->timestamp_lastwritten)
  646. best = conn;
  647. }
  648. return best;
  649. }
  650. int connection_receiver_bucket_should_increase(connection_t *conn) {
  651. assert(conn);
  652. if(!connection_speaks_cells(conn))
  653. return 0; /* edge connections don't use receiver_buckets */
  654. if(conn->state != OR_CONN_STATE_OPEN)
  655. return 0; /* only open connections play the rate limiting game */
  656. assert(conn->bandwidth > 0);
  657. if(conn->receiver_bucket > 9*conn->bandwidth)
  658. return 0;
  659. return 1;
  660. }
  661. int connection_is_listener(connection_t *conn) {
  662. if(conn->type == CONN_TYPE_OR_LISTENER ||
  663. conn->type == CONN_TYPE_AP_LISTENER ||
  664. conn->type == CONN_TYPE_DIR_LISTENER)
  665. return 1;
  666. return 0;
  667. }
  668. int connection_state_is_open(connection_t *conn) {
  669. assert(conn);
  670. if(conn->marked_for_close)
  671. return 0;
  672. if((conn->type == CONN_TYPE_OR && conn->state == OR_CONN_STATE_OPEN) ||
  673. (conn->type == CONN_TYPE_AP && conn->state == AP_CONN_STATE_OPEN) ||
  674. (conn->type == CONN_TYPE_EXIT && conn->state == EXIT_CONN_STATE_OPEN))
  675. return 1;
  676. return 0;
  677. }
  678. int connection_send_destroy(uint16_t circ_id, connection_t *conn) {
  679. cell_t cell;
  680. assert(conn);
  681. assert(connection_speaks_cells(conn));
  682. memset(&cell, 0, sizeof(cell_t));
  683. cell.circ_id = circ_id;
  684. cell.command = CELL_DESTROY;
  685. log_fn(LOG_INFO,"Sending destroy (circID %d).", circ_id);
  686. connection_or_write_cell_to_buf(&cell, conn);
  687. return 0;
  688. }
  689. int connection_process_inbuf(connection_t *conn) {
  690. assert(conn);
  691. switch(conn->type) {
  692. case CONN_TYPE_OR:
  693. return connection_or_process_inbuf(conn);
  694. case CONN_TYPE_EXIT:
  695. case CONN_TYPE_AP:
  696. return connection_edge_process_inbuf(conn);
  697. case CONN_TYPE_DIR:
  698. return connection_dir_process_inbuf(conn);
  699. case CONN_TYPE_DNSWORKER:
  700. return connection_dns_process_inbuf(conn);
  701. case CONN_TYPE_CPUWORKER:
  702. return connection_cpu_process_inbuf(conn);
  703. default:
  704. log_fn(LOG_WARN,"got unexpected conn->type %d.", conn->type);
  705. return -1;
  706. }
  707. }
  708. int connection_finished_flushing(connection_t *conn) {
  709. assert(conn);
  710. // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
  711. switch(conn->type) {
  712. case CONN_TYPE_OR:
  713. return connection_or_finished_flushing(conn);
  714. case CONN_TYPE_AP:
  715. case CONN_TYPE_EXIT:
  716. return connection_edge_finished_flushing(conn);
  717. case CONN_TYPE_DIR:
  718. return connection_dir_finished_flushing(conn);
  719. case CONN_TYPE_DNSWORKER:
  720. return connection_dns_finished_flushing(conn);
  721. case CONN_TYPE_CPUWORKER:
  722. return connection_cpu_finished_flushing(conn);
  723. default:
  724. log_fn(LOG_WARN,"got unexpected conn->type %d.", conn->type);
  725. return -1;
  726. }
  727. }
  728. void assert_connection_ok(connection_t *conn, time_t now)
  729. {
  730. assert(conn);
  731. assert(conn->magic == CONNECTION_MAGIC);
  732. assert(conn->type >= _CONN_TYPE_MIN);
  733. assert(conn->type <= _CONN_TYPE_MAX);
  734. if(conn->outbuf_flushlen > 0) {
  735. assert(connection_is_writing(conn) || conn->wants_to_write);
  736. }
  737. if(conn->hold_open_until_flushed)
  738. assert(conn->marked_for_close);
  739. /* XXX check: wants_to_read, wants_to_write, s, poll_index,
  740. * marked_for_close. */
  741. /* buffers */
  742. if (!connection_is_listener(conn)) {
  743. assert_buf_ok(conn->inbuf);
  744. assert_buf_ok(conn->outbuf);
  745. }
  746. #if 0 /* computers often go back in time; no way to know */
  747. assert(!now || conn->timestamp_lastread <= now);
  748. assert(!now || conn->timestamp_lastwritten <= now);
  749. assert(conn->timestamp_created <= conn->timestamp_lastread);
  750. assert(conn->timestamp_created <= conn->timestamp_lastwritten);
  751. #endif
  752. /* XXX Fix this; no longer so.*/
  753. #if 0
  754. if(conn->type != CONN_TYPE_OR && conn->type != CONN_TYPE_DIR)
  755. assert(!conn->pkey);
  756. /* pkey is set if we're a dir client, or if we're an OR in state OPEN
  757. * connected to another OR.
  758. */
  759. #endif
  760. if (conn->type != CONN_TYPE_OR) {
  761. assert(!conn->tls);
  762. } else {
  763. if(conn->state == OR_CONN_STATE_OPEN) {
  764. /* assert(conn->bandwidth > 0); */
  765. /* the above isn't necessarily true: if we just did a TLS
  766. * handshake but we didn't recognize the other peer, or it
  767. * gave a bad cert/etc, then we won't have assigned bandwidth,
  768. * yet it will be open. -RD
  769. */
  770. assert(conn->receiver_bucket >= 0);
  771. }
  772. assert(conn->addr && conn->port);
  773. assert(conn->address);
  774. if (conn->state != OR_CONN_STATE_CONNECTING)
  775. assert(conn->tls);
  776. }
  777. if (conn->type != CONN_TYPE_EXIT && conn->type != CONN_TYPE_AP) {
  778. assert(!conn->stream_id);
  779. assert(!conn->next_stream);
  780. assert(!conn->cpath_layer);
  781. assert(!conn->package_window);
  782. assert(!conn->deliver_window);
  783. assert(!conn->done_sending);
  784. assert(!conn->done_receiving);
  785. } else {
  786. if(conn->type == CONN_TYPE_AP && conn->state == AP_CONN_STATE_OPEN)
  787. assert(conn->cpath_layer);
  788. if(conn->cpath_layer)
  789. assert_cpath_layer_ok(conn->cpath_layer);
  790. /* XXX unchecked: package window, deliver window. */
  791. }
  792. if (conn->type != CONN_TYPE_AP) {
  793. assert(!conn->socks_request);
  794. }
  795. switch(conn->type)
  796. {
  797. case CONN_TYPE_OR_LISTENER:
  798. case CONN_TYPE_AP_LISTENER:
  799. case CONN_TYPE_DIR_LISTENER:
  800. assert(conn->state == LISTENER_STATE_READY);
  801. break;
  802. case CONN_TYPE_OR:
  803. assert(conn->state >= _OR_CONN_STATE_MIN &&
  804. conn->state <= _OR_CONN_STATE_MAX);
  805. break;
  806. case CONN_TYPE_EXIT:
  807. assert(conn->state >= _EXIT_CONN_STATE_MIN &&
  808. conn->state <= _EXIT_CONN_STATE_MAX);
  809. break;
  810. case CONN_TYPE_AP:
  811. assert(conn->state >= _AP_CONN_STATE_MIN &&
  812. conn->state <= _AP_CONN_STATE_MAX);
  813. assert(conn->socks_request);
  814. break;
  815. case CONN_TYPE_DIR:
  816. assert(conn->state >= _DIR_CONN_STATE_MIN &&
  817. conn->state <= _DIR_CONN_STATE_MAX);
  818. break;
  819. case CONN_TYPE_DNSWORKER:
  820. assert(conn->state == DNSWORKER_STATE_IDLE ||
  821. conn->state == DNSWORKER_STATE_BUSY);
  822. break;
  823. case CONN_TYPE_CPUWORKER:
  824. assert(conn->state >= _CPUWORKER_STATE_MIN &&
  825. conn->state <= _CPUWORKER_STATE_MAX);
  826. break;
  827. default:
  828. assert(0);
  829. }
  830. }
  831. /*
  832. Local Variables:
  833. mode:c
  834. indent-tabs-mode:nil
  835. c-basic-offset:2
  836. End:
  837. */