connection.c 32 KB

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