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