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