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