- fprintf(stderr, "%p advanced %u\n", utcp, advanced);
- // Make room in the send buffer.
- // TODO: try to avoid memmoving too much. Circular buffer?
- uint32_t left = seqdiff(c->snd.nxt, hdr.ack);
- if(left)
- memmove(c->sndbuf, c->sndbuf + advanced, left);
+ // RTT measurement
+ if(c->rtt_start.tv_sec) {
+ if(c->rtt_seq == hdr.ack) {
+ struct timeval now, diff;
+ gettimeofday(&now, NULL);
+ timersub(&now, &c->rtt_start, &diff);
+ update_rtt(c, diff.tv_sec * 1000000 + diff.tv_usec);
+ c->rtt_start.tv_sec = 0;
+ } else if(c->rtt_seq < hdr.ack) {
+ debug("Cancelling RTT measurement: %u < %u\n", c->rtt_seq, hdr.ack);
+ c->rtt_start.tv_sec = 0;
+ }
+ }
+
+ int32_t data_acked = advanced;
+
+ switch(c->state) {
+ case SYN_SENT:
+ case SYN_RECEIVED:
+ data_acked--;
+ break;
+
+ // TODO: handle FIN as well.
+ default:
+ break;
+ }
+
+ assert(data_acked >= 0);
+
+ int32_t bufused = seqdiff(c->snd.last, c->snd.una);
+ assert(data_acked <= bufused);
+
+ if(data_acked) {
+ buffer_get(&c->sndbuf, NULL, data_acked);
+ }
+
+ // Also advance snd.nxt if possible
+ if(seqdiff(c->snd.nxt, hdr.ack) < 0) {
+ c->snd.nxt = hdr.ack;
+ }
+
+ c->snd.una = hdr.ack;
+
+ c->dupack = 0;
+ c->snd.cwnd += utcp->mtu;
+
+ if(c->snd.cwnd > c->sndbuf.maxsize) {
+ c->snd.cwnd = c->sndbuf.maxsize;
+ }
+
+ // Check if we have sent a FIN that is now ACKed.
+ switch(c->state) {
+ case FIN_WAIT_1:
+ if(c->snd.una == c->snd.last) {
+ set_state(c, FIN_WAIT_2);
+ }
+
+ break;
+
+ case CLOSING:
+ if(c->snd.una == c->snd.last) {
+ gettimeofday(&c->conn_timeout, NULL);
+ c->conn_timeout.tv_sec += 60;
+ set_state(c, TIME_WAIT);
+ }
+
+ break;
+
+ default:
+ break;
+ }
+ } else {
+ if(!len && is_reliable(c)) {
+ c->dupack++;
+
+ if(c->dupack == 3) {
+ debug("Triplicate ACK\n");
+ //TODO: Resend one packet and go to fast recovery mode. See RFC 6582.
+ //We do a very simple variant here; reset the nxt pointer to the last acknowledged packet from the peer.
+ //Reset the congestion window so we wait for ACKs.
+ c->snd.nxt = c->snd.una;
+ c->snd.cwnd = utcp->mtu;
+ start_retransmit_timer(c);
+ }
+ }