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