]> git.meshlink.io Git - meshlink/blob - src/utcp.c
Ensure aux field is initialized in RST packets.
[meshlink] / src / 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 #include "system.h"
21 #include <time.h>
22
23 #include "utcp_priv.h"
24
25 #ifndef EBADMSG
26 #define EBADMSG         104
27 #endif
28
29 #ifndef SHUT_RDWR
30 #define SHUT_RDWR 2
31 #endif
32
33 #ifdef poll
34 #undef poll
35 #endif
36
37 #ifndef UTCP_CLOCK
38 #if defined(CLOCK_MONOTONIC_RAW) && defined(__x86_64__)
39 #define UTCP_CLOCK CLOCK_MONOTONIC_RAW
40 #else
41 #define UTCP_CLOCK CLOCK_MONOTONIC
42 #endif
43 #endif
44
45 static void timespec_sub(const struct timespec *a, const struct timespec *b, struct timespec *r) {
46         r->tv_sec = a->tv_sec - b->tv_sec;
47         r->tv_nsec = a->tv_nsec - b->tv_nsec;
48
49         if(r->tv_nsec < 0) {
50                 r->tv_sec--, r->tv_nsec += NSEC_PER_SEC;
51         }
52 }
53
54 static int32_t timespec_diff_usec(const struct timespec *a, const struct timespec *b) {
55         return (a->tv_sec - b->tv_sec) * 1000000 + (a->tv_nsec - b->tv_nsec) / 1000;
56 }
57
58 static bool timespec_lt(const struct timespec *a, const struct timespec *b) {
59         if(a->tv_sec == b->tv_sec) {
60                 return a->tv_nsec < b->tv_nsec;
61         } else {
62                 return a->tv_sec < b->tv_sec;
63         }
64 }
65
66 static void timespec_clear(struct timespec *a) {
67         a->tv_sec = 0;
68         a->tv_nsec = 0;
69 }
70
71 static bool timespec_isset(const struct timespec *a) {
72         return a->tv_sec;
73 }
74
75 static long CLOCK_GRANULARITY; // usec
76
77 static inline size_t min(size_t a, size_t b) {
78         return a < b ? a : b;
79 }
80
81 static inline size_t max(size_t a, size_t b) {
82         return a > b ? a : b;
83 }
84
85 #ifdef UTCP_DEBUG
86 #include <stdarg.h>
87
88 #ifndef UTCP_DEBUG_DATALEN
89 #define UTCP_DEBUG_DATALEN 20
90 #endif
91
92 static void debug(struct utcp_connection *c, const char *format, ...) {
93         struct timespec tv;
94         char buf[1024];
95         int len;
96
97         clock_gettime(CLOCK_REALTIME, &tv);
98         len = snprintf(buf, sizeof(buf), "%ld.%06lu %u:%u ", (long)tv.tv_sec, tv.tv_nsec / 1000, c ? c->src : 0, c ? c->dst : 0);
99         va_list ap;
100         va_start(ap, format);
101         len += vsnprintf(buf + len, sizeof(buf) - len, format, ap);
102         va_end(ap);
103
104         if(len > 0 && (size_t)len < sizeof(buf)) {
105                 fwrite(buf, len, 1, stderr);
106         }
107 }
108
109 static void print_packet(struct utcp_connection *c, const char *dir, const void *pkt, size_t len) {
110         struct hdr hdr;
111
112         if(len < sizeof(hdr)) {
113                 debug(c, "%s: short packet (%lu bytes)\n", dir, (unsigned long)len);
114                 return;
115         }
116
117         memcpy(&hdr, pkt, sizeof(hdr));
118
119         uint32_t datalen;
120
121         if(len > sizeof(hdr)) {
122                 datalen = min(len - sizeof(hdr), UTCP_DEBUG_DATALEN);
123         } else {
124                 datalen = 0;
125         }
126
127
128         const uint8_t *data = (uint8_t *)pkt + sizeof(hdr);
129         char str[datalen * 2 + 1];
130         char *p = str;
131
132         for(uint32_t i = 0; i < datalen; i++) {
133                 *p++ = "0123456789ABCDEF"[data[i] >> 4];
134                 *p++ = "0123456789ABCDEF"[data[i] & 15];
135         }
136
137         *p = 0;
138
139         debug(c, "%s: len %lu src %u dst %u seq %u ack %u wnd %u aux %x ctl %s%s%s%s%s data %s\n",
140               dir, (unsigned long)len, hdr.src, hdr.dst, hdr.seq, hdr.ack, hdr.wnd, hdr.aux,
141               hdr.ctl & SYN ? "SYN" : "",
142               hdr.ctl & RST ? "RST" : "",
143               hdr.ctl & FIN ? "FIN" : "",
144               hdr.ctl & ACK ? "ACK" : "",
145               hdr.ctl & MF ? "MF" : "",
146               str
147              );
148 }
149
150 static void debug_cwnd(struct utcp_connection *c) {
151         debug(c, "snd.cwnd %u snd.ssthresh %u\n", c->snd.cwnd, ~c->snd.ssthresh ? c->snd.ssthresh : 0);
152 }
153 #else
154 #define debug(...) do {} while(0)
155 #define print_packet(...) do {} while(0)
156 #define debug_cwnd(...) do {} while(0)
157 #endif
158
159 static void set_state(struct utcp_connection *c, enum state state) {
160         c->state = state;
161
162         if(state == ESTABLISHED) {
163                 timespec_clear(&c->conn_timeout);
164         }
165
166         debug(c, "state %s\n", strstate[state]);
167 }
168
169 static bool fin_wanted(struct utcp_connection *c, uint32_t seq) {
170         if(seq != c->snd.last) {
171                 return false;
172         }
173
174         switch(c->state) {
175         case FIN_WAIT_1:
176         case CLOSING:
177         case LAST_ACK:
178                 return true;
179
180         default:
181                 return false;
182         }
183 }
184
185 static bool is_reliable(struct utcp_connection *c) {
186         return c->flags & UTCP_RELIABLE;
187 }
188
189 static int32_t seqdiff(uint32_t a, uint32_t b) {
190         return a - b;
191 }
192
193 // Buffer functions
194 static bool buffer_wraps(struct buffer *buf) {
195         return buf->size - buf->offset < buf->used;
196 }
197
198 static bool buffer_resize(struct buffer *buf, uint32_t newsize) {
199         assert(!buf->external);
200
201         if(!newsize) {
202                 free(buf->data);
203                 buf->data = NULL;
204                 buf->size = 0;
205                 buf->offset = 0;
206                 return true;
207         }
208
209         char *newdata = realloc(buf->data, newsize);
210
211         if(!newdata) {
212                 return false;
213         }
214
215         buf->data = newdata;
216
217         if(buffer_wraps(buf)) {
218                 // Shift the right part of the buffer until it hits the end of the new buffer.
219                 // Old situation:
220                 // [345......012]
221                 // New situation:
222                 // [345.........|........012]
223                 uint32_t tailsize = buf->size - buf->offset;
224                 uint32_t newoffset = newsize - tailsize;
225                 memmove(buf->data + newoffset, buf->data + buf->offset, tailsize);
226                 buf->offset = newoffset;
227         }
228
229         buf->size = newsize;
230         return true;
231 }
232
233 // Store data into the buffer
234 static ssize_t buffer_put_at(struct buffer *buf, size_t offset, const void *data, size_t len) {
235         debug(NULL, "buffer_put_at %lu %lu %lu\n", (unsigned long)buf->used, (unsigned long)offset, (unsigned long)len);
236
237         // Ensure we don't store more than maxsize bytes in total
238         size_t required = offset + len;
239
240         if(required > buf->maxsize) {
241                 if(offset >= buf->maxsize) {
242                         return 0;
243                 }
244
245                 len = buf->maxsize - offset;
246                 required = buf->maxsize;
247         }
248
249         // Check if we need to resize the buffer
250         if(required > buf->size) {
251                 size_t newsize = buf->size;
252
253                 if(!newsize) {
254                         newsize = 4096;
255                 }
256
257                 do {
258                         newsize *= 2;
259                 } while(newsize < required);
260
261                 if(newsize > buf->maxsize) {
262                         newsize = buf->maxsize;
263                 }
264
265                 if(!buffer_resize(buf, newsize)) {
266                         return -1;
267                 }
268         }
269
270         uint32_t realoffset = buf->offset + offset;
271
272         if(buf->size - buf->offset <= offset) {
273                 // The offset wrapped
274                 realoffset -= buf->size;
275         }
276
277         if(buf->size - realoffset < len) {
278                 // The new chunk of data must be wrapped
279                 memcpy(buf->data + realoffset, data, buf->size - realoffset);
280                 memcpy(buf->data, (char *)data + buf->size - realoffset, len - (buf->size - realoffset));
281         } else {
282                 memcpy(buf->data + realoffset, data, len);
283         }
284
285         if(required > buf->used) {
286                 buf->used = required;
287         }
288
289         return len;
290 }
291
292 static ssize_t buffer_put(struct buffer *buf, const void *data, size_t len) {
293         return buffer_put_at(buf, buf->used, data, len);
294 }
295
296 // Copy data from the buffer without removing it.
297 static ssize_t buffer_copy(struct buffer *buf, void *data, size_t offset, size_t len) {
298         // Ensure we don't copy more than is actually stored in the buffer
299         if(offset >= buf->used) {
300                 return 0;
301         }
302
303         if(buf->used - offset < len) {
304                 len = buf->used - offset;
305         }
306
307         uint32_t realoffset = buf->offset + offset;
308
309         if(buf->size - buf->offset <= offset) {
310                 // The offset wrapped
311                 realoffset -= buf->size;
312         }
313
314         if(buf->size - realoffset < len) {
315                 // The data is wrapped
316                 memcpy(data, buf->data + realoffset, buf->size - realoffset);
317                 memcpy((char *)data + buf->size - realoffset, buf->data, len - (buf->size - realoffset));
318         } else {
319                 memcpy(data, buf->data + realoffset, len);
320         }
321
322         return len;
323 }
324
325 // Copy data from the buffer without removing it.
326 static ssize_t buffer_call(struct utcp_connection *c, struct buffer *buf, size_t offset, size_t len) {
327         if(!c->recv) {
328                 return len;
329         }
330
331         // Ensure we don't copy more than is actually stored in the buffer
332         if(offset >= buf->used) {
333                 return 0;
334         }
335
336         if(buf->used - offset < len) {
337                 len = buf->used - offset;
338         }
339
340         uint32_t realoffset = buf->offset + offset;
341
342         if(buf->size - buf->offset <= offset) {
343                 // The offset wrapped
344                 realoffset -= buf->size;
345         }
346
347         if(buf->size - realoffset < len) {
348                 // The data is wrapped
349                 ssize_t rx1 = c->recv(c, buf->data + realoffset, buf->size - realoffset);
350
351                 if(rx1 < buf->size - realoffset) {
352                         return rx1;
353                 }
354
355                 // The channel might have been closed by the previous callback
356                 if(!c->recv) {
357                         return len;
358                 }
359
360                 ssize_t rx2 = c->recv(c, buf->data, len - (buf->size - realoffset));
361
362                 if(rx2 < 0) {
363                         return rx2;
364                 } else {
365                         return rx1 + rx2;
366                 }
367         } else {
368                 return c->recv(c, buf->data + realoffset, len);
369         }
370 }
371
372 // Discard data from the buffer.
373 static ssize_t buffer_discard(struct buffer *buf, size_t len) {
374         if(buf->used < len) {
375                 len = buf->used;
376         }
377
378         if(buf->size - buf->offset <= len) {
379                 buf->offset -= buf->size;
380         }
381
382         if(buf->used == len) {
383                 buf->offset = 0;
384         } else {
385                 buf->offset += len;
386         }
387
388         buf->used -= len;
389
390         return len;
391 }
392
393 static void buffer_clear(struct buffer *buf) {
394         buf->used = 0;
395         buf->offset = 0;
396 }
397
398 static bool buffer_set_size(struct buffer *buf, uint32_t minsize, uint32_t maxsize) {
399         if(maxsize < minsize) {
400                 maxsize = minsize;
401         }
402
403         buf->maxsize = maxsize;
404
405         return buf->size >= minsize || buffer_resize(buf, minsize);
406 }
407
408 static void buffer_transfer(struct buffer *buf, char *newdata, size_t newsize) {
409         if(buffer_wraps(buf)) {
410                 // Old situation:
411                 // [345......012]
412                 // New situation:
413                 // [012345......]
414                 uint32_t tailsize = buf->size - buf->offset;
415                 memcpy(newdata, buf->data + buf->offset, tailsize);
416                 memcpy(newdata + tailsize, buf->data, buf->used - tailsize);
417         } else {
418                 // Old situation:
419                 // [....012345..]
420                 // New situation:
421                 // [012345......]
422                 memcpy(newdata, buf->data + buf->offset, buf->used);
423         }
424
425         buf->offset = 0;
426         buf->size = newsize;
427 }
428
429 static void set_buffer_storage(struct buffer *buf, char *data, size_t size) {
430         if(size > UINT32_MAX) {
431                 size = UINT32_MAX;
432         }
433
434         buf->maxsize = size;
435
436         if(data) {
437                 if(buf->external) {
438                         // Don't allow resizing an external buffer
439                         abort();
440                 }
441
442                 if(size < buf->used) {
443                         // Ignore requests for an external buffer if we are already using more than it can store
444                         return;
445                 }
446
447                 // Transition from internal to external buffer
448                 buffer_transfer(buf, data, size);
449                 free(buf->data);
450                 buf->data = data;
451                 buf->external = true;
452         } else if(buf->external) {
453                 // Transition from external to internal buf
454                 size_t minsize = buf->used <= DEFAULT_SNDBUFSIZE ? DEFAULT_SNDBUFSIZE : buf->used;
455
456                 if(minsize) {
457                         data = malloc(minsize);
458
459                         if(!data) {
460                                 // Cannot handle this
461                                 abort();
462                         }
463
464                         buffer_transfer(buf, data, minsize);
465                         buf->data = data;
466                 } else {
467                         buf->data = NULL;
468                         buf->size = 0;
469                 }
470
471                 buf->external = false;
472         } else {
473                 // Don't do anything if the buffer wraps
474                 if(buffer_wraps(buf)) {
475                         return;
476                 }
477
478                 // Realloc internal storage
479                 size_t minsize = max(DEFAULT_SNDBUFSIZE, buf->offset + buf->used);
480
481                 if(minsize) {
482                         data = realloc(buf->data, minsize);
483
484                         if(data) {
485                                 buf->data = data;
486                                 buf->size = minsize;
487                         }
488                 } else {
489                         free(buf->data);
490                         buf->data = NULL;
491                         buf->size = 0;
492                 }
493         }
494 }
495
496 static void buffer_exit(struct buffer *buf) {
497         if(!buf->external) {
498                 free(buf->data);
499         }
500
501         memset(buf, 0, sizeof(*buf));
502 }
503
504 static uint32_t buffer_free(const struct buffer *buf) {
505         return buf->maxsize > buf->used ? buf->maxsize - buf->used : 0;
506 }
507
508 // Connections are stored in a sorted list.
509 // This gives O(log(N)) lookup time, O(N log(N)) insertion time and O(N) deletion time.
510
511 static int compare(const void *va, const void *vb) {
512         assert(va && vb);
513
514         const struct utcp_connection *a = *(struct utcp_connection **)va;
515         const struct utcp_connection *b = *(struct utcp_connection **)vb;
516
517         assert(a && b);
518
519         int c = (int)a->src - (int)b->src;
520
521         if(c) {
522                 return c;
523         }
524
525         c = (int)a->dst - (int)b->dst;
526         return c;
527 }
528
529 static struct utcp_connection *find_connection(const struct utcp *utcp, uint16_t src, uint16_t dst) {
530         if(!utcp->nconnections) {
531                 return NULL;
532         }
533
534         struct utcp_connection key = {
535                 .src = src,
536                 .dst = dst,
537         }, *keyp = &key;
538         struct utcp_connection **match = bsearch(&keyp, utcp->connections, utcp->nconnections, sizeof(*utcp->connections), compare);
539         return match ? *match : NULL;
540 }
541
542 static void free_connection(struct utcp_connection *c) {
543         struct utcp *utcp = c->utcp;
544         struct utcp_connection **cp = bsearch(&c, utcp->connections, utcp->nconnections, sizeof(*utcp->connections), compare);
545
546         assert(cp);
547
548         int i = cp - utcp->connections;
549         memmove(cp, cp + 1, (utcp->nconnections - i - 1) * sizeof(*cp));
550         utcp->nconnections--;
551
552         buffer_exit(&c->rcvbuf);
553         buffer_exit(&c->sndbuf);
554         free(c);
555 }
556
557 static struct utcp_connection *allocate_connection(struct utcp *utcp, uint16_t src, uint16_t dst) {
558         // Check whether this combination of src and dst is free
559
560         if(src) {
561                 if(find_connection(utcp, src, dst)) {
562                         errno = EADDRINUSE;
563                         return NULL;
564                 }
565         } else { // If src == 0, generate a random port number with the high bit set
566                 if(utcp->nconnections >= 32767) {
567                         errno = ENOMEM;
568                         return NULL;
569                 }
570
571                 src = rand() | 0x8000;
572
573                 while(find_connection(utcp, src, dst)) {
574                         src++;
575                 }
576         }
577
578         // Allocate memory for the new connection
579
580         if(utcp->nconnections >= utcp->nallocated) {
581                 if(!utcp->nallocated) {
582                         utcp->nallocated = 4;
583                 } else {
584                         utcp->nallocated *= 2;
585                 }
586
587                 struct utcp_connection **new_array = realloc(utcp->connections, utcp->nallocated * sizeof(*utcp->connections));
588
589                 if(!new_array) {
590                         return NULL;
591                 }
592
593                 utcp->connections = new_array;
594         }
595
596         struct utcp_connection *c = calloc(1, sizeof(*c));
597
598         if(!c) {
599                 return NULL;
600         }
601
602         if(!buffer_set_size(&c->sndbuf, DEFAULT_SNDBUFSIZE, DEFAULT_MAXSNDBUFSIZE)) {
603                 free(c);
604                 return NULL;
605         }
606
607         if(!buffer_set_size(&c->rcvbuf, DEFAULT_RCVBUFSIZE, DEFAULT_MAXRCVBUFSIZE)) {
608                 buffer_exit(&c->sndbuf);
609                 free(c);
610                 return NULL;
611         }
612
613         // Fill in the details
614
615         c->src = src;
616         c->dst = dst;
617 #ifdef UTCP_DEBUG
618         c->snd.iss = 0;
619 #else
620         c->snd.iss = rand();
621 #endif
622         c->snd.una = c->snd.iss;
623         c->snd.nxt = c->snd.iss + 1;
624         c->snd.last = c->snd.nxt;
625         c->snd.cwnd = (utcp->mss > 2190 ? 2 : utcp->mss > 1095 ? 3 : 4) * utcp->mss;
626         c->snd.ssthresh = ~0;
627         debug_cwnd(c);
628         c->srtt = 0;
629         c->rttvar = 0;
630         c->rto = START_RTO;
631         c->utcp = utcp;
632
633         // Add it to the sorted list of connections
634
635         utcp->connections[utcp->nconnections++] = c;
636         qsort(utcp->connections, utcp->nconnections, sizeof(*utcp->connections), compare);
637
638         return c;
639 }
640
641 static inline uint32_t absdiff(uint32_t a, uint32_t b) {
642         if(a > b) {
643                 return a - b;
644         } else {
645                 return b - a;
646         }
647 }
648
649 // Update RTT variables. See RFC 6298.
650 static void update_rtt(struct utcp_connection *c, uint32_t rtt) {
651         if(!rtt) {
652                 debug(c, "invalid rtt\n");
653                 return;
654         }
655
656         if(!c->srtt) {
657                 c->srtt = rtt;
658                 c->rttvar = rtt / 2;
659         } else {
660                 c->rttvar = (c->rttvar * 3 + absdiff(c->srtt, rtt)) / 4;
661                 c->srtt = (c->srtt * 7 + rtt) / 8;
662         }
663
664         c->rto = c->srtt + max(4 * c->rttvar, CLOCK_GRANULARITY);
665
666         if(c->rto > MAX_RTO) {
667                 c->rto = MAX_RTO;
668         }
669
670         debug(c, "rtt %u srtt %u rttvar %u rto %u\n", rtt, c->srtt, c->rttvar, c->rto);
671 }
672
673 static void start_retransmit_timer(struct utcp_connection *c) {
674         clock_gettime(UTCP_CLOCK, &c->rtrx_timeout);
675
676         uint32_t rto = c->rto;
677
678         while(rto > USEC_PER_SEC) {
679                 c->rtrx_timeout.tv_sec++;
680                 rto -= USEC_PER_SEC;
681         }
682
683         c->rtrx_timeout.tv_nsec += rto * 1000;
684
685         if(c->rtrx_timeout.tv_nsec >= NSEC_PER_SEC) {
686                 c->rtrx_timeout.tv_nsec -= NSEC_PER_SEC;
687                 c->rtrx_timeout.tv_sec++;
688         }
689
690         debug(c, "rtrx_timeout %ld.%06lu\n", c->rtrx_timeout.tv_sec, c->rtrx_timeout.tv_nsec);
691 }
692
693 static void stop_retransmit_timer(struct utcp_connection *c) {
694         timespec_clear(&c->rtrx_timeout);
695         debug(c, "rtrx_timeout cleared\n");
696 }
697
698 struct utcp_connection *utcp_connect_ex(struct utcp *utcp, uint16_t dst, utcp_recv_t recv, void *priv, uint32_t flags) {
699         struct utcp_connection *c = allocate_connection(utcp, 0, dst);
700
701         if(!c) {
702                 return NULL;
703         }
704
705         assert((flags & ~0x1f) == 0);
706
707         c->flags = flags;
708         c->recv = recv;
709         c->priv = priv;
710
711         struct {
712                 struct hdr hdr;
713                 uint8_t init[4];
714         } pkt;
715
716         pkt.hdr.src = c->src;
717         pkt.hdr.dst = c->dst;
718         pkt.hdr.seq = c->snd.iss;
719         pkt.hdr.ack = 0;
720         pkt.hdr.wnd = c->rcvbuf.maxsize;
721         pkt.hdr.ctl = SYN;
722         pkt.hdr.aux = 0x0101;
723         pkt.init[0] = 1;
724         pkt.init[1] = 0;
725         pkt.init[2] = 0;
726         pkt.init[3] = flags & 0x7;
727
728         set_state(c, SYN_SENT);
729
730         print_packet(c, "send", &pkt, sizeof(pkt));
731         utcp->send(utcp, &pkt, sizeof(pkt));
732
733         clock_gettime(UTCP_CLOCK, &c->conn_timeout);
734         c->conn_timeout.tv_sec += utcp->timeout;
735
736         start_retransmit_timer(c);
737
738         return c;
739 }
740
741 struct utcp_connection *utcp_connect(struct utcp *utcp, uint16_t dst, utcp_recv_t recv, void *priv) {
742         return utcp_connect_ex(utcp, dst, recv, priv, UTCP_TCP);
743 }
744
745 void utcp_accept(struct utcp_connection *c, utcp_recv_t recv, void *priv) {
746         if(c->reapable || c->state != SYN_RECEIVED) {
747                 debug(c, "accept() called on invalid connection in state %s\n", c, strstate[c->state]);
748                 return;
749         }
750
751         debug(c, "accepted %p %p\n", c, recv, priv);
752         c->recv = recv;
753         c->priv = priv;
754         c->do_poll = true;
755         set_state(c, ESTABLISHED);
756 }
757
758 static void ack(struct utcp_connection *c, bool sendatleastone) {
759         int32_t left = seqdiff(c->snd.last, c->snd.nxt);
760         int32_t cwndleft = is_reliable(c) ? min(c->snd.cwnd, c->snd.wnd) - seqdiff(c->snd.nxt, c->snd.una) : MAX_UNRELIABLE_SIZE;
761
762         assert(left >= 0);
763
764         if(cwndleft <= 0) {
765                 left = 0;
766         } else if(cwndleft < left) {
767                 left = cwndleft;
768
769                 if(!sendatleastone || cwndleft > c->utcp->mss) {
770                         left -= left % c->utcp->mss;
771                 }
772         }
773
774         debug(c, "cwndleft %d left %d\n", cwndleft, left);
775
776         if(!left && !sendatleastone) {
777                 return;
778         }
779
780         struct {
781                 struct hdr hdr;
782                 uint8_t data[];
783         } *pkt = c->utcp->pkt;
784
785         pkt->hdr.src = c->src;
786         pkt->hdr.dst = c->dst;
787         pkt->hdr.ack = c->rcv.nxt;
788         pkt->hdr.wnd = is_reliable(c) ? c->rcvbuf.maxsize : 0;
789         pkt->hdr.ctl = ACK;
790         pkt->hdr.aux = 0;
791
792         do {
793                 uint32_t seglen = left > c->utcp->mss ? c->utcp->mss : left;
794                 pkt->hdr.seq = c->snd.nxt;
795
796                 buffer_copy(&c->sndbuf, pkt->data, seqdiff(c->snd.nxt, c->snd.una), seglen);
797
798                 c->snd.nxt += seglen;
799                 left -= seglen;
800
801                 if(!is_reliable(c)) {
802                         if(left) {
803                                 pkt->hdr.ctl |= MF;
804                         } else {
805                                 pkt->hdr.ctl &= ~MF;
806                         }
807                 }
808
809                 if(seglen && fin_wanted(c, c->snd.nxt)) {
810                         seglen--;
811                         pkt->hdr.ctl |= FIN;
812                 }
813
814                 if(!c->rtt_start.tv_sec) {
815                         // Start RTT measurement
816                         clock_gettime(UTCP_CLOCK, &c->rtt_start);
817                         c->rtt_seq = pkt->hdr.seq + seglen;
818                         debug(c, "starting RTT measurement, expecting ack %u\n", c->rtt_seq);
819                 }
820
821                 print_packet(c, "send", pkt, sizeof(pkt->hdr) + seglen);
822                 c->utcp->send(c->utcp, pkt, sizeof(pkt->hdr) + seglen);
823
824                 if(left && !is_reliable(c)) {
825                         pkt->hdr.wnd += seglen;
826                 }
827         } while(left);
828 }
829
830 ssize_t utcp_send(struct utcp_connection *c, const void *data, size_t len) {
831         if(c->reapable) {
832                 debug(c, "send() called on closed connection\n");
833                 errno = EBADF;
834                 return -1;
835         }
836
837         switch(c->state) {
838         case CLOSED:
839         case LISTEN:
840                 debug(c, "send() called on unconnected connection\n");
841                 errno = ENOTCONN;
842                 return -1;
843
844         case SYN_SENT:
845         case SYN_RECEIVED:
846         case ESTABLISHED:
847         case CLOSE_WAIT:
848                 break;
849
850         case FIN_WAIT_1:
851         case FIN_WAIT_2:
852         case CLOSING:
853         case LAST_ACK:
854         case TIME_WAIT:
855                 debug(c, "send() called on closed connection\n");
856                 errno = EPIPE;
857                 return -1;
858         }
859
860         // Exit early if we have nothing to send.
861
862         if(!len) {
863                 return 0;
864         }
865
866         if(!data) {
867                 errno = EFAULT;
868                 return -1;
869         }
870
871         // Check if we need to be able to buffer all data
872
873         if(c->flags & UTCP_NO_PARTIAL) {
874                 if(len > buffer_free(&c->sndbuf)) {
875                         if(len > c->sndbuf.maxsize) {
876                                 errno = EMSGSIZE;
877                                 return -1;
878                         } else {
879                                 errno = EWOULDBLOCK;
880                                 return 0;
881                         }
882                 }
883         }
884
885         // Add data to send buffer.
886
887         if(is_reliable(c)) {
888                 len = buffer_put(&c->sndbuf, data, len);
889         } else if(c->state != SYN_SENT && c->state != SYN_RECEIVED) {
890                 if(len > MAX_UNRELIABLE_SIZE || buffer_put(&c->sndbuf, data, len) != (ssize_t)len) {
891                         errno = EMSGSIZE;
892                         return -1;
893                 }
894         } else {
895                 return 0;
896         }
897
898         if(len <= 0) {
899                 if(is_reliable(c)) {
900                         errno = EWOULDBLOCK;
901                         return 0;
902                 } else {
903                         return len;
904                 }
905         }
906
907         c->snd.last += len;
908
909         // Don't send anything yet if the connection has not fully established yet
910
911         if(c->state == SYN_SENT || c->state == SYN_RECEIVED) {
912                 return len;
913         }
914
915         ack(c, false);
916
917         if(!is_reliable(c)) {
918                 c->snd.una = c->snd.nxt = c->snd.last;
919                 buffer_discard(&c->sndbuf, c->sndbuf.used);
920         }
921
922         if(is_reliable(c) && !timespec_isset(&c->rtrx_timeout)) {
923                 start_retransmit_timer(c);
924         }
925
926         if(is_reliable(c) && !timespec_isset(&c->conn_timeout)) {
927                 clock_gettime(UTCP_CLOCK, &c->conn_timeout);
928                 c->conn_timeout.tv_sec += c->utcp->timeout;
929         }
930
931         return len;
932 }
933
934 static void swap_ports(struct hdr *hdr) {
935         uint16_t tmp = hdr->src;
936         hdr->src = hdr->dst;
937         hdr->dst = tmp;
938 }
939
940 static void fast_retransmit(struct utcp_connection *c) {
941         if(c->state == CLOSED || c->snd.last == c->snd.una) {
942                 debug(c, "fast_retransmit() called but nothing to retransmit!\n");
943                 return;
944         }
945
946         struct utcp *utcp = c->utcp;
947
948         struct {
949                 struct hdr hdr;
950                 uint8_t data[];
951         } *pkt = c->utcp->pkt;
952
953         pkt->hdr.src = c->src;
954         pkt->hdr.dst = c->dst;
955         pkt->hdr.wnd = c->rcvbuf.maxsize;
956         pkt->hdr.aux = 0;
957
958         switch(c->state) {
959         case ESTABLISHED:
960         case FIN_WAIT_1:
961         case CLOSE_WAIT:
962         case CLOSING:
963         case LAST_ACK:
964                 // Send unacked data again.
965                 pkt->hdr.seq = c->snd.una;
966                 pkt->hdr.ack = c->rcv.nxt;
967                 pkt->hdr.ctl = ACK;
968                 uint32_t len = min(seqdiff(c->snd.last, c->snd.una), utcp->mss);
969
970                 if(fin_wanted(c, c->snd.una + len)) {
971                         len--;
972                         pkt->hdr.ctl |= FIN;
973                 }
974
975                 buffer_copy(&c->sndbuf, pkt->data, 0, len);
976                 print_packet(c, "rtrx", pkt, sizeof(pkt->hdr) + len);
977                 utcp->send(utcp, pkt, sizeof(pkt->hdr) + len);
978                 break;
979
980         default:
981                 break;
982         }
983 }
984
985 static void retransmit(struct utcp_connection *c) {
986         if(c->state == CLOSED || c->snd.last == c->snd.una) {
987                 debug(c, "retransmit() called but nothing to retransmit!\n");
988                 stop_retransmit_timer(c);
989                 return;
990         }
991
992         struct utcp *utcp = c->utcp;
993
994         if(utcp->retransmit) {
995                 utcp->retransmit(c);
996         }
997
998         struct {
999                 struct hdr hdr;
1000                 uint8_t data[];
1001         } *pkt = c->utcp->pkt;
1002
1003         pkt->hdr.src = c->src;
1004         pkt->hdr.dst = c->dst;
1005         pkt->hdr.wnd = c->rcvbuf.maxsize;
1006         pkt->hdr.aux = 0;
1007
1008         switch(c->state) {
1009         case SYN_SENT:
1010                 // Send our SYN again
1011                 pkt->hdr.seq = c->snd.iss;
1012                 pkt->hdr.ack = 0;
1013                 pkt->hdr.ctl = SYN;
1014                 pkt->hdr.aux = 0x0101;
1015                 pkt->data[0] = 1;
1016                 pkt->data[1] = 0;
1017                 pkt->data[2] = 0;
1018                 pkt->data[3] = c->flags & 0x7;
1019                 print_packet(c, "rtrx", pkt, sizeof(pkt->hdr) + 4);
1020                 utcp->send(utcp, pkt, sizeof(pkt->hdr) + 4);
1021                 break;
1022
1023         case SYN_RECEIVED:
1024                 // Send SYNACK again
1025                 pkt->hdr.seq = c->snd.nxt;
1026                 pkt->hdr.ack = c->rcv.nxt;
1027                 pkt->hdr.ctl = SYN | ACK;
1028                 print_packet(c, "rtrx", pkt, sizeof(pkt->hdr));
1029                 utcp->send(utcp, pkt, sizeof(pkt->hdr));
1030                 break;
1031
1032         case ESTABLISHED:
1033         case FIN_WAIT_1:
1034         case CLOSE_WAIT:
1035         case CLOSING:
1036         case LAST_ACK:
1037                 // Send unacked data again.
1038                 pkt->hdr.seq = c->snd.una;
1039                 pkt->hdr.ack = c->rcv.nxt;
1040                 pkt->hdr.ctl = ACK;
1041                 uint32_t len = min(seqdiff(c->snd.last, c->snd.una), utcp->mss);
1042
1043                 if(fin_wanted(c, c->snd.una + len)) {
1044                         len--;
1045                         pkt->hdr.ctl |= FIN;
1046                 }
1047
1048                 // RFC 5681 slow start after timeout
1049                 uint32_t flightsize = seqdiff(c->snd.nxt, c->snd.una);
1050                 c->snd.ssthresh = max(flightsize / 2, utcp->mss * 2); // eq. 4
1051                 c->snd.cwnd = utcp->mss;
1052                 debug_cwnd(c);
1053
1054                 buffer_copy(&c->sndbuf, pkt->data, 0, len);
1055                 print_packet(c, "rtrx", pkt, sizeof(pkt->hdr) + len);
1056                 utcp->send(utcp, pkt, sizeof(pkt->hdr) + len);
1057
1058                 c->snd.nxt = c->snd.una + len;
1059                 break;
1060
1061         case CLOSED:
1062         case LISTEN:
1063         case TIME_WAIT:
1064         case FIN_WAIT_2:
1065                 // We shouldn't need to retransmit anything in this state.
1066 #ifdef UTCP_DEBUG
1067                 abort();
1068 #endif
1069                 stop_retransmit_timer(c);
1070                 goto cleanup;
1071         }
1072
1073         start_retransmit_timer(c);
1074         c->rto *= 2;
1075
1076         if(c->rto > MAX_RTO) {
1077                 c->rto = MAX_RTO;
1078         }
1079
1080         c->rtt_start.tv_sec = 0; // invalidate RTT timer
1081         c->dupack = 0; // cancel any ongoing fast recovery
1082
1083 cleanup:
1084         return;
1085 }
1086
1087 /* Update receive buffer and SACK entries after consuming data.
1088  *
1089  * Situation:
1090  *
1091  * |.....0000..1111111111.....22222......3333|
1092  * |---------------^
1093  *
1094  * 0..3 represent the SACK entries. The ^ indicates up to which point we want
1095  * to remove data from the receive buffer. The idea is to substract "len"
1096  * from the offset of all the SACK entries, and then remove/cut down entries
1097  * that are shifted to before the start of the receive buffer.
1098  *
1099  * There are three cases:
1100  * - the SACK entry is after ^, in that case just change the offset.
1101  * - the SACK entry starts before and ends after ^, so we have to
1102  *   change both its offset and size.
1103  * - the SACK entry is completely before ^, in that case delete it.
1104  */
1105 static void sack_consume(struct utcp_connection *c, size_t len) {
1106         debug(c, "sack_consume %lu\n", (unsigned long)len);
1107
1108         if(len > c->rcvbuf.used) {
1109                 debug(c, "all SACK entries consumed\n");
1110                 c->sacks[0].len = 0;
1111                 return;
1112         }
1113
1114         buffer_discard(&c->rcvbuf, len);
1115
1116         for(int i = 0; i < NSACKS && c->sacks[i].len;) {
1117                 if(len < c->sacks[i].offset) {
1118                         c->sacks[i].offset -= len;
1119                         i++;
1120                 } else if(len < c->sacks[i].offset + c->sacks[i].len) {
1121                         c->sacks[i].len -= len - c->sacks[i].offset;
1122                         c->sacks[i].offset = 0;
1123                         i++;
1124                 } else {
1125                         if(i < NSACKS - 1) {
1126                                 memmove(&c->sacks[i], &c->sacks[i + 1], (NSACKS - 1 - i) * sizeof(c->sacks)[i]);
1127                                 c->sacks[NSACKS - 1].len = 0;
1128                         } else {
1129                                 c->sacks[i].len = 0;
1130                                 break;
1131                         }
1132                 }
1133         }
1134
1135         for(int i = 0; i < NSACKS && c->sacks[i].len; i++) {
1136                 debug(c, "SACK[%d] offset %u len %u\n", i, c->sacks[i].offset, c->sacks[i].len);
1137         }
1138 }
1139
1140 static void handle_out_of_order(struct utcp_connection *c, uint32_t offset, const void *data, size_t len) {
1141         debug(c, "out of order packet, offset %u\n", offset);
1142         // Packet loss or reordering occured. Store the data in the buffer.
1143         ssize_t rxd = buffer_put_at(&c->rcvbuf, offset, data, len);
1144
1145         if(rxd <= 0) {
1146                 debug(c, "packet outside receive buffer, dropping\n");
1147                 return;
1148         }
1149
1150         if((size_t)rxd < len) {
1151                 debug(c, "packet partially outside receive buffer\n");
1152                 len = rxd;
1153         }
1154
1155         // Make note of where we put it.
1156         for(int i = 0; i < NSACKS; i++) {
1157                 if(!c->sacks[i].len) { // nothing to merge, add new entry
1158                         debug(c, "new SACK entry %d\n", i);
1159                         c->sacks[i].offset = offset;
1160                         c->sacks[i].len = rxd;
1161                         break;
1162                 } else if(offset < c->sacks[i].offset) {
1163                         if(offset + rxd < c->sacks[i].offset) { // insert before
1164                                 if(!c->sacks[NSACKS - 1].len) { // only if room left
1165                                         debug(c, "insert SACK entry at %d\n", i);
1166                                         memmove(&c->sacks[i + 1], &c->sacks[i], (NSACKS - i - 1) * sizeof(c->sacks)[i]);
1167                                         c->sacks[i].offset = offset;
1168                                         c->sacks[i].len = rxd;
1169                                 } else {
1170                                         debug(c, "SACK entries full, dropping packet\n");
1171                                 }
1172
1173                                 break;
1174                         } else { // merge
1175                                 debug(c, "merge with start of SACK entry at %d\n", i);
1176                                 c->sacks[i].offset = offset;
1177                                 break;
1178                         }
1179                 } else if(offset <= c->sacks[i].offset + c->sacks[i].len) {
1180                         if(offset + rxd > c->sacks[i].offset + c->sacks[i].len) { // merge
1181                                 debug(c, "merge with end of SACK entry at %d\n", i);
1182                                 c->sacks[i].len = offset + rxd - c->sacks[i].offset;
1183                                 // TODO: handle potential merge with next entry
1184                         }
1185
1186                         break;
1187                 }
1188         }
1189
1190         for(int i = 0; i < NSACKS && c->sacks[i].len; i++) {
1191                 debug(c, "SACK[%d] offset %u len %u\n", i, c->sacks[i].offset, c->sacks[i].len);
1192         }
1193 }
1194
1195 static void handle_in_order(struct utcp_connection *c, const void *data, size_t len) {
1196         if(c->recv) {
1197                 ssize_t rxd = c->recv(c, data, len);
1198
1199                 if(rxd != (ssize_t)len) {
1200                         // TODO: handle the application not accepting all data.
1201                         abort();
1202                 }
1203         }
1204
1205         // Check if we can process out-of-order data now.
1206         if(c->sacks[0].len && len >= c->sacks[0].offset) {
1207                 debug(c, "incoming packet len %lu connected with SACK at %u\n", (unsigned long)len, c->sacks[0].offset);
1208
1209                 if(len < c->sacks[0].offset + c->sacks[0].len) {
1210                         size_t offset = len;
1211                         len = c->sacks[0].offset + c->sacks[0].len;
1212                         size_t remainder = len - offset;
1213
1214                         ssize_t rxd = buffer_call(c, &c->rcvbuf, offset, remainder);
1215
1216                         if(rxd != (ssize_t)remainder) {
1217                                 // TODO: handle the application not accepting all data.
1218                                 abort();
1219                         }
1220                 }
1221         }
1222
1223         if(c->rcvbuf.used) {
1224                 sack_consume(c, len);
1225         }
1226
1227         c->rcv.nxt += len;
1228 }
1229
1230 static void handle_unreliable(struct utcp_connection *c, const struct hdr *hdr, const void *data, size_t len) {
1231         // Fast path for unfragmented packets
1232         if(!hdr->wnd && !(hdr->ctl & MF)) {
1233                 if(c->recv) {
1234                         c->recv(c, data, len);
1235                 }
1236
1237                 c->rcv.nxt = hdr->seq + len;
1238                 return;
1239         }
1240
1241         // Ensure reassembled packet are not larger than 64 kiB
1242         if(hdr->wnd >= MAX_UNRELIABLE_SIZE || hdr->wnd + len > MAX_UNRELIABLE_SIZE) {
1243                 return;
1244         }
1245
1246         // Don't accept out of order fragments
1247         if(hdr->wnd && hdr->seq != c->rcv.nxt) {
1248                 return;
1249         }
1250
1251         // Reset the receive buffer for the first fragment
1252         if(!hdr->wnd) {
1253                 buffer_clear(&c->rcvbuf);
1254         }
1255
1256         ssize_t rxd = buffer_put_at(&c->rcvbuf, hdr->wnd, data, len);
1257
1258         if(rxd != (ssize_t)len) {
1259                 return;
1260         }
1261
1262         // Send the packet if it's the final fragment
1263         if(!(hdr->ctl & MF)) {
1264                 buffer_call(c, &c->rcvbuf, 0, hdr->wnd + len);
1265         }
1266
1267         c->rcv.nxt = hdr->seq + len;
1268 }
1269
1270 static void handle_incoming_data(struct utcp_connection *c, const struct hdr *hdr, const void *data, size_t len) {
1271         if(!is_reliable(c)) {
1272                 handle_unreliable(c, hdr, data, len);
1273                 return;
1274         }
1275
1276         uint32_t offset = seqdiff(hdr->seq, c->rcv.nxt);
1277
1278         if(offset) {
1279                 handle_out_of_order(c, offset, data, len);
1280         } else {
1281                 handle_in_order(c, data, len);
1282         }
1283 }
1284
1285
1286 ssize_t utcp_recv(struct utcp *utcp, const void *data, size_t len) {
1287         const uint8_t *ptr = data;
1288
1289         if(!utcp) {
1290                 errno = EFAULT;
1291                 return -1;
1292         }
1293
1294         if(!len) {
1295                 return 0;
1296         }
1297
1298         if(!data) {
1299                 errno = EFAULT;
1300                 return -1;
1301         }
1302
1303         // Drop packets smaller than the header
1304
1305         struct hdr hdr;
1306
1307         if(len < sizeof(hdr)) {
1308                 print_packet(NULL, "recv", data, len);
1309                 errno = EBADMSG;
1310                 return -1;
1311         }
1312
1313         // Make a copy from the potentially unaligned data to a struct hdr
1314
1315         memcpy(&hdr, ptr, sizeof(hdr));
1316
1317         // Try to match the packet to an existing connection
1318
1319         struct utcp_connection *c = find_connection(utcp, hdr.dst, hdr.src);
1320         print_packet(c, "recv", data, len);
1321
1322         // Process the header
1323
1324         ptr += sizeof(hdr);
1325         len -= sizeof(hdr);
1326
1327         // Drop packets with an unknown CTL flag
1328
1329         if(hdr.ctl & ~(SYN | ACK | RST | FIN | MF)) {
1330                 print_packet(NULL, "recv", data, len);
1331                 errno = EBADMSG;
1332                 return -1;
1333         }
1334
1335         // Check for auxiliary headers
1336
1337         const uint8_t *init = NULL;
1338
1339         uint16_t aux = hdr.aux;
1340
1341         while(aux) {
1342                 size_t auxlen = 4 * (aux >> 8) & 0xf;
1343                 uint8_t auxtype = aux & 0xff;
1344
1345                 if(len < auxlen) {
1346                         errno = EBADMSG;
1347                         return -1;
1348                 }
1349
1350                 switch(auxtype) {
1351                 case AUX_INIT:
1352                         if(!(hdr.ctl & SYN) || auxlen != 4) {
1353                                 errno = EBADMSG;
1354                                 return -1;
1355                         }
1356
1357                         init = ptr;
1358                         break;
1359
1360                 default:
1361                         errno = EBADMSG;
1362                         return -1;
1363                 }
1364
1365                 len -= auxlen;
1366                 ptr += auxlen;
1367
1368                 if(!(aux & 0x800)) {
1369                         break;
1370                 }
1371
1372                 if(len < 2) {
1373                         errno = EBADMSG;
1374                         return -1;
1375                 }
1376
1377                 memcpy(&aux, ptr, 2);
1378                 len -= 2;
1379                 ptr += 2;
1380         }
1381
1382         bool has_data = len || (hdr.ctl & (SYN | FIN));
1383
1384         // Is it for a new connection?
1385
1386         if(!c) {
1387                 // Ignore RST packets
1388
1389                 if(hdr.ctl & RST) {
1390                         return 0;
1391                 }
1392
1393                 // Is it a SYN packet and are we LISTENing?
1394
1395                 if(hdr.ctl & SYN && !(hdr.ctl & ACK) && utcp->accept) {
1396                         // If we don't want to accept it, send a RST back
1397                         if((utcp->listen && !utcp->listen(utcp, hdr.dst))) {
1398                                 len = 1;
1399                                 goto reset;
1400                         }
1401
1402                         // Try to allocate memory, otherwise send a RST back
1403                         c = allocate_connection(utcp, hdr.dst, hdr.src);
1404
1405                         if(!c) {
1406                                 len = 1;
1407                                 goto reset;
1408                         }
1409
1410                         // Parse auxilliary information
1411                         if(init) {
1412                                 if(init[0] < 1) {
1413                                         len = 1;
1414                                         goto reset;
1415                                 }
1416
1417                                 c->flags = init[3] & 0x7;
1418                         } else {
1419                                 c->flags = UTCP_TCP;
1420                         }
1421
1422 synack:
1423                         // Return SYN+ACK, go to SYN_RECEIVED state
1424                         c->snd.wnd = hdr.wnd;
1425                         c->rcv.irs = hdr.seq;
1426                         c->rcv.nxt = c->rcv.irs + 1;
1427                         set_state(c, SYN_RECEIVED);
1428
1429                         struct {
1430                                 struct hdr hdr;
1431                                 uint8_t data[4];
1432                         } pkt;
1433
1434                         pkt.hdr.src = c->src;
1435                         pkt.hdr.dst = c->dst;
1436                         pkt.hdr.ack = c->rcv.irs + 1;
1437                         pkt.hdr.seq = c->snd.iss;
1438                         pkt.hdr.wnd = c->rcvbuf.maxsize;
1439                         pkt.hdr.ctl = SYN | ACK;
1440
1441                         if(init) {
1442                                 pkt.hdr.aux = 0x0101;
1443                                 pkt.data[0] = 1;
1444                                 pkt.data[1] = 0;
1445                                 pkt.data[2] = 0;
1446                                 pkt.data[3] = c->flags & 0x7;
1447                                 print_packet(c, "send", &pkt, sizeof(hdr) + 4);
1448                                 utcp->send(utcp, &pkt, sizeof(hdr) + 4);
1449                         } else {
1450                                 pkt.hdr.aux = 0;
1451                                 print_packet(c, "send", &pkt, sizeof(hdr));
1452                                 utcp->send(utcp, &pkt, sizeof(hdr));
1453                         }
1454
1455                         start_retransmit_timer(c);
1456                 } else {
1457                         // No, we don't want your packets, send a RST back
1458                         len = 1;
1459                         goto reset;
1460                 }
1461
1462                 return 0;
1463         }
1464
1465         debug(c, "state %s\n", strstate[c->state]);
1466
1467         // In case this is for a CLOSED connection, ignore the packet.
1468         // TODO: make it so incoming packets can never match a CLOSED connection.
1469
1470         if(c->state == CLOSED) {
1471                 debug(c, "got packet for closed connection\n");
1472                 goto reset;
1473         }
1474
1475         // It is for an existing connection.
1476
1477         // 1. Drop invalid packets.
1478
1479         // 1a. Drop packets that should not happen in our current state.
1480
1481         switch(c->state) {
1482         case SYN_SENT:
1483         case SYN_RECEIVED:
1484         case ESTABLISHED:
1485         case FIN_WAIT_1:
1486         case FIN_WAIT_2:
1487         case CLOSE_WAIT:
1488         case CLOSING:
1489         case LAST_ACK:
1490         case TIME_WAIT:
1491                 break;
1492
1493         default:
1494 #ifdef UTCP_DEBUG
1495                 abort();
1496 #endif
1497                 break;
1498         }
1499
1500         // 1b. Discard data that is not in our receive window.
1501
1502         if(is_reliable(c)) {
1503                 bool acceptable;
1504
1505                 if(c->state == SYN_SENT) {
1506                         acceptable = true;
1507                 } else if(len == 0) {
1508                         acceptable = seqdiff(hdr.seq, c->rcv.nxt) >= 0;
1509                 } else {
1510                         int32_t rcv_offset = seqdiff(hdr.seq, c->rcv.nxt);
1511
1512                         // cut already accepted front overlapping
1513                         if(rcv_offset < 0) {
1514                                 acceptable = len > (size_t) - rcv_offset;
1515
1516                                 if(acceptable) {
1517                                         ptr -= rcv_offset;
1518                                         len += rcv_offset;
1519                                         hdr.seq -= rcv_offset;
1520                                 }
1521                         } else {
1522                                 acceptable = seqdiff(hdr.seq, c->rcv.nxt) >= 0 && seqdiff(hdr.seq, c->rcv.nxt) + len <= c->rcvbuf.maxsize;
1523                         }
1524                 }
1525
1526                 if(!acceptable) {
1527                         debug(c, "packet not acceptable, %u <= %u + %lu < %u\n", c->rcv.nxt, hdr.seq, (unsigned long)len, c->rcv.nxt + c->rcvbuf.maxsize);
1528
1529                         // Ignore unacceptable RST packets.
1530                         if(hdr.ctl & RST) {
1531                                 return 0;
1532                         }
1533
1534                         // Otherwise, continue processing.
1535                         len = 0;
1536                 }
1537         } else {
1538 #if UTCP_DEBUG
1539                 int32_t rcv_offset = seqdiff(hdr.seq, c->rcv.nxt);
1540
1541                 if(rcv_offset) {
1542                         debug(c, "packet out of order, offset %u bytes", rcv_offset);
1543                 }
1544
1545 #endif
1546         }
1547
1548         c->snd.wnd = hdr.wnd; // TODO: move below
1549
1550         // 1c. Drop packets with an invalid ACK.
1551         // ackno should not roll back, and it should also not be bigger than what we ever could have sent
1552         // (= snd.una + c->sndbuf.used).
1553
1554         if(!is_reliable(c)) {
1555                 if(hdr.ack != c->snd.last && c->state >= ESTABLISHED) {
1556                         hdr.ack = c->snd.una;
1557                 }
1558         }
1559
1560         // 2. Handle RST packets
1561
1562         if(hdr.ctl & RST) {
1563                 switch(c->state) {
1564                 case SYN_SENT:
1565                         if(!(hdr.ctl & ACK)) {
1566                                 return 0;
1567                         }
1568
1569                         // The peer has refused our connection.
1570                         set_state(c, CLOSED);
1571                         errno = ECONNREFUSED;
1572
1573                         if(c->recv) {
1574                                 c->recv(c, NULL, 0);
1575                         }
1576
1577                         if(c->poll && !c->reapable) {
1578                                 c->poll(c, 0);
1579                         }
1580
1581                         return 0;
1582
1583                 case SYN_RECEIVED:
1584                         if(hdr.ctl & ACK) {
1585                                 return 0;
1586                         }
1587
1588                         // We haven't told the application about this connection yet. Silently delete.
1589                         free_connection(c);
1590                         return 0;
1591
1592                 case ESTABLISHED:
1593                 case FIN_WAIT_1:
1594                 case FIN_WAIT_2:
1595                 case CLOSE_WAIT:
1596                         if(hdr.ctl & ACK) {
1597                                 return 0;
1598                         }
1599
1600                         // The peer has aborted our connection.
1601                         set_state(c, CLOSED);
1602                         errno = ECONNRESET;
1603
1604                         if(c->recv) {
1605                                 c->recv(c, NULL, 0);
1606                         }
1607
1608                         if(c->poll && !c->reapable) {
1609                                 c->poll(c, 0);
1610                         }
1611
1612                         return 0;
1613
1614                 case CLOSING:
1615                 case LAST_ACK:
1616                 case TIME_WAIT:
1617                         if(hdr.ctl & ACK) {
1618                                 return 0;
1619                         }
1620
1621                         // As far as the application is concerned, the connection has already been closed.
1622                         // If it has called utcp_close() already, we can immediately free this connection.
1623                         if(c->reapable) {
1624                                 free_connection(c);
1625                                 return 0;
1626                         }
1627
1628                         // Otherwise, immediately move to the CLOSED state.
1629                         set_state(c, CLOSED);
1630                         return 0;
1631
1632                 default:
1633 #ifdef UTCP_DEBUG
1634                         abort();
1635 #endif
1636                         break;
1637                 }
1638         }
1639
1640         uint32_t advanced;
1641
1642         if(!(hdr.ctl & ACK)) {
1643                 advanced = 0;
1644                 goto skip_ack;
1645         }
1646
1647         // 3. Advance snd.una
1648
1649         if(seqdiff(hdr.ack, c->snd.last) > 0 || seqdiff(hdr.ack, c->snd.una) < 0) {
1650                 debug(c, "packet ack seqno out of range, %u <= %u < %u\n", c->snd.una, hdr.ack, c->snd.una + c->sndbuf.used);
1651                 goto reset;
1652         }
1653
1654         advanced = seqdiff(hdr.ack, c->snd.una);
1655
1656         if(advanced) {
1657                 // RTT measurement
1658                 if(c->rtt_start.tv_sec) {
1659                         if(c->rtt_seq == hdr.ack) {
1660                                 struct timespec now;
1661                                 clock_gettime(UTCP_CLOCK, &now);
1662                                 int32_t diff = timespec_diff_usec(&now, &c->rtt_start);
1663                                 update_rtt(c, diff);
1664                                 c->rtt_start.tv_sec = 0;
1665                         } else if(c->rtt_seq < hdr.ack) {
1666                                 debug(c, "cancelling RTT measurement: %u < %u\n", c->rtt_seq, hdr.ack);
1667                                 c->rtt_start.tv_sec = 0;
1668                         }
1669                 }
1670
1671                 int32_t data_acked = advanced;
1672
1673                 switch(c->state) {
1674                 case SYN_SENT:
1675                 case SYN_RECEIVED:
1676                         data_acked--;
1677                         break;
1678
1679                 // TODO: handle FIN as well.
1680                 default:
1681                         break;
1682                 }
1683
1684                 assert(data_acked >= 0);
1685
1686 #ifndef NDEBUG
1687                 int32_t bufused = seqdiff(c->snd.last, c->snd.una);
1688                 assert(data_acked <= bufused);
1689 #endif
1690
1691                 if(data_acked) {
1692                         buffer_discard(&c->sndbuf, data_acked);
1693
1694                         if(is_reliable(c)) {
1695                                 c->do_poll = true;
1696                         }
1697                 }
1698
1699                 // Also advance snd.nxt if possible
1700                 if(seqdiff(c->snd.nxt, hdr.ack) < 0) {
1701                         c->snd.nxt = hdr.ack;
1702                 }
1703
1704                 c->snd.una = hdr.ack;
1705
1706                 if(c->dupack) {
1707                         if(c->dupack >= 3) {
1708                                 debug(c, "fast recovery ended\n");
1709                                 c->snd.cwnd = c->snd.ssthresh;
1710                         }
1711
1712                         c->dupack = 0;
1713                 }
1714
1715                 // Increase the congestion window according to RFC 5681
1716                 if(c->snd.cwnd < c->snd.ssthresh) {
1717                         c->snd.cwnd += min(advanced, utcp->mss); // eq. 2
1718                 } else {
1719                         c->snd.cwnd += max(1, (utcp->mss * utcp->mss) / c->snd.cwnd); // eq. 3
1720                 }
1721
1722                 if(c->snd.cwnd > c->sndbuf.maxsize) {
1723                         c->snd.cwnd = c->sndbuf.maxsize;
1724                 }
1725
1726                 debug_cwnd(c);
1727
1728                 // Check if we have sent a FIN that is now ACKed.
1729                 switch(c->state) {
1730                 case FIN_WAIT_1:
1731                         if(c->snd.una == c->snd.last) {
1732                                 set_state(c, FIN_WAIT_2);
1733                         }
1734
1735                         break;
1736
1737                 case CLOSING:
1738                         if(c->snd.una == c->snd.last) {
1739                                 clock_gettime(UTCP_CLOCK, &c->conn_timeout);
1740                                 c->conn_timeout.tv_sec += utcp->timeout;
1741                                 set_state(c, TIME_WAIT);
1742                         }
1743
1744                         break;
1745
1746                 default:
1747                         break;
1748                 }
1749         } else {
1750                 if(!len && is_reliable(c) && c->snd.una != c->snd.last) {
1751                         c->dupack++;
1752                         debug(c, "duplicate ACK %d\n", c->dupack);
1753
1754                         if(c->dupack == 3) {
1755                                 // RFC 5681 fast recovery
1756                                 debug(c, "fast recovery started\n", c->dupack);
1757                                 uint32_t flightsize = seqdiff(c->snd.nxt, c->snd.una);
1758                                 c->snd.ssthresh = max(flightsize / 2, utcp->mss * 2); // eq. 4
1759                                 c->snd.cwnd = min(c->snd.ssthresh + 3 * utcp->mss, c->sndbuf.maxsize);
1760
1761                                 if(c->snd.cwnd > c->sndbuf.maxsize) {
1762                                         c->snd.cwnd = c->sndbuf.maxsize;
1763                                 }
1764
1765                                 debug_cwnd(c);
1766
1767                                 fast_retransmit(c);
1768                         } else if(c->dupack > 3) {
1769                                 c->snd.cwnd += utcp->mss;
1770
1771                                 if(c->snd.cwnd > c->sndbuf.maxsize) {
1772                                         c->snd.cwnd = c->sndbuf.maxsize;
1773                                 }
1774
1775                                 debug_cwnd(c);
1776                         }
1777
1778                         // We got an ACK which indicates the other side did get one of our packets.
1779                         // Reset the retransmission timer to avoid going to slow start,
1780                         // but don't touch the connection timeout.
1781                         start_retransmit_timer(c);
1782                 }
1783         }
1784
1785         // 4. Update timers
1786
1787         if(advanced) {
1788                 if(c->snd.una == c->snd.last) {
1789                         stop_retransmit_timer(c);
1790                         timespec_clear(&c->conn_timeout);
1791                 } else if(is_reliable(c)) {
1792                         start_retransmit_timer(c);
1793                         clock_gettime(UTCP_CLOCK, &c->conn_timeout);
1794                         c->conn_timeout.tv_sec += utcp->timeout;
1795                 }
1796         }
1797
1798 skip_ack:
1799         // 5. Process SYN stuff
1800
1801         if(hdr.ctl & SYN) {
1802                 switch(c->state) {
1803                 case SYN_SENT:
1804
1805                         // This is a SYNACK. It should always have ACKed the SYN.
1806                         if(!advanced) {
1807                                 goto reset;
1808                         }
1809
1810                         c->rcv.irs = hdr.seq;
1811                         c->rcv.nxt = hdr.seq + 1;
1812
1813                         if(c->shut_wr) {
1814                                 c->snd.last++;
1815                                 set_state(c, FIN_WAIT_1);
1816                         } else {
1817                                 c->do_poll = true;
1818                                 set_state(c, ESTABLISHED);
1819                         }
1820
1821                         break;
1822
1823                 case SYN_RECEIVED:
1824                         // This is a retransmit of a SYN, send back the SYNACK.
1825                         goto synack;
1826
1827                 case ESTABLISHED:
1828                 case FIN_WAIT_1:
1829                 case FIN_WAIT_2:
1830                 case CLOSE_WAIT:
1831                 case CLOSING:
1832                 case LAST_ACK:
1833                 case TIME_WAIT:
1834                         // This could be a retransmission. Ignore the SYN flag, but send an ACK back.
1835                         break;
1836
1837                 default:
1838 #ifdef UTCP_DEBUG
1839                         abort();
1840 #endif
1841                         return 0;
1842                 }
1843         }
1844
1845         // 6. Process new data
1846
1847         if(c->state == SYN_RECEIVED) {
1848                 // This is the ACK after the SYNACK. It should always have ACKed the SYNACK.
1849                 if(!advanced) {
1850                         goto reset;
1851                 }
1852
1853                 // Are we still LISTENing?
1854                 if(utcp->accept) {
1855                         utcp->accept(c, c->src);
1856                 }
1857
1858                 if(c->state != ESTABLISHED) {
1859                         set_state(c, CLOSED);
1860                         c->reapable = true;
1861                         goto reset;
1862                 }
1863         }
1864
1865         if(len) {
1866                 switch(c->state) {
1867                 case SYN_SENT:
1868                 case SYN_RECEIVED:
1869                         // This should never happen.
1870 #ifdef UTCP_DEBUG
1871                         abort();
1872 #endif
1873                         return 0;
1874
1875                 case ESTABLISHED:
1876                         break;
1877
1878                 case FIN_WAIT_1:
1879                 case FIN_WAIT_2:
1880                         if(c->reapable) {
1881                                 // We already closed the connection and are not interested in more data.
1882                                 goto reset;
1883                         }
1884
1885                         break;
1886
1887                 case CLOSE_WAIT:
1888                 case CLOSING:
1889                 case LAST_ACK:
1890                 case TIME_WAIT:
1891                         // Ehm no, We should never receive more data after a FIN.
1892                         goto reset;
1893
1894                 default:
1895 #ifdef UTCP_DEBUG
1896                         abort();
1897 #endif
1898                         return 0;
1899                 }
1900
1901                 handle_incoming_data(c, &hdr, ptr, len);
1902         }
1903
1904         // 7. Process FIN stuff
1905
1906         if((hdr.ctl & FIN) && (!is_reliable(c) || hdr.seq + len == c->rcv.nxt)) {
1907                 switch(c->state) {
1908                 case SYN_SENT:
1909                 case SYN_RECEIVED:
1910                         // This should never happen.
1911 #ifdef UTCP_DEBUG
1912                         abort();
1913 #endif
1914                         break;
1915
1916                 case ESTABLISHED:
1917                         set_state(c, CLOSE_WAIT);
1918                         break;
1919
1920                 case FIN_WAIT_1:
1921                         set_state(c, CLOSING);
1922                         break;
1923
1924                 case FIN_WAIT_2:
1925                         clock_gettime(UTCP_CLOCK, &c->conn_timeout);
1926                         c->conn_timeout.tv_sec += utcp->timeout;
1927                         set_state(c, TIME_WAIT);
1928                         break;
1929
1930                 case CLOSE_WAIT:
1931                 case CLOSING:
1932                 case LAST_ACK:
1933                 case TIME_WAIT:
1934                         // Ehm, no. We should never receive a second FIN.
1935                         goto reset;
1936
1937                 default:
1938 #ifdef UTCP_DEBUG
1939                         abort();
1940 #endif
1941                         break;
1942                 }
1943
1944                 // FIN counts as one sequence number
1945                 c->rcv.nxt++;
1946                 len++;
1947
1948                 // Inform the application that the peer closed its end of the connection.
1949                 if(c->recv) {
1950                         errno = 0;
1951                         c->recv(c, NULL, 0);
1952                 }
1953         }
1954
1955         // Now we send something back if:
1956         // - we received data, so we have to send back an ACK
1957         //   -> sendatleastone = true
1958         // - or we got an ack, so we should maybe send a bit more data
1959         //   -> sendatleastone = false
1960
1961         if(is_reliable(c) || hdr.ctl & SYN || hdr.ctl & FIN) {
1962                 ack(c, has_data);
1963         }
1964
1965         return 0;
1966
1967 reset:
1968         swap_ports(&hdr);
1969         hdr.wnd = 0;
1970         hdr.aux = 0;
1971
1972         if(hdr.ctl & ACK) {
1973                 hdr.seq = hdr.ack;
1974                 hdr.ctl = RST;
1975         } else {
1976                 hdr.ack = hdr.seq + len;
1977                 hdr.seq = 0;
1978                 hdr.ctl = RST | ACK;
1979         }
1980
1981         print_packet(c, "send", &hdr, sizeof(hdr));
1982         utcp->send(utcp, &hdr, sizeof(hdr));
1983         return 0;
1984
1985 }
1986
1987 int utcp_shutdown(struct utcp_connection *c, int dir) {
1988         debug(c, "shutdown %d at %u\n", dir, c ? c->snd.last : 0);
1989
1990         if(!c) {
1991                 errno = EFAULT;
1992                 return -1;
1993         }
1994
1995         if(c->reapable) {
1996                 debug(c, "shutdown() called on closed connection\n");
1997                 errno = EBADF;
1998                 return -1;
1999         }
2000
2001         if(!(dir == UTCP_SHUT_RD || dir == UTCP_SHUT_WR || dir == UTCP_SHUT_RDWR)) {
2002                 errno = EINVAL;
2003                 return -1;
2004         }
2005
2006         // TCP does not have a provision for stopping incoming packets.
2007         // The best we can do is to just ignore them.
2008         if(dir == UTCP_SHUT_RD || dir == UTCP_SHUT_RDWR) {
2009                 c->recv = NULL;
2010         }
2011
2012         // The rest of the code deals with shutting down writes.
2013         if(dir == UTCP_SHUT_RD) {
2014                 return 0;
2015         }
2016
2017         // Only process shutting down writes once.
2018         if(c->shut_wr) {
2019                 return 0;
2020         }
2021
2022         c->shut_wr = true;
2023
2024         switch(c->state) {
2025         case CLOSED:
2026         case LISTEN:
2027                 errno = ENOTCONN;
2028                 return -1;
2029
2030         case SYN_SENT:
2031                 return 0;
2032
2033         case SYN_RECEIVED:
2034         case ESTABLISHED:
2035                 set_state(c, FIN_WAIT_1);
2036                 break;
2037
2038         case FIN_WAIT_1:
2039         case FIN_WAIT_2:
2040                 return 0;
2041
2042         case CLOSE_WAIT:
2043                 set_state(c, CLOSING);
2044                 break;
2045
2046         case CLOSING:
2047         case LAST_ACK:
2048         case TIME_WAIT:
2049                 return 0;
2050         }
2051
2052         c->snd.last++;
2053
2054         ack(c, false);
2055
2056         if(!timespec_isset(&c->rtrx_timeout)) {
2057                 start_retransmit_timer(c);
2058         }
2059
2060         return 0;
2061 }
2062
2063 static bool reset_connection(struct utcp_connection *c) {
2064         if(!c) {
2065                 errno = EFAULT;
2066                 return false;
2067         }
2068
2069         if(c->reapable) {
2070                 debug(c, "abort() called on closed connection\n");
2071                 errno = EBADF;
2072                 return false;
2073         }
2074
2075         buffer_clear(&c->sndbuf);
2076         buffer_clear(&c->rcvbuf);
2077
2078         c->recv = NULL;
2079         c->poll = NULL;
2080
2081         switch(c->state) {
2082         case CLOSED:
2083                 return true;
2084
2085         case LISTEN:
2086         case SYN_SENT:
2087         case CLOSING:
2088         case LAST_ACK:
2089         case TIME_WAIT:
2090                 set_state(c, CLOSED);
2091                 return true;
2092
2093         case SYN_RECEIVED:
2094         case ESTABLISHED:
2095         case FIN_WAIT_1:
2096         case FIN_WAIT_2:
2097         case CLOSE_WAIT:
2098                 set_state(c, CLOSED);
2099                 break;
2100         }
2101
2102         // Send RST
2103
2104         struct hdr hdr;
2105
2106         hdr.src = c->src;
2107         hdr.dst = c->dst;
2108         hdr.seq = c->snd.nxt;
2109         hdr.ack = c->rcv.nxt;
2110         hdr.wnd = 0;
2111         hdr.ctl = RST;
2112         hdr.aux = 0;
2113
2114         print_packet(c, "send", &hdr, sizeof(hdr));
2115         c->utcp->send(c->utcp, &hdr, sizeof(hdr));
2116         return true;
2117 }
2118
2119 static void set_reapable(struct utcp_connection *c) {
2120         set_buffer_storage(&c->sndbuf, NULL, min(c->sndbuf.maxsize, DEFAULT_MAXSNDBUFSIZE));
2121         set_buffer_storage(&c->rcvbuf, NULL, min(c->rcvbuf.maxsize, DEFAULT_MAXRCVBUFSIZE));
2122
2123         c->recv = NULL;
2124         c->poll = NULL;
2125         c->reapable = true;
2126 }
2127
2128 // Closes all the opened connections
2129 void utcp_abort_all_connections(struct utcp *utcp) {
2130         if(!utcp) {
2131                 errno = EINVAL;
2132                 return;
2133         }
2134
2135         for(int i = 0; i < utcp->nconnections; i++) {
2136                 struct utcp_connection *c = utcp->connections[i];
2137
2138                 if(c->reapable || c->state == CLOSED) {
2139                         continue;
2140                 }
2141
2142                 utcp_recv_t old_recv = c->recv;
2143                 utcp_poll_t old_poll = c->poll;
2144
2145                 utcp_abort(c);
2146
2147                 if(old_recv) {
2148                         errno = 0;
2149                         old_recv(c, NULL, 0);
2150                 }
2151
2152                 if(old_poll && !c->reapable) {
2153                         errno = 0;
2154                         old_poll(c, 0);
2155                 }
2156         }
2157
2158         return;
2159 }
2160
2161 int utcp_close(struct utcp_connection *c) {
2162         if(utcp_shutdown(c, SHUT_RDWR) && errno != ENOTCONN) {
2163                 return -1;
2164         }
2165
2166         set_reapable(c);
2167         return 0;
2168 }
2169
2170 int utcp_abort(struct utcp_connection *c) {
2171         if(!reset_connection(c)) {
2172                 return -1;
2173         }
2174
2175         set_reapable(c);
2176         return 0;
2177 }
2178
2179 /* Handle timeouts.
2180  * One call to this function will loop through all connections,
2181  * checking if something needs to be resent or not.
2182  * The return value is the time to the next timeout in milliseconds,
2183  * or maybe a negative value if the timeout is infinite.
2184  */
2185 struct timespec utcp_timeout(struct utcp *utcp) {
2186         struct timespec now;
2187         clock_gettime(UTCP_CLOCK, &now);
2188         struct timespec next = {now.tv_sec + 3600, now.tv_nsec};
2189
2190         for(int i = 0; i < utcp->nconnections; i++) {
2191                 struct utcp_connection *c = utcp->connections[i];
2192
2193                 if(!c) {
2194                         continue;
2195                 }
2196
2197                 // delete connections that have been utcp_close()d.
2198                 if(c->state == CLOSED) {
2199                         if(c->reapable) {
2200                                 debug(c, "reaping\n");
2201                                 free_connection(c);
2202                                 i--;
2203                         }
2204
2205                         continue;
2206                 }
2207
2208                 if(timespec_isset(&c->conn_timeout) && timespec_lt(&c->conn_timeout, &now)) {
2209                         errno = ETIMEDOUT;
2210                         c->state = CLOSED;
2211
2212                         if(c->recv) {
2213                                 c->recv(c, NULL, 0);
2214                         }
2215
2216                         if(c->poll && !c->reapable) {
2217                                 c->poll(c, 0);
2218                         }
2219
2220                         continue;
2221                 }
2222
2223                 if(timespec_isset(&c->rtrx_timeout) && timespec_lt(&c->rtrx_timeout, &now)) {
2224                         debug(c, "retransmitting after timeout\n");
2225                         retransmit(c);
2226                 }
2227
2228                 if(c->poll) {
2229                         if((c->state == ESTABLISHED || c->state == CLOSE_WAIT) && c->do_poll) {
2230                                 c->do_poll = false;
2231                                 uint32_t len = buffer_free(&c->sndbuf);
2232
2233                                 if(len) {
2234                                         c->poll(c, len);
2235                                 }
2236                         } else if(c->state == CLOSED) {
2237                                 c->poll(c, 0);
2238                         }
2239                 }
2240
2241                 if(timespec_isset(&c->conn_timeout) && timespec_lt(&c->conn_timeout, &next)) {
2242                         next = c->conn_timeout;
2243                 }
2244
2245                 if(timespec_isset(&c->rtrx_timeout) && timespec_lt(&c->rtrx_timeout, &next)) {
2246                         next = c->rtrx_timeout;
2247                 }
2248         }
2249
2250         struct timespec diff;
2251
2252         timespec_sub(&next, &now, &diff);
2253
2254         return diff;
2255 }
2256
2257 bool utcp_is_active(struct utcp *utcp) {
2258         if(!utcp) {
2259                 return false;
2260         }
2261
2262         for(int i = 0; i < utcp->nconnections; i++)
2263                 if(utcp->connections[i]->state != CLOSED && utcp->connections[i]->state != TIME_WAIT) {
2264                         return true;
2265                 }
2266
2267         return false;
2268 }
2269
2270 struct utcp *utcp_init(utcp_accept_t accept, utcp_listen_t listen, utcp_send_t send, void *priv) {
2271         if(!send) {
2272                 errno = EFAULT;
2273                 return NULL;
2274         }
2275
2276         struct utcp *utcp = calloc(1, sizeof(*utcp));
2277
2278         if(!utcp) {
2279                 return NULL;
2280         }
2281
2282         utcp_set_mtu(utcp, DEFAULT_MTU);
2283
2284         if(!utcp->pkt) {
2285                 free(utcp);
2286                 return NULL;
2287         }
2288
2289         if(!CLOCK_GRANULARITY) {
2290                 struct timespec res;
2291                 clock_getres(UTCP_CLOCK, &res);
2292                 CLOCK_GRANULARITY = res.tv_sec * USEC_PER_SEC + res.tv_nsec / 1000;
2293         }
2294
2295         utcp->accept = accept;
2296         utcp->listen = listen;
2297         utcp->send = send;
2298         utcp->priv = priv;
2299         utcp->timeout = DEFAULT_USER_TIMEOUT; // sec
2300
2301         return utcp;
2302 }
2303
2304 void utcp_exit(struct utcp *utcp) {
2305         if(!utcp) {
2306                 return;
2307         }
2308
2309         for(int i = 0; i < utcp->nconnections; i++) {
2310                 struct utcp_connection *c = utcp->connections[i];
2311
2312                 if(!c->reapable) {
2313                         if(c->recv) {
2314                                 c->recv(c, NULL, 0);
2315                         }
2316
2317                         if(c->poll && !c->reapable) {
2318                                 c->poll(c, 0);
2319                         }
2320                 }
2321
2322                 buffer_exit(&c->rcvbuf);
2323                 buffer_exit(&c->sndbuf);
2324                 free(c);
2325         }
2326
2327         free(utcp->connections);
2328         free(utcp->pkt);
2329         free(utcp);
2330 }
2331
2332 uint16_t utcp_get_mtu(struct utcp *utcp) {
2333         return utcp ? utcp->mtu : 0;
2334 }
2335
2336 uint16_t utcp_get_mss(struct utcp *utcp) {
2337         return utcp ? utcp->mss : 0;
2338 }
2339
2340 void utcp_set_mtu(struct utcp *utcp, uint16_t mtu) {
2341         if(!utcp) {
2342                 return;
2343         }
2344
2345         if(mtu <= sizeof(struct hdr)) {
2346                 return;
2347         }
2348
2349         if(mtu > utcp->mtu) {
2350                 char *new = realloc(utcp->pkt, mtu + sizeof(struct hdr));
2351
2352                 if(!new) {
2353                         return;
2354                 }
2355
2356                 utcp->pkt = new;
2357         }
2358
2359         utcp->mtu = mtu;
2360         utcp->mss = mtu - sizeof(struct hdr);
2361 }
2362
2363 void utcp_reset_timers(struct utcp *utcp) {
2364         if(!utcp) {
2365                 return;
2366         }
2367
2368         struct timespec now, then;
2369
2370         clock_gettime(UTCP_CLOCK, &now);
2371
2372         then = now;
2373
2374         then.tv_sec += utcp->timeout;
2375
2376         for(int i = 0; i < utcp->nconnections; i++) {
2377                 struct utcp_connection *c = utcp->connections[i];
2378
2379                 if(c->reapable) {
2380                         continue;
2381                 }
2382
2383                 if(timespec_isset(&c->rtrx_timeout)) {
2384                         c->rtrx_timeout = now;
2385                 }
2386
2387                 if(timespec_isset(&c->conn_timeout)) {
2388                         c->conn_timeout = then;
2389                 }
2390
2391                 c->rtt_start.tv_sec = 0;
2392
2393                 if(c->rto > START_RTO) {
2394                         c->rto = START_RTO;
2395                 }
2396         }
2397 }
2398
2399 int utcp_get_user_timeout(struct utcp *u) {
2400         return u ? u->timeout : 0;
2401 }
2402
2403 void utcp_set_user_timeout(struct utcp *u, int timeout) {
2404         if(u) {
2405                 u->timeout = timeout;
2406         }
2407 }
2408
2409 size_t utcp_get_sndbuf(struct utcp_connection *c) {
2410         return c ? c->sndbuf.maxsize : 0;
2411 }
2412
2413 size_t utcp_get_sndbuf_free(struct utcp_connection *c) {
2414         if(!c) {
2415                 return 0;
2416         }
2417
2418         switch(c->state) {
2419         case SYN_SENT:
2420         case SYN_RECEIVED:
2421         case ESTABLISHED:
2422         case CLOSE_WAIT:
2423                 return buffer_free(&c->sndbuf);
2424
2425         default:
2426                 return 0;
2427         }
2428 }
2429
2430 void utcp_set_sndbuf(struct utcp_connection *c, void *data, size_t size) {
2431         if(!c) {
2432                 return;
2433         }
2434
2435         set_buffer_storage(&c->sndbuf, data, size);
2436
2437         c->do_poll = is_reliable(c) && buffer_free(&c->sndbuf);
2438 }
2439
2440 size_t utcp_get_rcvbuf(struct utcp_connection *c) {
2441         return c ? c->rcvbuf.maxsize : 0;
2442 }
2443
2444 size_t utcp_get_rcvbuf_free(struct utcp_connection *c) {
2445         if(c && (c->state == ESTABLISHED || c->state == CLOSE_WAIT)) {
2446                 return buffer_free(&c->rcvbuf);
2447         } else {
2448                 return 0;
2449         }
2450 }
2451
2452 void utcp_set_rcvbuf(struct utcp_connection *c, void *data, size_t size) {
2453         if(!c) {
2454                 return;
2455         }
2456
2457         set_buffer_storage(&c->rcvbuf, data, size);
2458 }
2459
2460 size_t utcp_get_sendq(struct utcp_connection *c) {
2461         return c->sndbuf.used;
2462 }
2463
2464 size_t utcp_get_recvq(struct utcp_connection *c) {
2465         return c->rcvbuf.used;
2466 }
2467
2468 bool utcp_get_nodelay(struct utcp_connection *c) {
2469         return c ? c->nodelay : false;
2470 }
2471
2472 void utcp_set_nodelay(struct utcp_connection *c, bool nodelay) {
2473         if(c) {
2474                 c->nodelay = nodelay;
2475         }
2476 }
2477
2478 bool utcp_get_keepalive(struct utcp_connection *c) {
2479         return c ? c->keepalive : false;
2480 }
2481
2482 void utcp_set_keepalive(struct utcp_connection *c, bool keepalive) {
2483         if(c) {
2484                 c->keepalive = keepalive;
2485         }
2486 }
2487
2488 size_t utcp_get_outq(struct utcp_connection *c) {
2489         return c ? seqdiff(c->snd.nxt, c->snd.una) : 0;
2490 }
2491
2492 void utcp_set_recv_cb(struct utcp_connection *c, utcp_recv_t recv) {
2493         if(c) {
2494                 c->recv = recv;
2495         }
2496 }
2497
2498 void utcp_set_poll_cb(struct utcp_connection *c, utcp_poll_t poll) {
2499         if(c) {
2500                 c->poll = poll;
2501                 c->do_poll = is_reliable(c) && buffer_free(&c->sndbuf);
2502         }
2503 }
2504
2505 void utcp_set_accept_cb(struct utcp *utcp, utcp_accept_t accept, utcp_listen_t listen) {
2506         if(utcp) {
2507                 utcp->accept = accept;
2508                 utcp->listen = listen;
2509         }
2510 }
2511
2512 void utcp_expect_data(struct utcp_connection *c, bool expect) {
2513         if(!c || c->reapable) {
2514                 return;
2515         }
2516
2517         if(!(c->state == ESTABLISHED || c->state == FIN_WAIT_1 || c->state == FIN_WAIT_2)) {
2518                 return;
2519         }
2520
2521         if(expect) {
2522                 // If we expect data, start the connection timer.
2523                 if(!timespec_isset(&c->conn_timeout)) {
2524                         clock_gettime(UTCP_CLOCK, &c->conn_timeout);
2525                         c->conn_timeout.tv_sec += c->utcp->timeout;
2526                 }
2527         } else {
2528                 // If we want to cancel expecting data, only clear the timer when there is no unACKed data.
2529                 if(c->snd.una == c->snd.last) {
2530                         timespec_clear(&c->conn_timeout);
2531                 }
2532         }
2533 }
2534
2535 void utcp_set_flags(struct utcp_connection *c, uint32_t flags) {
2536         c->flags &= ~UTCP_CHANGEABLE_FLAGS;
2537         c->flags |= flags & UTCP_CHANGEABLE_FLAGS;
2538 }
2539
2540 void utcp_offline(struct utcp *utcp, bool offline) {
2541         struct timespec now;
2542         clock_gettime(UTCP_CLOCK, &now);
2543
2544         for(int i = 0; i < utcp->nconnections; i++) {
2545                 struct utcp_connection *c = utcp->connections[i];
2546
2547                 if(c->reapable) {
2548                         continue;
2549                 }
2550
2551                 utcp_expect_data(c, offline);
2552
2553                 if(!offline) {
2554                         if(timespec_isset(&c->rtrx_timeout)) {
2555                                 c->rtrx_timeout = now;
2556                         }
2557
2558                         utcp->connections[i]->rtt_start.tv_sec = 0;
2559
2560                         if(c->rto > START_RTO) {
2561                                 c->rto = START_RTO;
2562                         }
2563                 }
2564         }
2565 }
2566
2567 void utcp_set_retransmit_cb(struct utcp *utcp, utcp_retransmit_t cb) {
2568         utcp->retransmit = cb;
2569 }
2570
2571 void utcp_set_clock_granularity(long granularity) {
2572         CLOCK_GRANULARITY = granularity;
2573 }