]> git.meshlink.io Git - utcp/blob - utcp.c
Reset the snd.nxt pointer when starting packet retransmission.
[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 SYN_SENT:
469                         // Send our SYN again
470                         pkt->hdr.seq = c->snd.iss;
471                         pkt->hdr.ack = 0;
472                         pkt->hdr.wnd = c->rcv.wnd;
473                         pkt->hdr.ctl = SYN;
474                         print_packet(c->utcp, "rtrx", pkt, sizeof pkt->hdr);
475                         utcp->send(utcp, pkt, sizeof pkt->hdr);
476                         break;
477
478                 case SYN_RECEIVED:
479                         // Send SYNACK again
480                         pkt->hdr.seq = c->snd.nxt;
481                         pkt->hdr.ack = c->rcv.nxt;
482                         pkt->hdr.ctl = SYN | ACK;
483                         print_packet(c->utcp, "rtrx", pkt, sizeof pkt->hdr);
484                         utcp->send(utcp, pkt, sizeof pkt->hdr);
485                         break;
486
487                 case ESTABLISHED:
488                 case FIN_WAIT_1:
489                 case CLOSE_WAIT:
490                 case CLOSING:
491                 case LAST_ACK:
492                         // Send unacked data again.
493                         pkt->hdr.seq = c->snd.una;
494                         pkt->hdr.ack = c->rcv.nxt;
495                         pkt->hdr.ctl = ACK;
496                         uint32_t len = seqdiff(c->snd.last, c->snd.una);
497                         if(len > utcp->mtu)
498                                 len = utcp->mtu;
499                         if(fin_wanted(c, c->snd.una + len)) {
500                                 len--;
501                                 pkt->hdr.ctl |= FIN;
502                         }
503                         c->snd.nxt = c->snd.una + len;
504                         buffer_copy(&c->sndbuf, pkt->data, 0, len);
505                         print_packet(c->utcp, "rtrx", pkt, sizeof pkt->hdr + len);
506                         utcp->send(utcp, pkt, sizeof pkt->hdr + len);
507                         break;
508
509                 case CLOSED:
510                 case LISTEN:
511                 case TIME_WAIT:
512                 case FIN_WAIT_2:
513                         // We shouldn't need to retransmit anything in this state.
514 #ifdef UTCP_DEBUG
515                         abort();
516 #endif
517                         timerclear(&c->rtrx_timeout);
518                         break;
519         }
520
521         free(pkt);
522 }
523
524
525 ssize_t utcp_recv(struct utcp *utcp, const void *data, size_t len) {
526         if(!utcp) {
527                 errno = EFAULT;
528                 return -1;
529         }
530
531         if(!len)
532                 return 0;
533
534         if(!data) {
535                 errno = EFAULT;
536                 return -1;
537         }
538
539         print_packet(utcp, "recv", data, len);
540
541         // Drop packets smaller than the header
542
543         struct hdr hdr;
544         if(len < sizeof hdr) {
545                 errno = EBADMSG;
546                 return -1;
547         }
548
549         // Make a copy from the potentially unaligned data to a struct hdr
550
551         memcpy(&hdr, data, sizeof hdr);
552         data += sizeof hdr;
553         len -= sizeof hdr;
554
555         // Drop packets with an unknown CTL flag
556
557         if(hdr.ctl & ~(SYN | ACK | RST | FIN)) {
558                 errno = EBADMSG;
559                 return -1;
560         }
561
562         // Try to match the packet to an existing connection
563
564         struct utcp_connection *c = find_connection(utcp, hdr.dst, hdr.src);
565
566         // Is it for a new connection?
567
568         if(!c) {
569                 // Ignore RST packets
570
571                 if(hdr.ctl & RST)
572                         return 0;
573
574                 // Is it a SYN packet and are we LISTENing?
575
576                 if(hdr.ctl & SYN && !(hdr.ctl & ACK) && utcp->accept) {
577                         // If we don't want to accept it, send a RST back
578                         if((utcp->pre_accept && !utcp->pre_accept(utcp, hdr.dst))) {
579                                 len = 1;
580                                 goto reset;
581                         }
582
583                         // Try to allocate memory, otherwise send a RST back
584                         c = allocate_connection(utcp, hdr.dst, hdr.src);
585                         if(!c) {
586                                 len = 1;
587                                 goto reset;
588                         }
589
590                         // Return SYN+ACK, go to SYN_RECEIVED state
591                         c->snd.wnd = hdr.wnd;
592                         c->rcv.irs = hdr.seq;
593                         c->rcv.nxt = c->rcv.irs + 1;
594                         set_state(c, SYN_RECEIVED);
595
596                         hdr.dst = c->dst;
597                         hdr.src = c->src;
598                         hdr.ack = c->rcv.irs + 1;
599                         hdr.seq = c->snd.iss;
600                         hdr.ctl = SYN | ACK;
601                         print_packet(c->utcp, "send", &hdr, sizeof hdr);
602                         utcp->send(utcp, &hdr, sizeof hdr);
603                 } else {
604                         // No, we don't want your packets, send a RST back
605                         len = 1;
606                         goto reset;
607                 }
608
609                 return 0;
610         }
611
612         debug("%p state %s\n", c->utcp, strstate[c->state]);
613
614         // In case this is for a CLOSED connection, ignore the packet.
615         // TODO: make it so incoming packets can never match a CLOSED connection.
616
617         if(c->state == CLOSED)
618                 return 0;
619
620         // It is for an existing connection.
621
622         uint32_t prevrcvnxt = c->rcv.nxt;
623
624         // 1. Drop invalid packets.
625
626         // 1a. Drop packets that should not happen in our current state.
627
628         switch(c->state) {
629         case SYN_SENT:
630         case SYN_RECEIVED:
631         case ESTABLISHED:
632         case FIN_WAIT_1:
633         case FIN_WAIT_2:
634         case CLOSE_WAIT:
635         case CLOSING:
636         case LAST_ACK:
637         case TIME_WAIT:
638                 break;
639         default:
640 #ifdef UTCP_DEBUG
641                 abort();
642 #endif
643                 break;
644         }
645
646         // 1b. Drop packets with a sequence number not in our receive window.
647
648         bool acceptable;
649
650         if(c->state == SYN_SENT)
651                 acceptable = true;
652
653         // TODO: handle packets overlapping c->rcv.nxt.
654 #if 0
655         // Only use this when accepting out-of-order packets.
656         else if(len == 0)
657                 if(c->rcv.wnd == 0)
658                         acceptable = hdr.seq == c->rcv.nxt;
659                 else
660                         acceptable = (seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt + c->rcv.wnd) < 0);
661         else
662                 if(c->rcv.wnd == 0)
663                         // We don't accept data when the receive window is zero.
664                         acceptable = false;
665                 else
666                         // Both start and end of packet must be within the receive window
667                         acceptable = (seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt + c->rcv.wnd) < 0)
668                                 || (seqdiff(hdr.seq + len + 1, c->rcv.nxt) >= 0 && seqdiff(hdr.seq + len - 1, c->rcv.nxt + c->rcv.wnd) < 0);
669 #else
670         if(c->state != SYN_SENT)
671                 acceptable = hdr.seq == c->rcv.nxt;
672 #endif
673
674         if(!acceptable) {
675                 debug("Packet not acceptable, %u <= %u + %zu < %u\n", c->rcv.nxt, hdr.seq, len, c->rcv.nxt + c->rcv.wnd);
676                 // Ignore unacceptable RST packets.
677                 if(hdr.ctl & RST)
678                         return 0;
679                 // Otherwise, send an ACK back in the hope things improve.
680                 ack(c, true);
681                 return 0;
682         }
683
684         c->snd.wnd = hdr.wnd; // TODO: move below
685
686         // 1c. Drop packets with an invalid ACK.
687         // ackno should not roll back, and it should also not be bigger than snd.nxt.
688
689         if(hdr.ctl & ACK && (seqdiff(hdr.ack, c->snd.nxt) > 0 || seqdiff(hdr.ack, c->snd.una) < 0)) {
690                 debug("Packet ack seqno out of range, %u %u %u\n", hdr.ack, c->snd.una, c->snd.nxt);
691                 // Ignore unacceptable RST packets.
692                 if(hdr.ctl & RST)
693                         return 0;
694                 goto reset;
695         }
696
697         // 2. Handle RST packets
698
699         if(hdr.ctl & RST) {
700                 switch(c->state) {
701                 case SYN_SENT:
702                         if(!(hdr.ctl & ACK))
703                                 return 0;
704                         // The peer has refused our connection.
705                         set_state(c, CLOSED);
706                         errno = ECONNREFUSED;
707                         if(c->recv)
708                                 c->recv(c, NULL, 0);
709                         return 0;
710                 case SYN_RECEIVED:
711                         if(hdr.ctl & ACK)
712                                 return 0;
713                         // We haven't told the application about this connection yet. Silently delete.
714                         free_connection(c);
715                         return 0;
716                 case ESTABLISHED:
717                 case FIN_WAIT_1:
718                 case FIN_WAIT_2:
719                 case CLOSE_WAIT:
720                         if(hdr.ctl & ACK)
721                                 return 0;
722                         // The peer has aborted our connection.
723                         set_state(c, CLOSED);
724                         errno = ECONNRESET;
725                         if(c->recv)
726                                 c->recv(c, NULL, 0);
727                         return 0;
728                 case CLOSING:
729                 case LAST_ACK:
730                 case TIME_WAIT:
731                         if(hdr.ctl & ACK)
732                                 return 0;
733                         // As far as the application is concerned, the connection has already been closed.
734                         // If it has called utcp_close() already, we can immediately free this connection.
735                         if(c->reapable) {
736                                 free_connection(c);
737                                 return 0;
738                         }
739                         // Otherwise, immediately move to the CLOSED state.
740                         set_state(c, CLOSED);
741                         return 0;
742                 default:
743 #ifdef UTCP_DEBUG
744                         abort();
745 #endif
746                         break;
747                 }
748         }
749
750         // 3. Advance snd.una
751
752         uint32_t advanced = seqdiff(hdr.ack, c->snd.una);
753         prevrcvnxt = c->rcv.nxt;
754
755         if(advanced) {
756                 int32_t data_acked = advanced;
757
758                 switch(c->state) {
759                         case SYN_SENT:
760                         case SYN_RECEIVED:
761                                 data_acked--;
762                                 break;
763                         // TODO: handle FIN as well.
764                         default:
765                                 break;
766                 }
767
768                 assert(data_acked >= 0);
769
770                 int32_t bufused = seqdiff(c->snd.last, c->snd.una);
771                 assert(data_acked <= bufused);
772
773                 if(data_acked)
774                         buffer_get(&c->sndbuf, NULL, data_acked);
775
776                 c->snd.una = hdr.ack;
777
778                 c->dupack = 0;
779                 c->snd.cwnd += utcp->mtu;
780                 if(c->snd.cwnd > c->sndbuf.maxsize)
781                         c->snd.cwnd = c->sndbuf.maxsize;
782
783                 // Check if we have sent a FIN that is now ACKed.
784                 switch(c->state) {
785                 case FIN_WAIT_1:
786                         if(c->snd.una == c->snd.last)
787                                 set_state(c, FIN_WAIT_2);
788                         break;
789                 case CLOSING:
790                         if(c->snd.una == c->snd.last) {
791                                 gettimeofday(&c->conn_timeout, NULL);
792                                 c->conn_timeout.tv_sec += 60;
793                                 set_state(c, TIME_WAIT);
794                         }
795                         break;
796                 default:
797                         break;
798                 }
799         } else {
800                 if(!len) {
801                         c->dupack++;
802                         if(c->dupack == 3) {
803                                 debug("Triplicate ACK\n");
804                                 //TODO: Resend one packet and go to fast recovery mode. See RFC 6582.
805                                 //We do a very simple variant here; reset the nxt pointer to the last acknowledged packet from the peer.
806                                 //This will cause us to start retransmitting, but at the same speed as the incoming ACKs arrive,
807                                 //thus preventing a drop in speed.
808                                 c->snd.nxt = c->snd.una;
809                         }
810                 }
811         }
812
813         // 4. Update timers
814
815         if(advanced) {
816                 timerclear(&c->conn_timeout); // It will be set anew in utcp_timeout() if c->snd.una != c->snd.nxt.
817                 if(c->snd.una == c->snd.nxt)
818                         timerclear(&c->rtrx_timeout);
819         }
820
821         // 5. Process SYN stuff
822
823         if(hdr.ctl & SYN) {
824                 switch(c->state) {
825                 case SYN_SENT:
826                         // This is a SYNACK. It should always have ACKed the SYN.
827                         if(!advanced)
828                                 goto reset;
829                         c->rcv.irs = hdr.seq;
830                         c->rcv.nxt = hdr.seq;
831                         set_state(c, ESTABLISHED);
832                         // TODO: notify application of this somehow.
833                         break;
834                 case SYN_RECEIVED:
835                 case ESTABLISHED:
836                 case FIN_WAIT_1:
837                 case FIN_WAIT_2:
838                 case CLOSE_WAIT:
839                 case CLOSING:
840                 case LAST_ACK:
841                 case TIME_WAIT:
842                         // Ehm, no. We should never receive a second SYN.
843                         goto reset;
844                 default:
845 #ifdef UTCP_DEBUG
846                         abort();
847 #endif
848                         return 0;
849                 }
850
851                 // SYN counts as one sequence number
852                 c->rcv.nxt++;
853         }
854
855         // 6. Process new data
856
857         if(c->state == SYN_RECEIVED) {
858                 // This is the ACK after the SYNACK. It should always have ACKed the SYNACK.
859                 if(!advanced)
860                         goto reset;
861
862                 // Are we still LISTENing?
863                 if(utcp->accept)
864                         utcp->accept(c, c->src);
865
866                 if(c->state != ESTABLISHED) {
867                         set_state(c, CLOSED);
868                         c->reapable = true;
869                         goto reset;
870                 }
871         }
872
873         if(len) {
874                 switch(c->state) {
875                 case SYN_SENT:
876                 case SYN_RECEIVED:
877                         // This should never happen.
878 #ifdef UTCP_DEBUG
879                         abort();
880 #endif
881                         return 0;
882                 case ESTABLISHED:
883                 case FIN_WAIT_1:
884                 case FIN_WAIT_2:
885                         break;
886                 case CLOSE_WAIT:
887                 case CLOSING:
888                 case LAST_ACK:
889                 case TIME_WAIT:
890                         // Ehm no, We should never receive more data after a FIN.
891                         goto reset;
892                 default:
893 #ifdef UTCP_DEBUG
894                         abort();
895 #endif
896                         return 0;
897                 }
898
899                 ssize_t rxd;
900
901                 if(c->recv) {
902                         rxd = c->recv(c, data, len);
903                         if(rxd != len) {
904                                 // TODO: once we have a receive buffer, handle the application not accepting all data.
905                                 abort();
906                         }
907                         if(rxd < 0)
908                                 rxd = 0;
909                         else if(rxd > len)
910                                 rxd = len; // Bad application, bad!
911                 } else {
912                         rxd = len;
913                 }
914
915                 c->rcv.nxt += len;
916         }
917
918         // 7. Process FIN stuff
919
920         if(hdr.ctl & FIN) {
921                 switch(c->state) {
922                 case SYN_SENT:
923                 case SYN_RECEIVED:
924                         // This should never happen.
925 #ifdef UTCP_DEBUG
926                         abort();
927 #endif
928                         break;
929                 case ESTABLISHED:
930                         set_state(c, CLOSE_WAIT);
931                         break;
932                 case FIN_WAIT_1:
933                         set_state(c, CLOSING);
934                         break;
935                 case FIN_WAIT_2:
936                         gettimeofday(&c->conn_timeout, NULL);
937                         c->conn_timeout.tv_sec += 60;
938                         set_state(c, TIME_WAIT);
939                         break;
940                 case CLOSE_WAIT:
941                 case CLOSING:
942                 case LAST_ACK:
943                 case TIME_WAIT:
944                         // Ehm, no. We should never receive a second FIN.
945                         goto reset;
946                 default:
947 #ifdef UTCP_DEBUG
948                         abort();
949 #endif
950                         break;
951                 }
952
953                 // FIN counts as one sequence number
954                 c->rcv.nxt++;
955                 len++;
956
957                 // Inform the application that the peer closed the connection.
958                 if(c->recv) {
959                         errno = 0;
960                         c->recv(c, NULL, 0);
961                 }
962         }
963
964         // Now we send something back if:
965         // - we advanced rcv.nxt (ie, we got some data that needs to be ACKed)
966         //   -> sendatleastone = true
967         // - or we got an ack, so we should maybe send a bit more data
968         //   -> sendatleastone = false
969
970 ack:
971         ack(c, prevrcvnxt != c->rcv.nxt);
972         return 0;
973
974 reset:
975         swap_ports(&hdr);
976         hdr.wnd = 0;
977         if(hdr.ctl & ACK) {
978                 hdr.seq = hdr.ack;
979                 hdr.ctl = RST;
980         } else {
981                 hdr.ack = hdr.seq + len;
982                 hdr.seq = 0;
983                 hdr.ctl = RST | ACK;
984         }
985         print_packet(utcp, "send", &hdr, sizeof hdr);
986         utcp->send(utcp, &hdr, sizeof hdr);
987         return 0;
988
989 }
990
991 int utcp_shutdown(struct utcp_connection *c, int dir) {
992         debug("%p shutdown %d at %u\n", c ? c->utcp : NULL, dir, c ? c->snd.last : 0);
993         if(!c) {
994                 errno = EFAULT;
995                 return -1;
996         }
997
998         if(c->reapable) {
999                 debug("Error: shutdown() called on closed connection %p\n", c);
1000                 errno = EBADF;
1001                 return -1;
1002         }
1003
1004         if(!(dir == UTCP_SHUT_RD || dir == UTCP_SHUT_WR || dir == UTCP_SHUT_RDWR)) {
1005                 errno = EINVAL;
1006                 return -1;
1007         }
1008
1009         // TCP does not have a provision for stopping incoming packets.
1010         // The best we can do is to just ignore them.
1011         if(dir == UTCP_SHUT_RD || dir == UTCP_SHUT_RDWR)
1012                 c->recv = NULL;
1013
1014         // The rest of the code deals with shutting down writes.
1015         if(dir == UTCP_SHUT_RD)
1016                 return 0;
1017
1018         switch(c->state) {
1019         case CLOSED:
1020         case LISTEN:
1021                 errno = ENOTCONN;
1022                 return -1;
1023
1024         case SYN_SENT:
1025                 set_state(c, CLOSED);
1026                 return 0;
1027
1028         case SYN_RECEIVED:
1029         case ESTABLISHED:
1030                 set_state(c, FIN_WAIT_1);
1031                 break;
1032         case FIN_WAIT_1:
1033         case FIN_WAIT_2:
1034                 return 0;
1035         case CLOSE_WAIT:
1036                 set_state(c, CLOSING);
1037                 break;
1038
1039         case CLOSING:
1040         case LAST_ACK:
1041         case TIME_WAIT:
1042                 return 0;
1043         }
1044
1045         c->snd.last++;
1046
1047         ack(c, false);
1048         return 0;
1049 }
1050
1051 int utcp_close(struct utcp_connection *c) {
1052         if(utcp_shutdown(c, SHUT_RDWR))
1053                 return -1;
1054         c->recv = NULL;
1055         c->poll = NULL;
1056         c->reapable = true;
1057         return 0;
1058 }
1059
1060 int utcp_abort(struct utcp_connection *c) {
1061         if(!c) {
1062                 errno = EFAULT;
1063                 return -1;
1064         }
1065
1066         if(c->reapable) {
1067                 debug("Error: abort() called on closed connection %p\n", c);
1068                 errno = EBADF;
1069                 return -1;
1070         }
1071
1072         c->recv = NULL;
1073         c->poll = NULL;
1074         c->reapable = true;
1075
1076         switch(c->state) {
1077         case CLOSED:
1078                 return 0;
1079         case LISTEN:
1080         case SYN_SENT:
1081         case CLOSING:
1082         case LAST_ACK:
1083         case TIME_WAIT:
1084                 set_state(c, CLOSED);
1085                 return 0;
1086
1087         case SYN_RECEIVED:
1088         case ESTABLISHED:
1089         case FIN_WAIT_1:
1090         case FIN_WAIT_2:
1091         case CLOSE_WAIT:
1092                 set_state(c, CLOSED);
1093                 break;
1094         }
1095
1096         // Send RST
1097
1098         struct hdr hdr;
1099
1100         hdr.src = c->src;
1101         hdr.dst = c->dst;
1102         hdr.seq = c->snd.nxt;
1103         hdr.ack = 0;
1104         hdr.wnd = 0;
1105         hdr.ctl = RST;
1106
1107         print_packet(c->utcp, "send", &hdr, sizeof hdr);
1108         c->utcp->send(c->utcp, &hdr, sizeof hdr);
1109         return 0;
1110 }
1111
1112 /* Handle timeouts.
1113  * One call to this function will loop through all connections,
1114  * checking if something needs to be resent or not.
1115  * The return value is the time to the next timeout in milliseconds,
1116  * or maybe a negative value if the timeout is infinite.
1117  */
1118 struct timeval utcp_timeout(struct utcp *utcp) {
1119         struct timeval now;
1120         gettimeofday(&now, NULL);
1121         struct timeval next = {now.tv_sec + 3600, now.tv_usec};
1122
1123         for(int i = 0; i < utcp->nconnections; i++) {
1124                 struct utcp_connection *c = utcp->connections[i];
1125                 if(!c)
1126                         continue;
1127
1128                 if(c->state == CLOSED) {
1129                         if(c->reapable) {
1130                                 debug("Reaping %p\n", c);
1131                                 free_connection(c);
1132                                 i--;
1133                         }
1134                         continue;
1135                 }
1136
1137                 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &now, <)) {
1138                         errno = ETIMEDOUT;
1139                         c->state = CLOSED;
1140                         if(c->recv)
1141                                 c->recv(c, NULL, 0);
1142                         continue;
1143                 }
1144
1145                 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &now, <)) {
1146                         retransmit(c);
1147                 }
1148
1149                 if(c->poll && buffer_free(&c->sndbuf) && (c->state == ESTABLISHED || c->state == CLOSE_WAIT))
1150                         c->poll(c, buffer_free(&c->sndbuf));
1151
1152                 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &next, <))
1153                         next = c->conn_timeout;
1154
1155                 if(c->snd.nxt != c->snd.una) {
1156                         c->rtrx_timeout = now;
1157                         c->rtrx_timeout.tv_sec++;
1158                 } else {
1159                         timerclear(&c->rtrx_timeout);
1160                 }
1161
1162                 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &next, <))
1163                         next = c->rtrx_timeout;
1164         }
1165
1166         struct timeval diff;
1167         timersub(&next, &now, &diff);
1168         return diff;
1169 }
1170
1171 bool utcp_is_active(struct utcp *utcp) {
1172         if(!utcp)
1173                 return false;
1174
1175         for(int i = 0; i < utcp->nconnections; i++)
1176                 if(utcp->connections[i]->state != CLOSED && utcp->connections[i]->state != TIME_WAIT)
1177                         return true;
1178
1179         return false;
1180 }
1181
1182 struct utcp *utcp_init(utcp_accept_t accept, utcp_pre_accept_t pre_accept, utcp_send_t send, void *priv) {
1183         struct utcp *utcp = calloc(1, sizeof *utcp);
1184         if(!utcp)
1185                 return NULL;
1186
1187         if(!send) {
1188                 errno = EFAULT;
1189                 return NULL;
1190         }
1191
1192         utcp->accept = accept;
1193         utcp->pre_accept = pre_accept;
1194         utcp->send = send;
1195         utcp->priv = priv;
1196         utcp->mtu = 1000;
1197         utcp->timeout = 60;
1198
1199         return utcp;
1200 }
1201
1202 void utcp_exit(struct utcp *utcp) {
1203         if(!utcp)
1204                 return;
1205         for(int i = 0; i < utcp->nconnections; i++) {
1206                 if(!utcp->connections[i]->reapable)
1207                         debug("Warning, freeing unclosed connection %p\n", utcp->connections[i]);
1208                 buffer_exit(&utcp->connections[i]->sndbuf);
1209                 free(utcp->connections[i]);
1210         }
1211         free(utcp->connections);
1212         free(utcp);
1213 }
1214
1215 uint16_t utcp_get_mtu(struct utcp *utcp) {
1216         return utcp ? utcp->mtu : 0;
1217 }
1218
1219 void utcp_set_mtu(struct utcp *utcp, uint16_t mtu) {
1220         // TODO: handle overhead of the header
1221         if(utcp)
1222                 utcp->mtu = mtu;
1223 }
1224
1225 int utcp_get_user_timeout(struct utcp *u) {
1226         return u ? u->timeout : 0;
1227 }
1228
1229 void utcp_set_user_timeout(struct utcp *u, int timeout) {
1230         if(u)
1231                 u->timeout = timeout;
1232 }
1233
1234 size_t utcp_get_sndbuf(struct utcp_connection *c) {
1235         return c ? c->sndbuf.maxsize : 0;
1236 }
1237
1238 size_t utcp_get_sndbuf_free(struct utcp_connection *c) {
1239         if(c && (c->state == ESTABLISHED || c->state == CLOSE_WAIT))
1240                 return buffer_free(&c->sndbuf);
1241         else
1242                 return 0;
1243 }
1244
1245 void utcp_set_sndbuf(struct utcp_connection *c, size_t size) {
1246         if(!c)
1247                 return;
1248         c->sndbuf.maxsize = size;
1249         if(c->sndbuf.maxsize != size)
1250                 c->sndbuf.maxsize = -1;
1251 }
1252
1253 bool utcp_get_nodelay(struct utcp_connection *c) {
1254         return c ? c->nodelay : false;
1255 }
1256
1257 void utcp_set_nodelay(struct utcp_connection *c, bool nodelay) {
1258         if(c)
1259                 c->nodelay = nodelay;
1260 }
1261
1262 bool utcp_get_keepalive(struct utcp_connection *c) {
1263         return c ? c->keepalive : false;
1264 }
1265
1266 void utcp_set_keepalive(struct utcp_connection *c, bool keepalive) {
1267         if(c)
1268                 c->keepalive = keepalive;
1269 }
1270
1271 size_t utcp_get_outq(struct utcp_connection *c) {
1272         return c ? seqdiff(c->snd.nxt, c->snd.una) : 0;
1273 }
1274
1275 void utcp_set_recv_cb(struct utcp_connection *c, utcp_recv_t recv) {
1276         if(c)
1277                 c->recv = recv;
1278 }
1279
1280 void utcp_set_poll_cb(struct utcp_connection *c, utcp_poll_t poll) {
1281         if(c)
1282                 c->poll = poll;
1283 }
1284
1285 void utcp_set_accept_cb(struct utcp *utcp, utcp_accept_t accept, utcp_pre_accept_t pre_accept) {
1286         if(utcp) {
1287                 utcp->accept = accept;
1288                 utcp->pre_accept = pre_accept;
1289         }
1290 }