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