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