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