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