]> git.meshlink.io Git - utcp/blob - utcp.c
Recover from dropped packets after receiving a triplicate ACK.
[utcp] / utcp.c
1 /*
2     utcp.c -- Userspace TCP
3     Copyright (C) 2014 Guus Sliepen <guus@tinc-vpn.org>
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License along
16     with this program; if not, write to the Free Software Foundation, Inc.,
17     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #define _GNU_SOURCE
21
22 #include <assert.h>
23 #include <errno.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <stdint.h>
27 #include <stdbool.h>
28 #include <string.h>
29 #include <unistd.h>
30 #include <sys/time.h>
31 #include <sys/socket.h>
32
33 #include "utcp_priv.h"
34
35 #ifndef EBADMSG
36 #define EBADMSG         104
37 #endif
38
39 #ifndef SHUT_RDWR
40 #define SHUT_RDWR 2
41 #endif
42
43 #ifdef poll
44 #undef poll
45 #endif
46
47 #ifndef timersub
48 #define timersub(a, b, r) do {\
49         (r)->tv_sec = (a)->tv_sec - (b)->tv_sec;\
50         (r)->tv_usec = (a)->tv_usec - (b)->tv_usec;\
51         if((r)->tv_usec < 0)\
52                 (r)->tv_sec--, (r)->tv_usec += 1000000;\
53 } while (0)
54 #endif
55
56 #ifdef UTCP_DEBUG
57 #include <stdarg.h>
58
59 static void debug(const char *format, ...) {
60         va_list ap;
61         va_start(ap, format);
62         vfprintf(stderr, format, ap);
63         va_end(ap);
64 }
65
66 static void print_packet(struct utcp *utcp, const char *dir, const void *pkt, size_t len) {
67         struct hdr hdr;
68         if(len < sizeof hdr) {
69                 debug("%p %s: short packet (%zu bytes)\n", utcp, dir, len);
70                 return;
71         }
72
73         memcpy(&hdr, pkt, sizeof hdr);
74         fprintf (stderr, "%p %s: len=%zu, src=%u dst=%u seq=%u ack=%u wnd=%u ctl=", utcp, dir, len, hdr.src, hdr.dst, hdr.seq, hdr.ack, hdr.wnd);
75         if(hdr.ctl & SYN)
76                 debug("SYN");
77         if(hdr.ctl & RST)
78                 debug("RST");
79         if(hdr.ctl & FIN)
80                 debug("FIN");
81         if(hdr.ctl & ACK)
82                 debug("ACK");
83
84         if(len > sizeof hdr) {
85                 debug(" data=");
86                 for(int i = sizeof hdr; i < len; i++) {
87                         const char *data = pkt;
88                         debug("%c", data[i] >= 32 ? data[i] : '.');
89                 }
90         }
91
92         debug("\n");
93 }
94 #else
95 #define debug(...)
96 #define print_packet(...)
97 #endif
98
99 static void set_state(struct utcp_connection *c, enum state state) {
100         c->state = state;
101         if(state == ESTABLISHED)
102                 timerclear(&c->conn_timeout);
103         debug("%p new state: %s\n", c->utcp, strstate[state]);
104 }
105
106 static inline void list_connections(struct utcp *utcp) {
107         debug("%p has %d connections:\n", utcp, utcp->nconnections);
108         for(int i = 0; i < utcp->nconnections; i++)
109                 debug("  %u -> %u state %s\n", utcp->connections[i]->src, utcp->connections[i]->dst, strstate[utcp->connections[i]->state]);
110 }
111
112 static int32_t seqdiff(uint32_t a, uint32_t b) {
113         return a - b;
114 }
115
116 // Buffer functions
117 // TODO: convert to ringbuffers to avoid memmove() operations.
118
119 // Store data into the buffer
120 static ssize_t buffer_put(struct buffer *buf, const void *data, size_t len) {
121         if(buf->maxsize <= buf->used)
122                 return 0;
123         if(len > buf->maxsize - buf->used)
124                 len = buf->maxsize - buf->used;
125         if(len > buf->size - buf->used) {
126                 size_t newsize = buf->size;
127                 do {
128                         newsize *= 2;
129                 } while(newsize < buf->used + len);
130                 if(newsize > buf->maxsize)
131                         newsize = buf->maxsize;
132                 char *newdata = realloc(buf->data, newsize);
133                 if(!newdata)
134                         return -1;
135                 buf->data = newdata;
136                 buf->size = newsize;
137         }
138         memcpy(buf->data + buf->used, data, len);
139         buf->used += len;
140         return len;
141 }
142
143 // Get data from the buffer. data can be NULL.
144 static ssize_t buffer_get(struct buffer *buf, void *data, size_t len) {
145         if(len > buf->used)
146                 len = buf->used;
147         if(data)
148                 memcpy(data, buf->data, len);
149         if(len < buf->used)
150                 memmove(buf->data, buf->data + len, buf->used - len);
151         buf->used -= len;
152         return len;
153 }
154
155 // Copy data from the buffer without removing it.
156 static ssize_t buffer_copy(struct buffer *buf, void *data, size_t offset, size_t len) {
157         if(offset >= buf->used)
158                 return 0;
159         if(offset + len > buf->used)
160                 len = buf->used - offset;
161         memcpy(data, buf->data + offset, len);
162         return len;
163 }
164
165 static bool buffer_init(struct buffer *buf, uint32_t len, uint32_t maxlen) {
166         memset(buf, 0, sizeof *buf);
167         buf->data = malloc(len);
168         if(!len)
169                 return false;
170         buf->size = len;
171         buf->maxsize = maxlen;
172         return true;
173 }
174
175 static void buffer_exit(struct buffer *buf) {
176         free(buf->data);
177         memset(buf, 0, sizeof *buf);
178 }
179
180 static uint32_t buffer_free(const struct buffer *buf) {
181         return buf->maxsize - buf->used;
182 }
183
184 // Connections are stored in a sorted list.
185 // This gives O(log(N)) lookup time, O(N log(N)) insertion time and O(N) deletion time.
186
187 static int compare(const void *va, const void *vb) {
188         assert(va && vb);
189
190         const struct utcp_connection *a = *(struct utcp_connection **)va;
191         const struct utcp_connection *b = *(struct utcp_connection **)vb;
192
193         assert(a && b);
194         assert(a->src && b->src);
195
196         int c = (int)a->src - (int)b->src;
197         if(c)
198                 return c;
199         c = (int)a->dst - (int)b->dst;
200         return c;
201 }
202
203 static struct utcp_connection *find_connection(const struct utcp *utcp, uint16_t src, uint16_t dst) {
204         if(!utcp->nconnections)
205                 return NULL;
206         struct utcp_connection key = {
207                 .src = src,
208                 .dst = dst,
209         }, *keyp = &key;
210         struct utcp_connection **match = bsearch(&keyp, utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
211         return match ? *match : NULL;
212 }
213
214 static void free_connection(struct utcp_connection *c) {
215         struct utcp *utcp = c->utcp;
216         struct utcp_connection **cp = bsearch(&c, utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
217
218         assert(cp);
219
220         int i = cp - utcp->connections;
221         memmove(cp, cp + 1, (utcp->nconnections - i - 1) * sizeof *cp);
222         utcp->nconnections--;
223
224         buffer_exit(&c->sndbuf);
225         free(c);
226 }
227
228 static struct utcp_connection *allocate_connection(struct utcp *utcp, uint16_t src, uint16_t dst) {
229         // Check whether this combination of src and dst is free
230
231         if(src) {
232                 if(find_connection(utcp, src, dst)) {
233                         errno = EADDRINUSE;
234                         return NULL;
235                 }
236         } else { // If src == 0, generate a random port number with the high bit set
237                 if(utcp->nconnections >= 32767) {
238                         errno = ENOMEM;
239                         return NULL;
240                 }
241                 src = rand() | 0x8000;
242                 while(find_connection(utcp, src, dst))
243                         src++;
244         }
245
246         // Allocate memory for the new connection
247
248         if(utcp->nconnections >= utcp->nallocated) {
249                 if(!utcp->nallocated)
250                         utcp->nallocated = 4;
251                 else
252                         utcp->nallocated *= 2;
253                 struct utcp_connection **new_array = realloc(utcp->connections, utcp->nallocated * sizeof *utcp->connections);
254                 if(!new_array)
255                         return NULL;
256                 utcp->connections = new_array;
257         }
258
259         struct utcp_connection *c = calloc(1, sizeof *c);
260         if(!c)
261                 return NULL;
262
263         if(!buffer_init(&c->sndbuf, DEFAULT_SNDBUFSIZE, DEFAULT_MAXSNDBUFSIZE)) {
264                 free(c);
265                 return NULL;
266         }
267
268         // Fill in the details
269
270         c->src = src;
271         c->dst = dst;
272         c->snd.iss = rand();
273         c->snd.una = c->snd.iss;
274         c->snd.nxt = c->snd.iss + 1;
275         c->rcv.wnd = utcp->mtu;
276         c->snd.last = c->snd.nxt;
277         c->snd.cwnd = utcp->mtu;
278         c->utcp = utcp;
279
280         // Add it to the sorted list of connections
281
282         utcp->connections[utcp->nconnections++] = c;
283         qsort(utcp->connections, utcp->nconnections, sizeof *utcp->connections, compare);
284
285         return c;
286 }
287
288 struct utcp_connection *utcp_connect(struct utcp *utcp, uint16_t dst, utcp_recv_t recv, void *priv) {
289         struct utcp_connection *c = allocate_connection(utcp, 0, dst);
290         if(!c)
291                 return NULL;
292
293         c->recv = recv;
294         c->priv = priv;
295
296         struct hdr hdr;
297
298         hdr.src = c->src;
299         hdr.dst = c->dst;
300         hdr.seq = c->snd.iss;
301         hdr.ack = 0;
302         hdr.wnd = c->rcv.wnd;
303         hdr.ctl = SYN;
304         hdr.aux = 0;
305
306         set_state(c, SYN_SENT);
307
308         print_packet(utcp, "send", &hdr, sizeof hdr);
309         utcp->send(utcp, &hdr, sizeof hdr);
310
311         gettimeofday(&c->conn_timeout, NULL);
312         c->conn_timeout.tv_sec += utcp->timeout;
313
314         return c;
315 }
316
317 void utcp_accept(struct utcp_connection *c, utcp_recv_t recv, void *priv) {
318         if(c->reapable || c->state != SYN_RECEIVED) {
319                 debug("Error: accept() called on invalid connection %p in state %s\n", c, strstate[c->state]);
320                 return;
321         }
322
323         debug("%p accepted, %p %p\n", c, recv, priv);
324         c->recv = recv;
325         c->priv = priv;
326         set_state(c, ESTABLISHED);
327 }
328
329 static void ack(struct utcp_connection *c, bool sendatleastone) {
330         int32_t left = seqdiff(c->snd.last, c->snd.nxt);
331         int32_t cwndleft = c->snd.cwnd - seqdiff(c->snd.nxt, c->snd.una);
332
333         assert(left >= 0);
334
335         if(cwndleft <= 0)
336                 cwndleft = 0;
337
338         if(cwndleft < left)
339                 left = cwndleft;
340
341         if(!left && !sendatleastone)
342                 return;
343
344         struct {
345                 struct hdr hdr;
346                 char data[];
347         } *pkt;
348
349         pkt = malloc(sizeof pkt->hdr + c->utcp->mtu);
350         if(!pkt->data)
351                 return;
352
353         pkt->hdr.src = c->src;
354         pkt->hdr.dst = c->dst;
355         pkt->hdr.ack = c->rcv.nxt;
356         pkt->hdr.wnd = c->snd.wnd;
357         pkt->hdr.ctl = ACK;
358         pkt->hdr.aux = 0;
359
360         do {
361                 uint32_t seglen = left > c->utcp->mtu ? c->utcp->mtu : left;
362                 pkt->hdr.seq = c->snd.nxt;
363
364                 buffer_copy(&c->sndbuf, pkt->data, seqdiff(c->snd.nxt, c->snd.una), seglen);
365
366                 c->snd.nxt += seglen;
367                 left -= seglen;
368
369                 if(c->state != ESTABLISHED && !left && seglen) {
370                         switch(c->state) {
371                         case FIN_WAIT_1:
372                         case CLOSING:
373                                 seglen--;
374                                 pkt->hdr.ctl |= FIN;
375                                 break;
376                         default:
377                                 break;
378                         }
379                 }
380
381                 print_packet(c->utcp, "send", pkt, sizeof pkt->hdr + seglen);
382                 c->utcp->send(c->utcp, pkt, sizeof pkt->hdr + seglen);
383         } while(left);
384
385         free(pkt);
386 }
387
388 ssize_t utcp_send(struct utcp_connection *c, const void *data, size_t len) {
389         if(c->reapable) {
390                 debug("Error: send() called on closed connection %p\n", c);
391                 errno = EBADF;
392                 return -1;
393         }
394
395         switch(c->state) {
396         case CLOSED:
397         case LISTEN:
398         case SYN_SENT:
399         case SYN_RECEIVED:
400                 debug("Error: send() called on unconnected connection %p\n", c);
401                 errno = ENOTCONN;
402                 return -1;
403         case ESTABLISHED:
404         case CLOSE_WAIT:
405                 break;
406         case FIN_WAIT_1:
407         case FIN_WAIT_2:
408         case CLOSING:
409         case LAST_ACK:
410         case TIME_WAIT:
411                 debug("Error: send() called on closing connection %p\n", c);
412                 errno = EPIPE;
413                 return -1;
414         }
415
416         // Add data to send buffer
417
418         if(!len)
419                 return 0;
420
421         if(!data) {
422                 errno = EFAULT;
423                 return -1;
424         }
425
426         len = buffer_put(&c->sndbuf, data, len);
427         if(len <= 0) {
428                 errno = EWOULDBLOCK;
429                 return 0;
430         }
431
432         c->snd.last += len;
433         ack(c, false);
434         return len;
435 }
436
437 static void swap_ports(struct hdr *hdr) {
438         uint16_t tmp = hdr->src;
439         hdr->src = hdr->dst;
440         hdr->dst = tmp;
441 }
442
443 static void retransmit(struct utcp_connection *c) {
444         if(c->state == CLOSED || c->snd.nxt == c->snd.una)
445                 return;
446
447         struct utcp *utcp = c->utcp;
448
449         struct {
450                 struct hdr hdr;
451                 char data[];
452         } *pkt;
453
454         pkt = malloc(sizeof pkt->hdr + c->utcp->mtu);
455         if(!pkt)
456                 return;
457
458         pkt->hdr.src = c->src;
459         pkt->hdr.dst = c->dst;
460
461         switch(c->state) {
462                 case LISTEN:
463                         // TODO: this should not happen
464                         break;
465
466                 case SYN_SENT:
467                         pkt->hdr.seq = c->snd.iss;
468                         pkt->hdr.ack = 0;
469                         pkt->hdr.wnd = c->rcv.wnd;
470                         pkt->hdr.ctl = SYN;
471                         print_packet(c->utcp, "rtrx", pkt, sizeof pkt->hdr);
472                         utcp->send(utcp, pkt, sizeof pkt->hdr);
473                         break;
474
475                 case SYN_RECEIVED:
476                         pkt->hdr.seq = c->snd.nxt;
477                         pkt->hdr.ack = c->rcv.nxt;
478                         pkt->hdr.ctl = SYN | ACK;
479                         print_packet(c->utcp, "rtrx", pkt, sizeof pkt->hdr);
480                         utcp->send(utcp, pkt, sizeof pkt->hdr);
481                         break;
482
483                 case ESTABLISHED:
484                 case FIN_WAIT_1:
485                         pkt->hdr.seq = c->snd.una;
486                         pkt->hdr.ack = c->rcv.nxt;
487                         pkt->hdr.ctl = ACK;
488                         uint32_t len = seqdiff(c->snd.nxt, c->snd.una);
489                         fprintf(stderr, "retransmit %u %u %u\n", pkt->hdr.seq, pkt->hdr.ack, len);
490                         if(c->state == FIN_WAIT_1)
491                                 len--;
492                         if(len > utcp->mtu)
493                                 len = utcp->mtu;
494                         else {
495                                 if(c->state == FIN_WAIT_1)
496                                         pkt->hdr.ctl |= FIN;
497                         }
498                         buffer_copy(&c->sndbuf, pkt->data, 0, len);
499                         print_packet(c->utcp, "rtrx", pkt, sizeof pkt->hdr + len);
500                         utcp->send(utcp, pkt, sizeof pkt->hdr + len);
501                         break;
502
503                 default:
504                         // TODO: implement
505                         abort();
506         }
507
508         free(pkt);
509 }
510
511
512 ssize_t utcp_recv(struct utcp *utcp, const void *data, size_t len) {
513         if(!utcp) {
514                 errno = EFAULT;
515                 return -1;
516         }
517
518         if(!len)
519                 return 0;
520
521         if(!data) {
522                 errno = EFAULT;
523                 return -1;
524         }
525
526         print_packet(utcp, "recv", data, len);
527
528         // Drop packets smaller than the header
529
530         struct hdr hdr;
531         if(len < sizeof hdr) {
532                 errno = EBADMSG;
533                 return -1;
534         }
535
536         // Make a copy from the potentially unaligned data to a struct hdr
537
538         memcpy(&hdr, data, sizeof hdr);
539         data += sizeof hdr;
540         len -= sizeof hdr;
541
542         // Drop packets with an unknown CTL flag
543
544         if(hdr.ctl & ~(SYN | ACK | RST | FIN)) {
545                 errno = EBADMSG;
546                 return -1;
547         }
548
549         // Try to match the packet to an existing connection
550
551         struct utcp_connection *c = find_connection(utcp, hdr.dst, hdr.src);
552
553         // Is it for a new connection?
554
555         if(!c) {
556                 // Ignore RST packets
557
558                 if(hdr.ctl & RST)
559                         return 0;
560
561                 // Is it a SYN packet and are we LISTENing?
562
563                 if(hdr.ctl & SYN && !(hdr.ctl & ACK) && utcp->accept) {
564                         // If we don't want to accept it, send a RST back
565                         if((utcp->pre_accept && !utcp->pre_accept(utcp, hdr.dst))) {
566                                 len = 1;
567                                 goto reset;
568                         }
569
570                         // Try to allocate memory, otherwise send a RST back
571                         c = allocate_connection(utcp, hdr.dst, hdr.src);
572                         if(!c) {
573                                 len = 1;
574                                 goto reset;
575                         }
576
577                         // Return SYN+ACK, go to SYN_RECEIVED state
578                         c->snd.wnd = hdr.wnd;
579                         c->rcv.irs = hdr.seq;
580                         c->rcv.nxt = c->rcv.irs + 1;
581                         set_state(c, SYN_RECEIVED);
582
583                         hdr.dst = c->dst;
584                         hdr.src = c->src;
585                         hdr.ack = c->rcv.irs + 1;
586                         hdr.seq = c->snd.iss;
587                         hdr.ctl = SYN | ACK;
588                         print_packet(c->utcp, "send", &hdr, sizeof hdr);
589                         utcp->send(utcp, &hdr, sizeof hdr);
590                 } else {
591                         // No, we don't want your packets, send a RST back
592                         len = 1;
593                         goto reset;
594                 }
595
596                 return 0;
597         }
598
599         debug("%p state %s\n", c->utcp, strstate[c->state]);
600
601         // In case this is for a CLOSED connection, ignore the packet.
602         // TODO: make it so incoming packets can never match a CLOSED connection.
603
604         if(c->state == CLOSED)
605                 return 0;
606
607         // It is for an existing connection.
608
609         uint32_t prevrcvnxt = c->rcv.nxt;
610
611         // 1. Drop invalid packets.
612
613         // 1a. Drop packets that should not happen in our current state.
614
615         switch(c->state) {
616         case SYN_SENT:
617         case SYN_RECEIVED:
618         case ESTABLISHED:
619         case FIN_WAIT_1:
620         case FIN_WAIT_2:
621         case CLOSE_WAIT:
622         case CLOSING:
623         case LAST_ACK:
624         case TIME_WAIT:
625                 break;
626         default:
627                 abort();
628         }
629
630         // 1b. Drop packets with a sequence number not in our receive window.
631
632         bool acceptable;
633
634         if(c->state == SYN_SENT)
635                 acceptable = true;
636
637         // TODO: handle packets overlapping c->rcv.nxt.
638 #if 0
639         // Only use this when accepting out-of-order packets.
640         else if(len == 0)
641                 if(c->rcv.wnd == 0)
642                         acceptable = hdr.seq == c->rcv.nxt;
643                 else
644                         acceptable = (seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt + c->rcv.wnd) < 0);
645         else
646                 if(c->rcv.wnd == 0)
647                         // We don't accept data when the receive window is zero.
648                         acceptable = false;
649                 else
650                         // Both start and end of packet must be within the receive window
651                         acceptable = (seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt + c->rcv.wnd) < 0)
652                                 || (seqdiff(hdr.seq + len + 1, c->rcv.nxt) >= 0 && seqdiff(hdr.seq + len - 1, c->rcv.nxt + c->rcv.wnd) < 0);
653 #else
654         if(c->state != SYN_SENT)
655                 acceptable = hdr.seq == c->rcv.nxt;
656 #endif
657
658         if(!acceptable) {
659                 debug("Packet not acceptable, %u <= %u + %zu < %u\n", c->rcv.nxt, hdr.seq, len, c->rcv.nxt + c->rcv.wnd);
660                 // Ignore unacceptable RST packets.
661                 if(hdr.ctl & RST)
662                         return 0;
663                 // Otherwise, send an ACK back in the hope things improve.
664                 ack(c, true);
665                 return 0;
666         }
667
668         c->snd.wnd = hdr.wnd; // TODO: move below
669
670         // 1c. Drop packets with an invalid ACK.
671         // ackno should not roll back, and it should also not be bigger than snd.nxt.
672
673         if(hdr.ctl & ACK && (seqdiff(hdr.ack, c->snd.nxt) > 0 || seqdiff(hdr.ack, c->snd.una) < 0)) {
674                 debug("Packet ack seqno out of range, %u %u %u\n", hdr.ack, c->snd.una, c->snd.nxt);
675                 // Ignore unacceptable RST packets.
676                 if(hdr.ctl & RST)
677                         return 0;
678                 goto reset;
679         }
680
681         // 2. Handle RST packets
682
683         if(hdr.ctl & RST) {
684                 switch(c->state) {
685                 case SYN_SENT:
686                         if(!(hdr.ctl & ACK))
687                                 return 0;
688                         // The peer has refused our connection.
689                         set_state(c, CLOSED);
690                         errno = ECONNREFUSED;
691                         if(c->recv)
692                                 c->recv(c, NULL, 0);
693                         return 0;
694                 case SYN_RECEIVED:
695                         if(hdr.ctl & ACK)
696                                 return 0;
697                         // We haven't told the application about this connection yet. Silently delete.
698                         free_connection(c);
699                         return 0;
700                 case ESTABLISHED:
701                 case FIN_WAIT_1:
702                 case FIN_WAIT_2:
703                 case CLOSE_WAIT:
704                         if(hdr.ctl & ACK)
705                                 return 0;
706                         // The peer has aborted our connection.
707                         set_state(c, CLOSED);
708                         errno = ECONNRESET;
709                         if(c->recv)
710                                 c->recv(c, NULL, 0);
711                         return 0;
712                 case CLOSING:
713                 case LAST_ACK:
714                 case TIME_WAIT:
715                         if(hdr.ctl & ACK)
716                                 return 0;
717                         // As far as the application is concerned, the connection has already been closed.
718                         // If it has called utcp_close() already, we can immediately free this connection.
719                         if(c->reapable) {
720                                 free_connection(c);
721                                 return 0;
722                         }
723                         // Otherwise, immediately move to the CLOSED state.
724                         set_state(c, CLOSED);
725                         return 0;
726                 default:
727                         abort();
728                 }
729         }
730
731         // 3. Advance snd.una
732
733         uint32_t advanced = seqdiff(hdr.ack, c->snd.una);
734         prevrcvnxt = c->rcv.nxt;
735
736         if(advanced) {
737                 int32_t data_acked = advanced;
738
739                 switch(c->state) {
740                         case SYN_SENT:
741                         case SYN_RECEIVED:
742                                 data_acked--;
743                                 break;
744                         // TODO: handle FIN as well.
745                         default:
746                                 break;
747                 }
748
749                 assert(data_acked >= 0);
750
751                 int32_t bufused = seqdiff(c->snd.last, c->snd.una);
752                 assert(data_acked <= bufused);
753
754                 if(data_acked)
755                         buffer_get(&c->sndbuf, NULL, data_acked);
756
757                 c->snd.una = hdr.ack;
758
759                 c->dupack = 0;
760                 c->snd.cwnd += utcp->mtu;
761                 if(c->snd.cwnd > c->sndbuf.maxsize)
762                         c->snd.cwnd = c->sndbuf.maxsize;
763
764                 // Check if we have sent a FIN that is now ACKed.
765                 switch(c->state) {
766                 case FIN_WAIT_1:
767                         if(c->snd.una == c->snd.last)
768                                 set_state(c, FIN_WAIT_2);
769                         break;
770                 case CLOSING:
771                         if(c->snd.una == c->snd.last) {
772                                 gettimeofday(&c->conn_timeout, NULL);
773                                 c->conn_timeout.tv_sec += 60;
774                                 set_state(c, TIME_WAIT);
775                         }
776                         break;
777                 default:
778                         break;
779                 }
780         } else {
781                 if(!len) {
782                         c->dupack++;
783                         if(c->dupack == 3) {
784                                 debug("Triplicate ACK\n");
785                                 fprintf(stderr, "Triplicate ACK\n");
786                                 //TODO: Resend one packet and go to fast recovery mode. See RFC 6582.
787                                 //We do a very simple variant here; reset the nxt pointer to the last acknowledged packet from the peer.
788                                 //This will cause us to start retransmitting, but at the same speed as the incoming ACKs arrive,
789                                 //thus preventing a drop in speed.
790                                 c->snd.nxt = c->snd.una;
791                         }
792                 }
793         }
794
795         // 4. Update timers
796
797         if(advanced) {
798                 timerclear(&c->conn_timeout); // It will be set anew in utcp_timeout() if c->snd.una != c->snd.nxt.
799                 if(c->snd.una == c->snd.nxt)
800                         timerclear(&c->rtrx_timeout);
801         }
802
803         // 5. Process SYN stuff
804
805         if(hdr.ctl & SYN) {
806                 switch(c->state) {
807                 case SYN_SENT:
808                         // This is a SYNACK. It should always have ACKed the SYN.
809                         if(!advanced)
810                                 goto reset;
811                         c->rcv.irs = hdr.seq;
812                         c->rcv.nxt = hdr.seq;
813                         set_state(c, ESTABLISHED);
814                         // TODO: notify application of this somehow.
815                         break;
816                 case SYN_RECEIVED:
817                 case ESTABLISHED:
818                 case FIN_WAIT_1:
819                 case FIN_WAIT_2:
820                 case CLOSE_WAIT:
821                 case CLOSING:
822                 case LAST_ACK:
823                 case TIME_WAIT:
824                         // Ehm, no. We should never receive a second SYN.
825                         goto reset;
826                 default:
827                         abort();
828                 }
829
830                 // SYN counts as one sequence number
831                 c->rcv.nxt++;
832         }
833
834         // 6. Process new data
835
836         if(c->state == SYN_RECEIVED) {
837                 // This is the ACK after the SYNACK. It should always have ACKed the SYNACK.
838                 if(!advanced)
839                         goto reset;
840
841                 // Are we still LISTENing?
842                 if(utcp->accept)
843                         utcp->accept(c, c->src);
844
845                 if(c->state != ESTABLISHED) {
846                         set_state(c, CLOSED);
847                         c->reapable = true;
848                         goto reset;
849                 }
850         }
851
852         if(len) {
853                 switch(c->state) {
854                 case SYN_SENT:
855                 case SYN_RECEIVED:
856                         // This should never happen.
857                         abort();
858                 case ESTABLISHED:
859                 case FIN_WAIT_1:
860                 case FIN_WAIT_2:
861                         break;
862                 case CLOSE_WAIT:
863                 case CLOSING:
864                 case LAST_ACK:
865                 case TIME_WAIT:
866                         // Ehm no, We should never receive more data after a FIN.
867                         goto reset;
868                 default:
869                         abort();
870                 }
871
872                 ssize_t rxd;
873
874                 if(c->recv) {
875                         rxd = c->recv(c, data, len);
876                         if(rxd != len) {
877                                 // TODO: once we have a receive buffer, handle the application not accepting all data.
878                                 abort();
879                         }
880                         if(rxd < 0)
881                                 rxd = 0;
882                         else if(rxd > len)
883                                 rxd = len; // Bad application, bad!
884                 } else {
885                         rxd = len;
886                 }
887
888                 c->rcv.nxt += len;
889         }
890
891         // 7. Process FIN stuff
892
893         if(hdr.ctl & FIN) {
894                 switch(c->state) {
895                 case SYN_SENT:
896                 case SYN_RECEIVED:
897                         // This should never happen.
898                         abort();
899                 case ESTABLISHED:
900                         set_state(c, CLOSE_WAIT);
901                         break;
902                 case FIN_WAIT_1:
903                         set_state(c, CLOSING);
904                         break;
905                 case FIN_WAIT_2:
906                         gettimeofday(&c->conn_timeout, NULL);
907                         c->conn_timeout.tv_sec += 60;
908                         set_state(c, TIME_WAIT);
909                         break;
910                 case CLOSE_WAIT:
911                 case CLOSING:
912                 case LAST_ACK:
913                 case TIME_WAIT:
914                         // Ehm, no. We should never receive a second FIN.
915                         goto reset;
916                 default:
917                         abort();
918                 }
919
920                 // FIN counts as one sequence number
921                 c->rcv.nxt++;
922                 len++;
923
924                 // Inform the application that the peer closed the connection.
925                 if(c->recv) {
926                         errno = 0;
927                         c->recv(c, NULL, 0);
928                 }
929         }
930
931         // Now we send something back if:
932         // - we advanced rcv.nxt (ie, we got some data that needs to be ACKed)
933         //   -> sendatleastone = true
934         // - or we got an ack, so we should maybe send a bit more data
935         //   -> sendatleastone = false
936
937 ack:
938         ack(c, prevrcvnxt != c->rcv.nxt);
939         return 0;
940
941 reset:
942         swap_ports(&hdr);
943         hdr.wnd = 0;
944         if(hdr.ctl & ACK) {
945                 hdr.seq = hdr.ack;
946                 hdr.ctl = RST;
947         } else {
948                 hdr.ack = hdr.seq + len;
949                 hdr.seq = 0;
950                 hdr.ctl = RST | ACK;
951         }
952         print_packet(utcp, "send", &hdr, sizeof hdr);
953         utcp->send(utcp, &hdr, sizeof hdr);
954         return 0;
955
956 }
957
958 int utcp_shutdown(struct utcp_connection *c, int dir) {
959         debug("%p shutdown %d\n", c ? c->utcp : NULL, dir);
960         if(!c) {
961                 errno = EFAULT;
962                 return -1;
963         }
964
965         if(c->reapable) {
966                 debug("Error: shutdown() called on closed connection %p\n", c);
967                 errno = EBADF;
968                 return -1;
969         }
970
971         // TODO: handle dir
972
973         switch(c->state) {
974         case CLOSED:
975                 return 0;
976         case LISTEN:
977         case SYN_SENT:
978                 set_state(c, CLOSED);
979                 return 0;
980
981         case SYN_RECEIVED:
982         case ESTABLISHED:
983                 set_state(c, FIN_WAIT_1);
984                 break;
985         case FIN_WAIT_1:
986         case FIN_WAIT_2:
987                 return 0;
988         case CLOSE_WAIT:
989                 set_state(c, CLOSING);
990                 break;
991
992         case CLOSING:
993         case LAST_ACK:
994         case TIME_WAIT:
995                 return 0;
996         }
997
998         c->snd.last++;
999
1000         ack(c, false);
1001         return 0;
1002 }
1003
1004 int utcp_close(struct utcp_connection *c) {
1005         if(utcp_shutdown(c, SHUT_RDWR))
1006                 return -1;
1007         c->recv = NULL;
1008         c->poll = NULL;
1009         c->reapable = true;
1010         return 0;
1011 }
1012
1013 int utcp_abort(struct utcp_connection *c) {
1014         if(!c) {
1015                 errno = EFAULT;
1016                 return -1;
1017         }
1018
1019         if(c->reapable) {
1020                 debug("Error: abort() called on closed connection %p\n", c);
1021                 errno = EBADF;
1022                 return -1;
1023         }
1024
1025         c->recv = NULL;
1026         c->poll = NULL;
1027         c->reapable = true;
1028
1029         switch(c->state) {
1030         case CLOSED:
1031                 return 0;
1032         case LISTEN:
1033         case SYN_SENT:
1034         case CLOSING:
1035         case LAST_ACK:
1036         case TIME_WAIT:
1037                 set_state(c, CLOSED);
1038                 return 0;
1039
1040         case SYN_RECEIVED:
1041         case ESTABLISHED:
1042         case FIN_WAIT_1:
1043         case FIN_WAIT_2:
1044         case CLOSE_WAIT:
1045                 set_state(c, CLOSED);
1046                 break;
1047         }
1048
1049         // Send RST
1050
1051         struct hdr hdr;
1052
1053         hdr.src = c->src;
1054         hdr.dst = c->dst;
1055         hdr.seq = c->snd.nxt;
1056         hdr.ack = 0;
1057         hdr.wnd = 0;
1058         hdr.ctl = RST;
1059
1060         print_packet(c->utcp, "send", &hdr, sizeof hdr);
1061         c->utcp->send(c->utcp, &hdr, sizeof hdr);
1062         return 0;
1063 }
1064
1065 /* Handle timeouts.
1066  * One call to this function will loop through all connections,
1067  * checking if something needs to be resent or not.
1068  * The return value is the time to the next timeout in milliseconds,
1069  * or maybe a negative value if the timeout is infinite.
1070  */
1071 struct timeval utcp_timeout(struct utcp *utcp) {
1072         struct timeval now;
1073         gettimeofday(&now, NULL);
1074         struct timeval next = {now.tv_sec + 3600, now.tv_usec};
1075
1076         for(int i = 0; i < utcp->nconnections; i++) {
1077                 struct utcp_connection *c = utcp->connections[i];
1078                 if(!c)
1079                         continue;
1080
1081                 if(c->state == CLOSED) {
1082                         if(c->reapable) {
1083                                 debug("Reaping %p\n", c);
1084                                 free_connection(c);
1085                                 i--;
1086                         }
1087                         continue;
1088                 }
1089
1090                 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &now, <)) {
1091                         errno = ETIMEDOUT;
1092                         c->state = CLOSED;
1093                         if(c->recv)
1094                                 c->recv(c, NULL, 0);
1095                         continue;
1096                 }
1097
1098                 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &now, <)) {
1099                         retransmit(c);
1100                 }
1101
1102                 if(c->poll && buffer_free(&c->sndbuf) && (c->state == ESTABLISHED || c->state == CLOSE_WAIT))
1103                         c->poll(c, buffer_free(&c->sndbuf));
1104
1105                 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &next, <))
1106                         next = c->conn_timeout;
1107
1108                 if(c->snd.nxt != c->snd.una) {
1109                         c->rtrx_timeout = now;
1110                         c->rtrx_timeout.tv_sec++;
1111                 } else {
1112                         timerclear(&c->rtrx_timeout);
1113                 }
1114
1115                 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &next, <))
1116                         next = c->rtrx_timeout;
1117         }
1118
1119         struct timeval diff;
1120         timersub(&next, &now, &diff);
1121         return diff;
1122 }
1123
1124 struct utcp *utcp_init(utcp_accept_t accept, utcp_pre_accept_t pre_accept, utcp_send_t send, void *priv) {
1125         struct utcp *utcp = calloc(1, sizeof *utcp);
1126         if(!utcp)
1127                 return NULL;
1128
1129         if(!send) {
1130                 errno = EFAULT;
1131                 return NULL;
1132         }
1133
1134         utcp->accept = accept;
1135         utcp->pre_accept = pre_accept;
1136         utcp->send = send;
1137         utcp->priv = priv;
1138         utcp->mtu = 1000;
1139         utcp->timeout = 60;
1140
1141         return utcp;
1142 }
1143
1144 void utcp_exit(struct utcp *utcp) {
1145         if(!utcp)
1146                 return;
1147         for(int i = 0; i < utcp->nconnections; i++) {
1148                 if(!utcp->connections[i]->reapable)
1149                         debug("Warning, freeing unclosed connection %p\n", utcp->connections[i]);
1150                 buffer_exit(&utcp->connections[i]->sndbuf);
1151                 free(utcp->connections[i]);
1152         }
1153         free(utcp->connections);
1154         free(utcp);
1155 }
1156
1157 uint16_t utcp_get_mtu(struct utcp *utcp) {
1158         return utcp->mtu;
1159 }
1160
1161 void utcp_set_mtu(struct utcp *utcp, uint16_t mtu) {
1162         // TODO: handle overhead of the header
1163         utcp->mtu = mtu;
1164 }
1165
1166 int utcp_get_user_timeout(struct utcp *u) {
1167         return u->timeout;
1168 }
1169
1170 void utcp_set_user_timeout(struct utcp *u, int timeout) {
1171         u->timeout = timeout;
1172 }
1173
1174 size_t utcp_get_sndbuf(struct utcp_connection *c) {
1175         return c->sndbuf.maxsize;
1176 }
1177
1178 size_t utcp_get_sndbuf_free(struct utcp_connection *c) {
1179         return buffer_free(&c->sndbuf);
1180 }
1181
1182 void utcp_set_sndbuf(struct utcp_connection *c, size_t size) {
1183         c->sndbuf.maxsize = size;
1184         if(c->sndbuf.maxsize != size)
1185                 c->sndbuf.maxsize = -1;
1186 }
1187
1188 bool utcp_get_nodelay(struct utcp_connection *c) {
1189         return c->nodelay;
1190 }
1191
1192 void utcp_set_nodelay(struct utcp_connection *c, bool nodelay) {
1193         c->nodelay = nodelay;
1194 }
1195
1196 bool utcp_get_keepalive(struct utcp_connection *c) {
1197         return c->keepalive;
1198 }
1199
1200 void utcp_set_keepalive(struct utcp_connection *c, bool keepalive) {
1201         c->keepalive = keepalive;
1202 }
1203
1204 size_t utcp_get_outq(struct utcp_connection *c) {
1205         return seqdiff(c->snd.nxt, c->snd.una);
1206 }
1207
1208 void utcp_set_recv_cb(struct utcp_connection *c, utcp_recv_t recv) {
1209         c->recv = recv;
1210 }
1211
1212 void utcp_set_poll_cb(struct utcp_connection *c, utcp_poll_t poll) {
1213         c->poll = poll;
1214 }