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