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