]> git.meshlink.io Git - utcp/blob - utcp.c
Don't abort when UTCP_NO_PARTIAL is set.
[utcp] / utcp.c
1 /*
2     utcp.c -- Userspace TCP
3     Copyright (C) 2014-2017 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)\
49         do {\
50                 (r)->tv_sec = (a)->tv_sec - (b)->tv_sec;\
51                 (r)->tv_usec = (a)->tv_usec - (b)->tv_usec;\
52                 if((r)->tv_usec < 0)\
53                         (r)->tv_sec--, (r)->tv_usec += USEC_PER_SEC;\
54         } while (0)
55 #endif
56
57 static inline size_t max(size_t a, size_t b) {
58         return a > b ? a : b;
59 }
60
61 #ifdef UTCP_DEBUG
62 #include <stdarg.h>
63
64 static void debug(const char *format, ...) {
65         va_list ap;
66         va_start(ap, format);
67         vfprintf(stderr, format, ap);
68         va_end(ap);
69 }
70
71 static void print_packet(struct utcp *utcp, const char *dir, const void *pkt, size_t len) {
72         struct hdr hdr;
73
74         if(len < sizeof(hdr)) {
75                 debug("%p %s: short packet (%lu bytes)\n", utcp, dir, (unsigned long)len);
76                 return;
77         }
78
79         memcpy(&hdr, pkt, sizeof(hdr));
80         debug("%p %s: len=%lu, src=%u dst=%u seq=%u ack=%u wnd=%u aux=%x ctl=", utcp, dir, (unsigned long)len, hdr.src, hdr.dst, hdr.seq, hdr.ack, hdr.wnd, hdr.aux);
81
82         if(hdr.ctl & SYN) {
83                 debug("SYN");
84         }
85
86         if(hdr.ctl & RST) {
87                 debug("RST");
88         }
89
90         if(hdr.ctl & FIN) {
91                 debug("FIN");
92         }
93
94         if(hdr.ctl & ACK) {
95                 debug("ACK");
96         }
97
98         if(len > sizeof(hdr)) {
99                 uint32_t datalen = len - sizeof(hdr);
100                 const uint8_t *data = (uint8_t *)pkt + sizeof(hdr);
101                 char str[datalen * 2 + 1];
102                 char *p = str;
103
104                 for(uint32_t i = 0; i < datalen; i++) {
105                         *p++ = "0123456789ABCDEF"[data[i] >> 4];
106                         *p++ = "0123456789ABCDEF"[data[i] & 15];
107                 }
108
109                 *p = 0;
110
111                 debug(" data=%s", str);
112         }
113
114         debug("\n");
115 }
116 #else
117 #define debug(...) do {} while(0)
118 #define print_packet(...) do {} while(0)
119 #endif
120
121 static void set_state(struct utcp_connection *c, enum state state) {
122         c->state = state;
123
124         if(state == ESTABLISHED) {
125                 timerclear(&c->conn_timeout);
126         }
127
128         debug("%p new state: %s\n", c->utcp, strstate[state]);
129 }
130
131 static bool fin_wanted(struct utcp_connection *c, uint32_t seq) {
132         if(seq != c->snd.last) {
133                 return false;
134         }
135
136         switch(c->state) {
137         case FIN_WAIT_1:
138         case CLOSING:
139         case LAST_ACK:
140                 return true;
141
142         default:
143                 return false;
144         }
145 }
146
147 static bool is_reliable(struct utcp_connection *c) {
148         return c->flags & UTCP_RELIABLE;
149 }
150
151 static int32_t seqdiff(uint32_t a, uint32_t b) {
152         return a - b;
153 }
154
155 // Buffer functions
156 // TODO: convert to ringbuffers to avoid memmove() operations.
157
158 // Store data into the buffer
159 static ssize_t buffer_put_at(struct buffer *buf, size_t offset, const void *data, size_t len) {
160         debug("buffer_put_at %lu %lu %lu\n", (unsigned long)buf->used, (unsigned long)offset, (unsigned long)len);
161
162         size_t required = offset + len;
163
164         if(required > buf->maxsize) {
165                 if(offset >= buf->maxsize) {
166                         return 0;
167                 }
168
169                 len = buf->maxsize - offset;
170                 required = buf->maxsize;
171         }
172
173         if(required > buf->size) {
174                 size_t newsize = buf->size;
175
176                 if(!newsize) {
177                         newsize = required;
178                 } else {
179                         do {
180                                 newsize *= 2;
181                         } while(newsize < required);
182                 }
183
184                 if(newsize > buf->maxsize) {
185                         newsize = buf->maxsize;
186                 }
187
188                 char *newdata = realloc(buf->data, newsize);
189
190                 if(!newdata) {
191                         return -1;
192                 }
193
194                 buf->data = newdata;
195                 buf->size = newsize;
196         }
197
198         memcpy(buf->data + offset, data, len);
199
200         if(required > buf->used) {
201                 buf->used = required;
202         }
203
204         return len;
205 }
206
207 static ssize_t buffer_put(struct buffer *buf, const void *data, size_t len) {
208         return buffer_put_at(buf, buf->used, data, len);
209 }
210
211 // Get data from the buffer. data can be NULL.
212 static ssize_t buffer_get(struct buffer *buf, void *data, size_t len) {
213         if(len > buf->used) {
214                 len = buf->used;
215         }
216
217         if(data) {
218                 memcpy(data, buf->data, len);
219         }
220
221         if(len < buf->used) {
222                 memmove(buf->data, buf->data + len, buf->used - len);
223         }
224
225         buf->used -= len;
226         return len;
227 }
228
229 // Copy data from the buffer without removing it.
230 static ssize_t buffer_copy(struct buffer *buf, void *data, size_t offset, size_t len) {
231         if(offset >= buf->used) {
232                 return 0;
233         }
234
235         if(offset + len > buf->used) {
236                 len = buf->used - offset;
237         }
238
239         memcpy(data, buf->data + offset, len);
240         return len;
241 }
242
243 static bool buffer_init(struct buffer *buf, uint32_t len, uint32_t maxlen) {
244         memset(buf, 0, sizeof(*buf));
245
246         if(len) {
247                 buf->data = malloc(len);
248
249                 if(!buf->data) {
250                         return false;
251                 }
252         }
253
254         buf->size = len;
255         buf->maxsize = maxlen;
256         return true;
257 }
258
259 static void buffer_exit(struct buffer *buf) {
260         free(buf->data);
261         memset(buf, 0, sizeof(*buf));
262 }
263
264 static uint32_t buffer_free(const struct buffer *buf) {
265         return buf->maxsize - buf->used;
266 }
267
268 // Connections are stored in a sorted list.
269 // This gives O(log(N)) lookup time, O(N log(N)) insertion time and O(N) deletion time.
270
271 static int compare(const void *va, const void *vb) {
272         assert(va && vb);
273
274         const struct utcp_connection *a = *(struct utcp_connection **)va;
275         const struct utcp_connection *b = *(struct utcp_connection **)vb;
276
277         assert(a && b);
278         assert(a->src && b->src);
279
280         int c = (int)a->src - (int)b->src;
281
282         if(c) {
283                 return c;
284         }
285
286         c = (int)a->dst - (int)b->dst;
287         return c;
288 }
289
290 static struct utcp_connection *find_connection(const struct utcp *utcp, uint16_t src, uint16_t dst) {
291         if(!utcp->nconnections) {
292                 return NULL;
293         }
294
295         struct utcp_connection key = {
296                 .src = src,
297                 .dst = dst,
298         }, *keyp = &key;
299         struct utcp_connection **match = bsearch(&keyp, utcp->connections, utcp->nconnections, sizeof(*utcp->connections), compare);
300         return match ? *match : NULL;
301 }
302
303 static void free_connection(struct utcp_connection *c) {
304         struct utcp *utcp = c->utcp;
305         struct utcp_connection **cp = bsearch(&c, utcp->connections, utcp->nconnections, sizeof(*utcp->connections), compare);
306
307         assert(cp);
308
309         int i = cp - utcp->connections;
310         memmove(cp, cp + 1, (utcp->nconnections - i - 1) * sizeof(*cp));
311         utcp->nconnections--;
312
313         buffer_exit(&c->rcvbuf);
314         buffer_exit(&c->sndbuf);
315         free(c);
316 }
317
318 static struct utcp_connection *allocate_connection(struct utcp *utcp, uint16_t src, uint16_t dst) {
319         // Check whether this combination of src and dst is free
320
321         if(src) {
322                 if(find_connection(utcp, src, dst)) {
323                         errno = EADDRINUSE;
324                         return NULL;
325                 }
326         } else { // If src == 0, generate a random port number with the high bit set
327                 if(utcp->nconnections >= 32767) {
328                         errno = ENOMEM;
329                         return NULL;
330                 }
331
332                 src = rand() | 0x8000;
333
334                 while(find_connection(utcp, src, dst)) {
335                         src++;
336                 }
337         }
338
339         // Allocate memory for the new connection
340
341         if(utcp->nconnections >= utcp->nallocated) {
342                 if(!utcp->nallocated) {
343                         utcp->nallocated = 4;
344                 } else {
345                         utcp->nallocated *= 2;
346                 }
347
348                 struct utcp_connection **new_array = realloc(utcp->connections, utcp->nallocated * sizeof(*utcp->connections));
349
350                 if(!new_array) {
351                         return NULL;
352                 }
353
354                 utcp->connections = new_array;
355         }
356
357         struct utcp_connection *c = calloc(1, sizeof(*c));
358
359         if(!c) {
360                 return NULL;
361         }
362
363         if(!buffer_init(&c->sndbuf, DEFAULT_SNDBUFSIZE, DEFAULT_MAXSNDBUFSIZE)) {
364                 free(c);
365                 return NULL;
366         }
367
368         if(!buffer_init(&c->rcvbuf, DEFAULT_RCVBUFSIZE, DEFAULT_MAXRCVBUFSIZE)) {
369                 buffer_exit(&c->sndbuf);
370                 free(c);
371                 return NULL;
372         }
373
374         // Fill in the details
375
376         c->src = src;
377         c->dst = dst;
378 #ifdef UTCP_DEBUG
379         c->snd.iss = 0;
380 #else
381         c->snd.iss = rand();
382 #endif
383         c->snd.una = c->snd.iss;
384         c->snd.nxt = c->snd.iss + 1;
385         c->rcv.wnd = utcp->mtu;
386         c->snd.last = c->snd.nxt;
387         c->snd.cwnd = utcp->mtu;
388         c->utcp = utcp;
389
390         // Add it to the sorted list of connections
391
392         utcp->connections[utcp->nconnections++] = c;
393         qsort(utcp->connections, utcp->nconnections, sizeof(*utcp->connections), compare);
394
395         return c;
396 }
397
398 static inline uint32_t absdiff(uint32_t a, uint32_t b) {
399         if(a > b) {
400                 return a - b;
401         } else {
402                 return b - a;
403         }
404 }
405
406 // Update RTT variables. See RFC 6298.
407 static void update_rtt(struct utcp_connection *c, uint32_t rtt) {
408         if(!rtt) {
409                 debug("invalid rtt\n");
410                 return;
411         }
412
413         struct utcp *utcp = c->utcp;
414
415         if(!utcp->srtt) {
416                 utcp->srtt = rtt;
417                 utcp->rttvar = rtt / 2;
418                 utcp->rto = rtt + max(2 * rtt, CLOCK_GRANULARITY);
419         } else {
420                 utcp->rttvar = (utcp->rttvar * 3 + absdiff(utcp->srtt, rtt)) / 4;
421                 utcp->srtt = (utcp->srtt * 7 + rtt) / 8;
422                 utcp->rto = utcp->srtt + max(utcp->rttvar, CLOCK_GRANULARITY);
423         }
424
425         if(utcp->rto > MAX_RTO) {
426                 utcp->rto = MAX_RTO;
427         }
428
429         debug("rtt %u srtt %u rttvar %u rto %u\n", rtt, utcp->srtt, utcp->rttvar, utcp->rto);
430 }
431
432 static void start_retransmit_timer(struct utcp_connection *c) {
433         gettimeofday(&c->rtrx_timeout, NULL);
434         c->rtrx_timeout.tv_usec += c->utcp->rto;
435
436         while(c->rtrx_timeout.tv_usec >= 1000000) {
437                 c->rtrx_timeout.tv_usec -= 1000000;
438                 c->rtrx_timeout.tv_sec++;
439         }
440
441         debug("timeout set to %lu.%06lu (%u)\n", c->rtrx_timeout.tv_sec, c->rtrx_timeout.tv_usec, c->utcp->rto);
442 }
443
444 static void stop_retransmit_timer(struct utcp_connection *c) {
445         timerclear(&c->rtrx_timeout);
446         debug("timeout cleared\n");
447 }
448
449 struct utcp_connection *utcp_connect_ex(struct utcp *utcp, uint16_t dst, utcp_recv_t recv, void *priv, uint32_t flags) {
450         struct utcp_connection *c = allocate_connection(utcp, 0, dst);
451
452         if(!c) {
453                 return NULL;
454         }
455
456         assert((flags & ~0x1f) == 0);
457
458         c->flags = flags;
459         c->recv = recv;
460         c->priv = priv;
461
462         struct {
463                 struct hdr hdr;
464                 uint8_t init[4];
465         } pkt;
466
467         pkt.hdr.src = c->src;
468         pkt.hdr.dst = c->dst;
469         pkt.hdr.seq = c->snd.iss;
470         pkt.hdr.ack = 0;
471         pkt.hdr.wnd = c->rcv.wnd;
472         pkt.hdr.ctl = SYN;
473         pkt.hdr.aux = 0x0101;
474         pkt.init[0] = 1;
475         pkt.init[1] = 0;
476         pkt.init[2] = 0;
477         pkt.init[3] = flags & 0x7;
478
479         set_state(c, SYN_SENT);
480
481         print_packet(utcp, "send", &pkt, sizeof(pkt));
482         utcp->send(utcp, &pkt, sizeof(pkt));
483
484         gettimeofday(&c->conn_timeout, NULL);
485         c->conn_timeout.tv_sec += utcp->timeout;
486
487         start_retransmit_timer(c);
488
489         return c;
490 }
491
492 struct utcp_connection *utcp_connect(struct utcp *utcp, uint16_t dst, utcp_recv_t recv, void *priv) {
493         return utcp_connect_ex(utcp, dst, recv, priv, UTCP_TCP);
494 }
495
496 void utcp_accept(struct utcp_connection *c, utcp_recv_t recv, void *priv) {
497         if(c->reapable || c->state != SYN_RECEIVED) {
498                 debug("Error: accept() called on invalid connection %p in state %s\n", c, strstate[c->state]);
499                 return;
500         }
501
502         debug("%p accepted, %p %p\n", c, recv, priv);
503         c->recv = recv;
504         c->priv = priv;
505         set_state(c, ESTABLISHED);
506 }
507
508 static void ack(struct utcp_connection *c, bool sendatleastone) {
509         int32_t left = seqdiff(c->snd.last, c->snd.nxt);
510         int32_t cwndleft = c->snd.cwnd - seqdiff(c->snd.nxt, c->snd.una);
511         debug("cwndleft = %d\n", cwndleft);
512
513         assert(left >= 0);
514
515         if(cwndleft <= 0) {
516                 cwndleft = 0;
517         }
518
519         if(cwndleft < left) {
520                 left = cwndleft;
521         }
522
523         if(!left && !sendatleastone) {
524                 return;
525         }
526
527         struct {
528                 struct hdr hdr;
529                 uint8_t data[];
530         } *pkt;
531
532         pkt = malloc(sizeof(pkt->hdr) + c->utcp->mtu);
533
534         if(!pkt) {
535                 return;
536         }
537
538         pkt->hdr.src = c->src;
539         pkt->hdr.dst = c->dst;
540         pkt->hdr.ack = c->rcv.nxt;
541         pkt->hdr.wnd = c->snd.wnd;
542         pkt->hdr.ctl = ACK;
543         pkt->hdr.aux = 0;
544
545         do {
546                 uint32_t seglen = left > c->utcp->mtu ? c->utcp->mtu : left;
547                 pkt->hdr.seq = c->snd.nxt;
548
549                 buffer_copy(&c->sndbuf, pkt->data, seqdiff(c->snd.nxt, c->snd.una), seglen);
550
551                 c->snd.nxt += seglen;
552                 left -= seglen;
553
554                 if(seglen && fin_wanted(c, c->snd.nxt)) {
555                         seglen--;
556                         pkt->hdr.ctl |= FIN;
557                 }
558
559                 if(!c->rtt_start.tv_sec) {
560                         // Start RTT measurement
561                         gettimeofday(&c->rtt_start, NULL);
562                         c->rtt_seq = pkt->hdr.seq + seglen;
563                         debug("Starting RTT measurement, expecting ack %u\n", c->rtt_seq);
564                 }
565
566                 print_packet(c->utcp, "send", pkt, sizeof(pkt->hdr) + seglen);
567                 c->utcp->send(c->utcp, pkt, sizeof(pkt->hdr) + seglen);
568         } while(left);
569
570         free(pkt);
571 }
572
573 ssize_t utcp_send(struct utcp_connection *c, const void *data, size_t len) {
574         if(c->reapable) {
575                 debug("Error: send() called on closed connection %p\n", c);
576                 errno = EBADF;
577                 return -1;
578         }
579
580         switch(c->state) {
581         case CLOSED:
582         case LISTEN:
583                 debug("Error: send() called on unconnected connection %p\n", c);
584                 errno = ENOTCONN;
585                 return -1;
586
587         case SYN_SENT:
588         case SYN_RECEIVED:
589         case ESTABLISHED:
590         case CLOSE_WAIT:
591                 break;
592
593         case FIN_WAIT_1:
594         case FIN_WAIT_2:
595         case CLOSING:
596         case LAST_ACK:
597         case TIME_WAIT:
598                 debug("Error: send() called on closing connection %p\n", c);
599                 errno = EPIPE;
600                 return -1;
601         }
602
603         // Exit early if we have nothing to send.
604
605         if(!len) {
606                 return 0;
607         }
608
609         if(!data) {
610                 errno = EFAULT;
611                 return -1;
612         }
613
614         // Check if we need to be able to buffer all data
615
616         if(c->flags & UTCP_NO_PARTIAL) {
617                 if(len > buffer_free(&c->sndbuf)) {
618                         if(len > c->sndbuf.maxsize) {
619                                 errno = EMSGSIZE;
620                                 return -1;
621                         } else {
622                                 errno = EWOULDBLOCK;
623                                 return 0;
624                         }
625                 }
626         }
627
628         // Add data to send buffer.
629
630         len = buffer_put(&c->sndbuf, data, len);
631
632         if(len <= 0) {
633                 errno = EWOULDBLOCK;
634                 return 0;
635         }
636
637         c->snd.last += len;
638
639         // Don't send anything yet if the connection has not fully established yet
640
641         if(c->state == SYN_SENT || c->state == SYN_RECEIVED) {
642                 return len;
643         }
644
645         ack(c, false);
646
647         if(!is_reliable(c)) {
648                 c->snd.una = c->snd.nxt = c->snd.last;
649                 buffer_get(&c->sndbuf, NULL, c->sndbuf.used);
650         }
651
652         if(is_reliable(c) && !timerisset(&c->rtrx_timeout)) {
653                 start_retransmit_timer(c);
654         }
655
656         if(is_reliable(c) && !timerisset(&c->conn_timeout)) {
657                 gettimeofday(&c->conn_timeout, NULL);
658                 c->conn_timeout.tv_sec += c->utcp->timeout;
659         }
660
661         return len;
662 }
663
664 static void swap_ports(struct hdr *hdr) {
665         uint16_t tmp = hdr->src;
666         hdr->src = hdr->dst;
667         hdr->dst = tmp;
668 }
669
670 static void retransmit(struct utcp_connection *c) {
671         if(c->state == CLOSED || c->snd.last == c->snd.una) {
672                 debug("Retransmit() called but nothing to retransmit!\n");
673                 stop_retransmit_timer(c);
674                 return;
675         }
676
677         struct utcp *utcp = c->utcp;
678
679         struct {
680                 struct hdr hdr;
681                 uint8_t data[];
682         } *pkt;
683
684         pkt = malloc(sizeof(pkt->hdr) + c->utcp->mtu);
685
686         if(!pkt) {
687                 return;
688         }
689
690         pkt->hdr.src = c->src;
691         pkt->hdr.dst = c->dst;
692         pkt->hdr.wnd = c->rcv.wnd;
693         pkt->hdr.aux = 0;
694
695         switch(c->state) {
696         case SYN_SENT:
697                 // Send our SYN again
698                 pkt->hdr.seq = c->snd.iss;
699                 pkt->hdr.ack = 0;
700                 pkt->hdr.ctl = SYN;
701                 pkt->hdr.aux = 0x0101;
702                 pkt->data[0] = 1;
703                 pkt->data[1] = 0;
704                 pkt->data[2] = 0;
705                 pkt->data[3] = c->flags & 0x7;
706                 print_packet(c->utcp, "rtrx", pkt, sizeof(pkt->hdr) + 4);
707                 utcp->send(utcp, pkt, sizeof(pkt->hdr) + 4);
708                 break;
709
710         case SYN_RECEIVED:
711                 // Send SYNACK again
712                 pkt->hdr.seq = c->snd.nxt;
713                 pkt->hdr.ack = c->rcv.nxt;
714                 pkt->hdr.ctl = SYN | ACK;
715                 print_packet(c->utcp, "rtrx", pkt, sizeof(pkt->hdr));
716                 utcp->send(utcp, pkt, sizeof(pkt->hdr));
717                 break;
718
719         case ESTABLISHED:
720         case FIN_WAIT_1:
721         case CLOSE_WAIT:
722         case CLOSING:
723         case LAST_ACK:
724                 // Send unacked data again.
725                 pkt->hdr.seq = c->snd.una;
726                 pkt->hdr.ack = c->rcv.nxt;
727                 pkt->hdr.ctl = ACK;
728                 uint32_t len = seqdiff(c->snd.last, c->snd.una);
729
730                 if(len > utcp->mtu) {
731                         len = utcp->mtu;
732                 }
733
734                 if(fin_wanted(c, c->snd.una + len)) {
735                         len--;
736                         pkt->hdr.ctl |= FIN;
737                 }
738
739                 c->snd.nxt = c->snd.una + len;
740                 c->snd.cwnd = utcp->mtu; // reduce cwnd on retransmit
741                 buffer_copy(&c->sndbuf, pkt->data, 0, len);
742                 print_packet(c->utcp, "rtrx", pkt, sizeof(pkt->hdr) + len);
743                 utcp->send(utcp, pkt, sizeof(pkt->hdr) + len);
744                 break;
745
746         case CLOSED:
747         case LISTEN:
748         case TIME_WAIT:
749         case FIN_WAIT_2:
750                 // We shouldn't need to retransmit anything in this state.
751 #ifdef UTCP_DEBUG
752                 abort();
753 #endif
754                 stop_retransmit_timer(c);
755                 goto cleanup;
756         }
757
758         start_retransmit_timer(c);
759         utcp->rto *= 2;
760
761         if(utcp->rto > MAX_RTO) {
762                 utcp->rto = MAX_RTO;
763         }
764
765         c->rtt_start.tv_sec = 0; // invalidate RTT timer
766
767 cleanup:
768         free(pkt);
769 }
770
771 /* Update receive buffer and SACK entries after consuming data.
772  *
773  * Situation:
774  *
775  * |.....0000..1111111111.....22222......3333|
776  * |---------------^
777  *
778  * 0..3 represent the SACK entries. The ^ indicates up to which point we want
779  * to remove data from the receive buffer. The idea is to substract "len"
780  * from the offset of all the SACK entries, and then remove/cut down entries
781  * that are shifted to before the start of the receive buffer.
782  *
783  * There are three cases:
784  * - the SACK entry is after ^, in that case just change the offset.
785  * - the SACK entry starts before and ends after ^, so we have to
786  *   change both its offset and size.
787  * - the SACK entry is completely before ^, in that case delete it.
788  */
789 static void sack_consume(struct utcp_connection *c, size_t len) {
790         debug("sack_consume %lu\n", (unsigned long)len);
791
792         if(len > c->rcvbuf.used) {
793                 debug("All SACK entries consumed");
794                 c->sacks[0].len = 0;
795                 return;
796         }
797
798         buffer_get(&c->rcvbuf, NULL, len);
799
800         for(int i = 0; i < NSACKS && c->sacks[i].len;) {
801                 if(len < c->sacks[i].offset) {
802                         c->sacks[i].offset -= len;
803                         i++;
804                 } else if(len < c->sacks[i].offset + c->sacks[i].len) {
805                         c->sacks[i].len -= len - c->sacks[i].offset;
806                         c->sacks[i].offset = 0;
807                         i++;
808                 } else {
809                         if(i < NSACKS - 1) {
810                                 memmove(&c->sacks[i], &c->sacks[i + 1], (NSACKS - 1 - i) * sizeof(c->sacks)[i]);
811                                 c->sacks[NSACKS - 1].len = 0;
812                         } else {
813                                 c->sacks[i].len = 0;
814                                 break;
815                         }
816                 }
817         }
818
819         for(int i = 0; i < NSACKS && c->sacks[i].len; i++) {
820                 debug("SACK[%d] offset %u len %u\n", i, c->sacks[i].offset, c->sacks[i].len);
821         }
822 }
823
824 static void handle_out_of_order(struct utcp_connection *c, uint32_t offset, const void *data, size_t len) {
825         debug("out of order packet, offset %u\n", offset);
826         // Packet loss or reordering occured. Store the data in the buffer.
827         ssize_t rxd = buffer_put_at(&c->rcvbuf, offset, data, len);
828
829         if(rxd < 0 || (size_t)rxd < len) {
830                 abort();
831         }
832
833         // Make note of where we put it.
834         for(int i = 0; i < NSACKS; i++) {
835                 if(!c->sacks[i].len) { // nothing to merge, add new entry
836                         debug("New SACK entry %d\n", i);
837                         c->sacks[i].offset = offset;
838                         c->sacks[i].len = rxd;
839                         break;
840                 } else if(offset < c->sacks[i].offset) {
841                         if(offset + rxd < c->sacks[i].offset) { // insert before
842                                 if(!c->sacks[NSACKS - 1].len) { // only if room left
843                                         debug("Insert SACK entry at %d\n", i);
844                                         memmove(&c->sacks[i + 1], &c->sacks[i], (NSACKS - i - 1) * sizeof(c->sacks)[i]);
845                                         c->sacks[i].offset = offset;
846                                         c->sacks[i].len = rxd;
847                                 } else {
848                                         debug("SACK entries full, dropping packet\n");
849                                 }
850
851                                 break;
852                         } else { // merge
853                                 debug("Merge with start of SACK entry at %d\n", i);
854                                 c->sacks[i].offset = offset;
855                                 break;
856                         }
857                 } else if(offset <= c->sacks[i].offset + c->sacks[i].len) {
858                         if(offset + rxd > c->sacks[i].offset + c->sacks[i].len) { // merge
859                                 debug("Merge with end of SACK entry at %d\n", i);
860                                 c->sacks[i].len = offset + rxd - c->sacks[i].offset;
861                                 // TODO: handle potential merge with next entry
862                         }
863
864                         break;
865                 }
866         }
867
868         for(int i = 0; i < NSACKS && c->sacks[i].len; i++) {
869                 debug("SACK[%d] offset %u len %u\n", i, c->sacks[i].offset, c->sacks[i].len);
870         }
871 }
872
873 static void handle_in_order(struct utcp_connection *c, const void *data, size_t len) {
874         // Check if we can process out-of-order data now.
875         if(c->sacks[0].len && len >= c->sacks[0].offset) { // TODO: handle overlap with second SACK
876                 debug("incoming packet len %lu connected with SACK at %u\n", (unsigned long)len, c->sacks[0].offset);
877                 buffer_put_at(&c->rcvbuf, 0, data, len); // TODO: handle return value
878                 len = max(len, c->sacks[0].offset + c->sacks[0].len);
879                 data = c->rcvbuf.data;
880         }
881
882         if(c->recv) {
883                 ssize_t rxd = c->recv(c, data, len);
884
885                 if(rxd < 0 || (size_t)rxd != len) {
886                         // TODO: handle the application not accepting all data.
887                         abort();
888                 }
889         }
890
891         if(c->rcvbuf.used) {
892                 sack_consume(c, len);
893         }
894
895         c->rcv.nxt += len;
896 }
897
898
899 static void handle_incoming_data(struct utcp_connection *c, uint32_t seq, const void *data, size_t len) {
900         if(!is_reliable(c)) {
901                 c->recv(c, data, len);
902                 c->rcv.nxt = seq + len;
903                 return;
904         }
905
906         uint32_t offset = seqdiff(seq, c->rcv.nxt);
907
908         if(offset + len > c->rcvbuf.maxsize) {
909                 abort();
910         }
911
912         if(offset) {
913                 handle_out_of_order(c, offset, data, len);
914         } else {
915                 handle_in_order(c, data, len);
916         }
917 }
918
919
920 ssize_t utcp_recv(struct utcp *utcp, const void *data, size_t len) {
921         const uint8_t *ptr = data;
922
923         if(!utcp) {
924                 errno = EFAULT;
925                 return -1;
926         }
927
928         if(!len) {
929                 return 0;
930         }
931
932         if(!data) {
933                 errno = EFAULT;
934                 return -1;
935         }
936
937         print_packet(utcp, "recv", data, len);
938
939         // Drop packets smaller than the header
940
941         struct hdr hdr;
942
943         if(len < sizeof(hdr)) {
944                 errno = EBADMSG;
945                 return -1;
946         }
947
948         // Make a copy from the potentially unaligned data to a struct hdr
949
950         memcpy(&hdr, ptr, sizeof(hdr));
951         ptr += sizeof(hdr);
952         len -= sizeof(hdr);
953
954         // Drop packets with an unknown CTL flag
955
956         if(hdr.ctl & ~(SYN | ACK | RST | FIN)) {
957                 errno = EBADMSG;
958                 return -1;
959         }
960
961         // Check for auxiliary headers
962
963         const uint8_t *init = NULL;
964
965         uint16_t aux = hdr.aux;
966
967         while(aux) {
968                 size_t auxlen = 4 * (aux >> 8) & 0xf;
969                 uint8_t auxtype = aux & 0xff;
970
971                 if(len < auxlen) {
972                         errno = EBADMSG;
973                         return -1;
974                 }
975
976                 switch(auxtype) {
977                 case AUX_INIT:
978                         if(!(hdr.ctl & SYN) || auxlen != 4) {
979                                 errno = EBADMSG;
980                                 return -1;
981                         }
982
983                         init = ptr;
984                         break;
985
986                 default:
987                         errno = EBADMSG;
988                         return -1;
989                 }
990
991                 len -= auxlen;
992                 ptr += auxlen;
993
994                 if(!(aux & 0x800)) {
995                         break;
996                 }
997
998                 if(len < 2) {
999                         errno = EBADMSG;
1000                         return -1;
1001                 }
1002
1003                 memcpy(&aux, ptr, 2);
1004                 len -= 2;
1005                 ptr += 2;
1006         }
1007
1008         // Try to match the packet to an existing connection
1009
1010         struct utcp_connection *c = find_connection(utcp, hdr.dst, hdr.src);
1011
1012         // Is it for a new connection?
1013
1014         if(!c) {
1015                 // Ignore RST packets
1016
1017                 if(hdr.ctl & RST) {
1018                         return 0;
1019                 }
1020
1021                 // Is it a SYN packet and are we LISTENing?
1022
1023                 if(hdr.ctl & SYN && !(hdr.ctl & ACK) && utcp->accept) {
1024                         // If we don't want to accept it, send a RST back
1025                         if((utcp->pre_accept && !utcp->pre_accept(utcp, hdr.dst))) {
1026                                 len = 1;
1027                                 goto reset;
1028                         }
1029
1030                         // Try to allocate memory, otherwise send a RST back
1031                         c = allocate_connection(utcp, hdr.dst, hdr.src);
1032
1033                         if(!c) {
1034                                 len = 1;
1035                                 goto reset;
1036                         }
1037
1038                         // Parse auxilliary information
1039                         if(init) {
1040                                 if(init[0] < 1) {
1041                                         len = 1;
1042                                         goto reset;
1043                                 }
1044
1045                                 c->flags = init[3] & 0x7;
1046                         } else {
1047                                 c->flags = UTCP_TCP;
1048                         }
1049
1050                         // Return SYN+ACK, go to SYN_RECEIVED state
1051                         c->snd.wnd = hdr.wnd;
1052                         c->rcv.irs = hdr.seq;
1053                         c->rcv.nxt = c->rcv.irs + 1;
1054                         set_state(c, SYN_RECEIVED);
1055
1056                         struct {
1057                                 struct hdr hdr;
1058                                 uint8_t data[4];
1059                         } pkt;
1060
1061                         pkt.hdr.src = c->src;
1062                         pkt.hdr.dst = c->dst;
1063                         pkt.hdr.ack = c->rcv.irs + 1;
1064                         pkt.hdr.seq = c->snd.iss;
1065                         pkt.hdr.wnd = c->rcv.wnd;
1066                         pkt.hdr.ctl = SYN | ACK;
1067
1068                         if(init) {
1069                                 pkt.hdr.aux = 0x0101;
1070                                 pkt.data[0] = 1;
1071                                 pkt.data[1] = 0;
1072                                 pkt.data[2] = 0;
1073                                 pkt.data[3] = c->flags & 0x7;
1074                                 print_packet(c->utcp, "send", &pkt, sizeof(hdr) + 4);
1075                                 utcp->send(utcp, &pkt, sizeof(hdr) + 4);
1076                         } else {
1077                                 pkt.hdr.aux = 0;
1078                                 print_packet(c->utcp, "send", &pkt, sizeof(hdr));
1079                                 utcp->send(utcp, &pkt, sizeof(hdr));
1080                         }
1081                 } else {
1082                         // No, we don't want your packets, send a RST back
1083                         len = 1;
1084                         goto reset;
1085                 }
1086
1087                 return 0;
1088         }
1089
1090         debug("%p state %s\n", c->utcp, strstate[c->state]);
1091
1092         // In case this is for a CLOSED connection, ignore the packet.
1093         // TODO: make it so incoming packets can never match a CLOSED connection.
1094
1095         if(c->state == CLOSED) {
1096                 debug("Got packet for closed connection\n");
1097                 return 0;
1098         }
1099
1100         // It is for an existing connection.
1101
1102         uint32_t prevrcvnxt = c->rcv.nxt;
1103
1104         // 1. Drop invalid packets.
1105
1106         // 1a. Drop packets that should not happen in our current state.
1107
1108         switch(c->state) {
1109         case SYN_SENT:
1110         case SYN_RECEIVED:
1111         case ESTABLISHED:
1112         case FIN_WAIT_1:
1113         case FIN_WAIT_2:
1114         case CLOSE_WAIT:
1115         case CLOSING:
1116         case LAST_ACK:
1117         case TIME_WAIT:
1118                 break;
1119
1120         default:
1121 #ifdef UTCP_DEBUG
1122                 abort();
1123 #endif
1124                 break;
1125         }
1126
1127         // 1b. Drop packets with a sequence number not in our receive window.
1128
1129         bool acceptable;
1130
1131         if(c->state == SYN_SENT) {
1132                 acceptable = true;
1133         } else if(len == 0) {
1134                 acceptable = seqdiff(hdr.seq, c->rcv.nxt) >= 0;
1135         } else {
1136                 int32_t rcv_offset = seqdiff(hdr.seq, c->rcv.nxt);
1137
1138                 // cut already accepted front overlapping
1139                 if(rcv_offset < 0) {
1140                         acceptable = len > (size_t) - rcv_offset;
1141
1142                         if(acceptable) {
1143                                 ptr -= rcv_offset;
1144                                 len += rcv_offset;
1145                                 hdr.seq -= rcv_offset;
1146                         }
1147                 } else {
1148                         acceptable = seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt) + len <= c->rcvbuf.maxsize;
1149                 }
1150         }
1151
1152         if(!acceptable) {
1153                 debug("Packet not acceptable, %u <= %u + %lu < %u\n", c->rcv.nxt, hdr.seq, (unsigned long)len, c->rcv.nxt + c->rcvbuf.maxsize);
1154
1155                 // Ignore unacceptable RST packets.
1156                 if(hdr.ctl & RST) {
1157                         return 0;
1158                 }
1159
1160                 // Otherwise, continue processing.
1161                 len = 0;
1162         }
1163
1164         c->snd.wnd = hdr.wnd; // TODO: move below
1165
1166         // 1c. Drop packets with an invalid ACK.
1167         // ackno should not roll back, and it should also not be bigger than what we ever could have sent
1168         // (= snd.una + c->sndbuf.used).
1169
1170         if(hdr.ctl & ACK && (seqdiff(hdr.ack, c->snd.last) > 0 || seqdiff(hdr.ack, c->snd.una) < 0)) {
1171                 debug("Packet ack seqno out of range, %u <= %u < %u\n", c->snd.una, hdr.ack, c->snd.una + c->sndbuf.used);
1172
1173                 // Ignore unacceptable RST packets.
1174                 if(hdr.ctl & RST) {
1175                         return 0;
1176                 }
1177
1178                 goto reset;
1179         }
1180
1181         // 2. Handle RST packets
1182
1183         if(hdr.ctl & RST) {
1184                 switch(c->state) {
1185                 case SYN_SENT:
1186                         if(!(hdr.ctl & ACK)) {
1187                                 return 0;
1188                         }
1189
1190                         // The peer has refused our connection.
1191                         set_state(c, CLOSED);
1192                         errno = ECONNREFUSED;
1193
1194                         if(c->recv) {
1195                                 c->recv(c, NULL, 0);
1196                         }
1197
1198                         return 0;
1199
1200                 case SYN_RECEIVED:
1201                         if(hdr.ctl & ACK) {
1202                                 return 0;
1203                         }
1204
1205                         // We haven't told the application about this connection yet. Silently delete.
1206                         free_connection(c);
1207                         return 0;
1208
1209                 case ESTABLISHED:
1210                 case FIN_WAIT_1:
1211                 case FIN_WAIT_2:
1212                 case CLOSE_WAIT:
1213                         if(hdr.ctl & ACK) {
1214                                 return 0;
1215                         }
1216
1217                         // The peer has aborted our connection.
1218                         set_state(c, CLOSED);
1219                         errno = ECONNRESET;
1220
1221                         if(c->recv) {
1222                                 c->recv(c, NULL, 0);
1223                         }
1224
1225                         return 0;
1226
1227                 case CLOSING:
1228                 case LAST_ACK:
1229                 case TIME_WAIT:
1230                         if(hdr.ctl & ACK) {
1231                                 return 0;
1232                         }
1233
1234                         // As far as the application is concerned, the connection has already been closed.
1235                         // If it has called utcp_close() already, we can immediately free this connection.
1236                         if(c->reapable) {
1237                                 free_connection(c);
1238                                 return 0;
1239                         }
1240
1241                         // Otherwise, immediately move to the CLOSED state.
1242                         set_state(c, CLOSED);
1243                         return 0;
1244
1245                 default:
1246 #ifdef UTCP_DEBUG
1247                         abort();
1248 #endif
1249                         break;
1250                 }
1251         }
1252
1253         uint32_t advanced;
1254
1255         if(!(hdr.ctl & ACK)) {
1256                 advanced = 0;
1257                 goto skip_ack;
1258         }
1259
1260         // 3. Advance snd.una
1261
1262         advanced = seqdiff(hdr.ack, c->snd.una);
1263         prevrcvnxt = c->rcv.nxt;
1264
1265         if(advanced) {
1266                 // RTT measurement
1267                 if(c->rtt_start.tv_sec) {
1268                         if(c->rtt_seq == hdr.ack) {
1269                                 struct timeval now, diff;
1270                                 gettimeofday(&now, NULL);
1271                                 timersub(&now, &c->rtt_start, &diff);
1272                                 update_rtt(c, diff.tv_sec * 1000000 + diff.tv_usec);
1273                                 c->rtt_start.tv_sec = 0;
1274                         } else if(c->rtt_seq < hdr.ack) {
1275                                 debug("Cancelling RTT measurement: %u < %u\n", c->rtt_seq, hdr.ack);
1276                                 c->rtt_start.tv_sec = 0;
1277                         }
1278                 }
1279
1280                 int32_t data_acked = advanced;
1281
1282                 switch(c->state) {
1283                 case SYN_SENT:
1284                 case SYN_RECEIVED:
1285                         data_acked--;
1286                         break;
1287
1288                 // TODO: handle FIN as well.
1289                 default:
1290                         break;
1291                 }
1292
1293                 assert(data_acked >= 0);
1294
1295                 int32_t bufused = seqdiff(c->snd.last, c->snd.una);
1296                 assert(data_acked <= bufused);
1297
1298                 if(data_acked) {
1299                         buffer_get(&c->sndbuf, NULL, data_acked);
1300                 }
1301
1302                 // Also advance snd.nxt if possible
1303                 if(seqdiff(c->snd.nxt, hdr.ack) < 0) {
1304                         c->snd.nxt = hdr.ack;
1305                 }
1306
1307                 c->snd.una = hdr.ack;
1308
1309                 c->dupack = 0;
1310                 c->snd.cwnd += utcp->mtu;
1311
1312                 if(c->snd.cwnd > c->sndbuf.maxsize) {
1313                         c->snd.cwnd = c->sndbuf.maxsize;
1314                 }
1315
1316                 // Check if we have sent a FIN that is now ACKed.
1317                 switch(c->state) {
1318                 case FIN_WAIT_1:
1319                         if(c->snd.una == c->snd.last) {
1320                                 set_state(c, FIN_WAIT_2);
1321                         }
1322
1323                         break;
1324
1325                 case CLOSING:
1326                         if(c->snd.una == c->snd.last) {
1327                                 gettimeofday(&c->conn_timeout, NULL);
1328                                 c->conn_timeout.tv_sec += 60;
1329                                 set_state(c, TIME_WAIT);
1330                         }
1331
1332                         break;
1333
1334                 default:
1335                         break;
1336                 }
1337         } else {
1338                 if(!len && is_reliable(c)) {
1339                         c->dupack++;
1340
1341                         if(c->dupack == 3) {
1342                                 debug("Triplicate ACK\n");
1343                                 //TODO: Resend one packet and go to fast recovery mode. See RFC 6582.
1344                                 //We do a very simple variant here; reset the nxt pointer to the last acknowledged packet from the peer.
1345                                 //Reset the congestion window so we wait for ACKs.
1346                                 c->snd.nxt = c->snd.una;
1347                                 c->snd.cwnd = utcp->mtu;
1348                                 start_retransmit_timer(c);
1349                         }
1350                 }
1351         }
1352
1353         // 4. Update timers
1354
1355         if(advanced) {
1356                 if(c->snd.una == c->snd.last) {
1357                         stop_retransmit_timer(c);
1358                         timerclear(&c->conn_timeout);
1359                 } else if(is_reliable(c)) {
1360                         start_retransmit_timer(c);
1361                         gettimeofday(&c->conn_timeout, NULL);
1362                         c->conn_timeout.tv_sec += utcp->timeout;
1363                 }
1364         }
1365
1366 skip_ack:
1367         // 5. Process SYN stuff
1368
1369         if(hdr.ctl & SYN) {
1370                 switch(c->state) {
1371                 case SYN_SENT:
1372
1373                         // This is a SYNACK. It should always have ACKed the SYN.
1374                         if(!advanced) {
1375                                 goto reset;
1376                         }
1377
1378                         c->rcv.irs = hdr.seq;
1379                         c->rcv.nxt = hdr.seq;
1380
1381                         if(c->shut_wr) {
1382                                 c->snd.last++;
1383                                 set_state(c, FIN_WAIT_1);
1384                         } else {
1385                                 set_state(c, ESTABLISHED);
1386                         }
1387
1388                         // TODO: notify application of this somehow.
1389                         break;
1390
1391                 case SYN_RECEIVED:
1392                 case ESTABLISHED:
1393                 case FIN_WAIT_1:
1394                 case FIN_WAIT_2:
1395                 case CLOSE_WAIT:
1396                 case CLOSING:
1397                 case LAST_ACK:
1398                 case TIME_WAIT:
1399                         // Ehm, no. We should never receive a second SYN.
1400                         return 0;
1401
1402                 default:
1403 #ifdef UTCP_DEBUG
1404                         abort();
1405 #endif
1406                         return 0;
1407                 }
1408
1409                 // SYN counts as one sequence number
1410                 c->rcv.nxt++;
1411         }
1412
1413         // 6. Process new data
1414
1415         if(c->state == SYN_RECEIVED) {
1416                 // This is the ACK after the SYNACK. It should always have ACKed the SYNACK.
1417                 if(!advanced) {
1418                         goto reset;
1419                 }
1420
1421                 // Are we still LISTENing?
1422                 if(utcp->accept) {
1423                         utcp->accept(c, c->src);
1424                 }
1425
1426                 if(c->state != ESTABLISHED) {
1427                         set_state(c, CLOSED);
1428                         c->reapable = true;
1429                         goto reset;
1430                 }
1431         }
1432
1433         if(len) {
1434                 switch(c->state) {
1435                 case SYN_SENT:
1436                 case SYN_RECEIVED:
1437                         // This should never happen.
1438 #ifdef UTCP_DEBUG
1439                         abort();
1440 #endif
1441                         return 0;
1442
1443                 case ESTABLISHED:
1444                 case FIN_WAIT_1:
1445                 case FIN_WAIT_2:
1446                         break;
1447
1448                 case CLOSE_WAIT:
1449                 case CLOSING:
1450                 case LAST_ACK:
1451                 case TIME_WAIT:
1452                         // Ehm no, We should never receive more data after a FIN.
1453                         goto reset;
1454
1455                 default:
1456 #ifdef UTCP_DEBUG
1457                         abort();
1458 #endif
1459                         return 0;
1460                 }
1461
1462                 handle_incoming_data(c, hdr.seq, ptr, len);
1463         }
1464
1465         // 7. Process FIN stuff
1466
1467         if((hdr.ctl & FIN) && hdr.seq + len == c->rcv.nxt) {
1468                 switch(c->state) {
1469                 case SYN_SENT:
1470                 case SYN_RECEIVED:
1471                         // This should never happen.
1472 #ifdef UTCP_DEBUG
1473                         abort();
1474 #endif
1475                         break;
1476
1477                 case ESTABLISHED:
1478                         set_state(c, CLOSE_WAIT);
1479                         break;
1480
1481                 case FIN_WAIT_1:
1482                         set_state(c, CLOSING);
1483                         break;
1484
1485                 case FIN_WAIT_2:
1486                         gettimeofday(&c->conn_timeout, NULL);
1487                         c->conn_timeout.tv_sec += 60;
1488                         set_state(c, TIME_WAIT);
1489                         break;
1490
1491                 case CLOSE_WAIT:
1492                 case CLOSING:
1493                 case LAST_ACK:
1494                 case TIME_WAIT:
1495                         // Ehm, no. We should never receive a second FIN.
1496                         goto reset;
1497
1498                 default:
1499 #ifdef UTCP_DEBUG
1500                         abort();
1501 #endif
1502                         break;
1503                 }
1504
1505                 // FIN counts as one sequence number
1506                 c->rcv.nxt++;
1507                 len++;
1508
1509                 // Inform the application that the peer closed the connection.
1510                 if(c->recv) {
1511                         errno = 0;
1512                         c->recv(c, NULL, 0);
1513                 }
1514         }
1515
1516         // Now we send something back if:
1517         // - we advanced rcv.nxt (ie, we got some data that needs to be ACKed)
1518         //   -> sendatleastone = true
1519         // - or we got an ack, so we should maybe send a bit more data
1520         //   -> sendatleastone = false
1521
1522         ack(c, len || prevrcvnxt != c->rcv.nxt);
1523         return 0;
1524
1525 reset:
1526         swap_ports(&hdr);
1527         hdr.wnd = 0;
1528         hdr.aux = 0;
1529
1530         if(hdr.ctl & ACK) {
1531                 hdr.seq = hdr.ack;
1532                 hdr.ctl = RST;
1533         } else {
1534                 hdr.ack = hdr.seq + len;
1535                 hdr.seq = 0;
1536                 hdr.ctl = RST | ACK;
1537         }
1538
1539         print_packet(utcp, "send", &hdr, sizeof(hdr));
1540         utcp->send(utcp, &hdr, sizeof(hdr));
1541         return 0;
1542
1543 }
1544
1545 int utcp_shutdown(struct utcp_connection *c, int dir) {
1546         debug("%p shutdown %d at %u\n", c ? c->utcp : NULL, dir, c ? c->snd.last : 0);
1547
1548         if(!c) {
1549                 errno = EFAULT;
1550                 return -1;
1551         }
1552
1553         if(c->reapable) {
1554                 debug("Error: shutdown() called on closed connection %p\n", c);
1555                 errno = EBADF;
1556                 return -1;
1557         }
1558
1559         if(!(dir == UTCP_SHUT_RD || dir == UTCP_SHUT_WR || dir == UTCP_SHUT_RDWR)) {
1560                 errno = EINVAL;
1561                 return -1;
1562         }
1563
1564         // TCP does not have a provision for stopping incoming packets.
1565         // The best we can do is to just ignore them.
1566         if(dir == UTCP_SHUT_RD || dir == UTCP_SHUT_RDWR) {
1567                 c->recv = NULL;
1568         }
1569
1570         // The rest of the code deals with shutting down writes.
1571         if(dir == UTCP_SHUT_RD) {
1572                 return 0;
1573         }
1574
1575         // Only process shutting down writes once.
1576         if(c->shut_wr) {
1577                 return 0;
1578         }
1579
1580         c->shut_wr = true;
1581
1582         switch(c->state) {
1583         case CLOSED:
1584         case LISTEN:
1585                 errno = ENOTCONN;
1586                 return -1;
1587
1588         case SYN_SENT:
1589                 return 0;
1590
1591         case SYN_RECEIVED:
1592         case ESTABLISHED:
1593                 set_state(c, FIN_WAIT_1);
1594                 break;
1595
1596         case FIN_WAIT_1:
1597         case FIN_WAIT_2:
1598                 return 0;
1599
1600         case CLOSE_WAIT:
1601                 set_state(c, CLOSING);
1602                 break;
1603
1604         case CLOSING:
1605         case LAST_ACK:
1606         case TIME_WAIT:
1607                 return 0;
1608         }
1609
1610         c->snd.last++;
1611
1612         ack(c, false);
1613
1614         if(!timerisset(&c->rtrx_timeout)) {
1615                 start_retransmit_timer(c);
1616         }
1617
1618         return 0;
1619 }
1620
1621 static bool reset_connection(struct utcp_connection *c) {
1622         if(!c) {
1623                 errno = EFAULT;
1624                 return false;
1625         }
1626
1627         if(c->reapable) {
1628                 debug("Error: abort() called on closed connection %p\n", c);
1629                 errno = EBADF;
1630                 return false;
1631         }
1632
1633         c->recv = NULL;
1634         c->poll = NULL;
1635
1636         switch(c->state) {
1637         case CLOSED:
1638                 return true;
1639
1640         case LISTEN:
1641         case SYN_SENT:
1642         case CLOSING:
1643         case LAST_ACK:
1644         case TIME_WAIT:
1645                 set_state(c, CLOSED);
1646                 return true;
1647
1648         case SYN_RECEIVED:
1649         case ESTABLISHED:
1650         case FIN_WAIT_1:
1651         case FIN_WAIT_2:
1652         case CLOSE_WAIT:
1653                 set_state(c, CLOSED);
1654                 break;
1655         }
1656
1657         // Send RST
1658
1659         struct hdr hdr;
1660
1661         hdr.src = c->src;
1662         hdr.dst = c->dst;
1663         hdr.seq = c->snd.nxt;
1664         hdr.ack = 0;
1665         hdr.wnd = 0;
1666         hdr.ctl = RST;
1667
1668         print_packet(c->utcp, "send", &hdr, sizeof(hdr));
1669         c->utcp->send(c->utcp, &hdr, sizeof(hdr));
1670         return true;
1671 }
1672
1673 // Closes all the opened connections
1674 void utcp_abort_all_connections(struct utcp *utcp) {
1675         if(!utcp) {
1676                 errno = EINVAL;
1677                 return;
1678         }
1679
1680         for(int i = 0; i < utcp->nconnections; i++) {
1681                 struct utcp_connection *c = utcp->connections[i];
1682
1683                 if(c->reapable || c->state == CLOSED) {
1684                         continue;
1685                 }
1686
1687                 utcp_recv_t old_recv = c->recv;
1688
1689                 reset_connection(c);
1690
1691                 if(old_recv) {
1692                         errno = 0;
1693                         old_recv(c, NULL, 0);
1694                 }
1695         }
1696
1697         return;
1698 }
1699
1700 int utcp_close(struct utcp_connection *c) {
1701         if(utcp_shutdown(c, SHUT_RDWR) && errno != ENOTCONN) {
1702                 return -1;
1703         }
1704
1705         c->recv = NULL;
1706         c->poll = NULL;
1707         c->reapable = true;
1708         return 0;
1709 }
1710
1711 int utcp_abort(struct utcp_connection *c) {
1712         if(!reset_connection(c)) {
1713                 return -1;
1714         }
1715
1716         c->reapable = true;
1717         return 0;
1718 }
1719
1720 /* Handle timeouts.
1721  * One call to this function will loop through all connections,
1722  * checking if something needs to be resent or not.
1723  * The return value is the time to the next timeout in milliseconds,
1724  * or maybe a negative value if the timeout is infinite.
1725  */
1726 struct timeval utcp_timeout(struct utcp *utcp) {
1727         struct timeval now;
1728         gettimeofday(&now, NULL);
1729         struct timeval next = {now.tv_sec + 3600, now.tv_usec};
1730
1731         for(int i = 0; i < utcp->nconnections; i++) {
1732                 struct utcp_connection *c = utcp->connections[i];
1733
1734                 if(!c) {
1735                         continue;
1736                 }
1737
1738                 // delete connections that have been utcp_close()d.
1739                 if(c->state == CLOSED) {
1740                         if(c->reapable) {
1741                                 debug("Reaping %p\n", c);
1742                                 free_connection(c);
1743                                 i--;
1744                         }
1745
1746                         continue;
1747                 }
1748
1749                 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &now, <)) {
1750                         errno = ETIMEDOUT;
1751                         c->state = CLOSED;
1752
1753                         if(c->recv) {
1754                                 c->recv(c, NULL, 0);
1755                         }
1756
1757                         if(c->poll) {
1758                                 c->poll(c, 0);
1759                         }
1760
1761                         continue;
1762                 }
1763
1764                 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &now, <)) {
1765                         debug("retransmit()\n");
1766                         retransmit(c);
1767                 }
1768
1769                 if(c->poll) {
1770                         if((c->state == ESTABLISHED || c->state == CLOSE_WAIT)) {
1771                                 uint32_t len =  buffer_free(&c->sndbuf);
1772
1773                                 if(len) {
1774                                         c->poll(c, len);
1775                                 }
1776                         } else if(c->state == CLOSED) {
1777                                 c->poll(c, 0);
1778                         }
1779                 }
1780
1781                 if(timerisset(&c->conn_timeout) && timercmp(&c->conn_timeout, &next, <)) {
1782                         next = c->conn_timeout;
1783                 }
1784
1785                 if(timerisset(&c->rtrx_timeout) && timercmp(&c->rtrx_timeout, &next, <)) {
1786                         next = c->rtrx_timeout;
1787                 }
1788         }
1789
1790         struct timeval diff;
1791
1792         timersub(&next, &now, &diff);
1793
1794         return diff;
1795 }
1796
1797 bool utcp_is_active(struct utcp *utcp) {
1798         if(!utcp) {
1799                 return false;
1800         }
1801
1802         for(int i = 0; i < utcp->nconnections; i++)
1803                 if(utcp->connections[i]->state != CLOSED && utcp->connections[i]->state != TIME_WAIT) {
1804                         return true;
1805                 }
1806
1807         return false;
1808 }
1809
1810 struct utcp *utcp_init(utcp_accept_t accept, utcp_pre_accept_t pre_accept, utcp_send_t send, void *priv) {
1811         if(!send) {
1812                 errno = EFAULT;
1813                 return NULL;
1814         }
1815
1816         struct utcp *utcp = calloc(1, sizeof(*utcp));
1817
1818         if(!utcp) {
1819                 return NULL;
1820         }
1821
1822         utcp->accept = accept;
1823         utcp->pre_accept = pre_accept;
1824         utcp->send = send;
1825         utcp->priv = priv;
1826         utcp->mtu = DEFAULT_MTU;
1827         utcp->timeout = DEFAULT_USER_TIMEOUT; // sec
1828         utcp->rto = START_RTO; // usec
1829
1830         return utcp;
1831 }
1832
1833 void utcp_exit(struct utcp *utcp) {
1834         if(!utcp) {
1835                 return;
1836         }
1837
1838         for(int i = 0; i < utcp->nconnections; i++) {
1839                 struct utcp_connection *c = utcp->connections[i];
1840
1841                 if(!c->reapable)
1842                         if(c->recv) {
1843                                 c->recv(c, NULL, 0);
1844                         }
1845
1846                 buffer_exit(&c->rcvbuf);
1847                 buffer_exit(&c->sndbuf);
1848                 free(c);
1849         }
1850
1851         free(utcp->connections);
1852         free(utcp);
1853 }
1854
1855 uint16_t utcp_get_mtu(struct utcp *utcp) {
1856         return utcp ? utcp->mtu : 0;
1857 }
1858
1859 void utcp_set_mtu(struct utcp *utcp, uint16_t mtu) {
1860         // TODO: handle overhead of the header
1861         if(utcp) {
1862                 utcp->mtu = mtu;
1863         }
1864 }
1865
1866 void utcp_reset_timers(struct utcp *utcp) {
1867         if(!utcp) {
1868                 return;
1869         }
1870
1871         struct timeval now, then;
1872
1873         gettimeofday(&now, NULL);
1874
1875         then = now;
1876
1877         then.tv_sec += utcp->timeout;
1878
1879         for(int i = 0; i < utcp->nconnections; i++) {
1880                 struct utcp_connection *c = utcp->connections[i];
1881
1882                 if(c->reapable) {
1883                         continue;
1884                 }
1885
1886                 c->rtrx_timeout = now;
1887                 c->conn_timeout = then;
1888                 c->rtt_start.tv_sec = 0;
1889         }
1890
1891         if(utcp->rto > START_RTO) {
1892                 utcp->rto = START_RTO;
1893         }
1894 }
1895
1896 int utcp_get_user_timeout(struct utcp *u) {
1897         return u ? u->timeout : 0;
1898 }
1899
1900 void utcp_set_user_timeout(struct utcp *u, int timeout) {
1901         if(u) {
1902                 u->timeout = timeout;
1903         }
1904 }
1905
1906 size_t utcp_get_sndbuf(struct utcp_connection *c) {
1907         return c ? c->sndbuf.maxsize : 0;
1908 }
1909
1910 size_t utcp_get_sndbuf_free(struct utcp_connection *c) {
1911         if(!c) {
1912                 return 0;
1913         }
1914
1915         switch(c->state) {
1916         case SYN_SENT:
1917         case SYN_RECEIVED:
1918         case ESTABLISHED:
1919         case CLOSE_WAIT:
1920                 return buffer_free(&c->sndbuf);
1921
1922         default:
1923                 return 0;
1924         }
1925 }
1926
1927 void utcp_set_sndbuf(struct utcp_connection *c, size_t size) {
1928         if(!c) {
1929                 return;
1930         }
1931
1932         c->sndbuf.maxsize = size;
1933
1934         if(c->sndbuf.maxsize != size) {
1935                 c->sndbuf.maxsize = -1;
1936         }
1937 }
1938
1939 size_t utcp_get_rcvbuf(struct utcp_connection *c) {
1940         return c ? c->rcvbuf.maxsize : 0;
1941 }
1942
1943 size_t utcp_get_rcvbuf_free(struct utcp_connection *c) {
1944         if(c && (c->state == ESTABLISHED || c->state == CLOSE_WAIT)) {
1945                 return buffer_free(&c->rcvbuf);
1946         } else {
1947                 return 0;
1948         }
1949 }
1950
1951 void utcp_set_rcvbuf(struct utcp_connection *c, size_t size) {
1952         if(!c) {
1953                 return;
1954         }
1955
1956         c->rcvbuf.maxsize = size;
1957
1958         if(c->rcvbuf.maxsize != size) {
1959                 c->rcvbuf.maxsize = -1;
1960         }
1961 }
1962
1963 size_t utcp_get_sendq(struct utcp_connection *c) {
1964         return c->sndbuf.used;
1965 }
1966
1967 size_t utcp_get_recvq(struct utcp_connection *c) {
1968         return c->rcvbuf.used;
1969 }
1970
1971 bool utcp_get_nodelay(struct utcp_connection *c) {
1972         return c ? c->nodelay : false;
1973 }
1974
1975 void utcp_set_nodelay(struct utcp_connection *c, bool nodelay) {
1976         if(c) {
1977                 c->nodelay = nodelay;
1978         }
1979 }
1980
1981 bool utcp_get_keepalive(struct utcp_connection *c) {
1982         return c ? c->keepalive : false;
1983 }
1984
1985 void utcp_set_keepalive(struct utcp_connection *c, bool keepalive) {
1986         if(c) {
1987                 c->keepalive = keepalive;
1988         }
1989 }
1990
1991 size_t utcp_get_outq(struct utcp_connection *c) {
1992         return c ? seqdiff(c->snd.nxt, c->snd.una) : 0;
1993 }
1994
1995 void utcp_set_recv_cb(struct utcp_connection *c, utcp_recv_t recv) {
1996         if(c) {
1997                 c->recv = recv;
1998         }
1999 }
2000
2001 void utcp_set_poll_cb(struct utcp_connection *c, utcp_poll_t poll) {
2002         if(c) {
2003                 c->poll = poll;
2004         }
2005 }
2006
2007 void utcp_set_accept_cb(struct utcp *utcp, utcp_accept_t accept, utcp_pre_accept_t pre_accept) {
2008         if(utcp) {
2009                 utcp->accept = accept;
2010                 utcp->pre_accept = pre_accept;
2011         }
2012 }
2013
2014 void utcp_expect_data(struct utcp_connection *c, bool expect) {
2015         if(!c || c->reapable) {
2016                 return;
2017         }
2018
2019         if(!(c->state == ESTABLISHED || c->state == FIN_WAIT_1 || c->state == FIN_WAIT_2)) {
2020                 return;
2021         }
2022
2023         if(expect) {
2024                 // If we expect data, start the connection timer.
2025                 if(!timerisset(&c->conn_timeout)) {
2026                         gettimeofday(&c->conn_timeout, NULL);
2027                         c->conn_timeout.tv_sec += c->utcp->timeout;
2028                 }
2029         } else {
2030                 // If we want to cancel expecting data, only clear the timer when there is no unACKed data.
2031                 if(c->snd.una == c->snd.last) {
2032                         timerclear(&c->conn_timeout);
2033                 }
2034         }
2035 }
2036
2037 void utcp_offline(struct utcp *utcp, bool offline) {
2038         for(int i = 0; i < utcp->nconnections; i++) {
2039                 struct utcp_connection *c = utcp->connections[i];
2040
2041                 if(!c->reapable) {
2042                         utcp_expect_data(c, offline);
2043
2044                         // If we are online again, reset the retransmission timers, but keep the connection timeout as it is,
2045                         // to prevent peers toggling online/offline state frequently from keeping connections alive
2046                         // if there is no progress in sending actual data.
2047                         if(!offline) {
2048                                 gettimeofday(&utcp->connections[i]->rtrx_timeout, NULL);
2049                                 utcp->connections[i]->rtt_start.tv_sec = 0;
2050                         }
2051                 }
2052         }
2053
2054         if(!offline && utcp->rto > START_RTO) {
2055                 utcp->rto = START_RTO;
2056         }
2057 }